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
feat(mcp): per-group MCP tool access under Admin > AI > Usage controls (#82718)
Aleksandr Lesnenkoc441a839bbe8
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex e66305f07c6..2dd5b1fc8cd 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1371,7 +1371,7 @@metabase.mcp.usagemetabase.mcp.v2.apimetabase.mcp.v2.registry}- :model-exports #{:model/McpSessionLog :model/McpToolCallLog}+ :model-exports #{:model/McpGroupPermission :model/McpSessionLog :model/McpToolCallLog}:uses #{activity-feedai-tracingapi@@ -1490,7 +1490,8 @@metabase.metabot.settingsmetabase.metabot.toolsmetabase.metabot.tools.construct- metabase.metabot.tools.search}+ metabase.metabot.tools.search+ metabase.metabot.usage-controls}:module-exports #{metabot.agent-apimetabot.llmmetabot.slackbot}@@ -3982,16 +3983,23 @@enterprise/mcp{:team "Metabot"- :api #{metabase-enterprise.mcp.init}+ :api #{metabase-enterprise.mcp.api.permissions metabase-enterprise.mcp.init}:uses #{analytics+ api+ app-dblib.schemamcpmetabot+ models+ permissionspremium-featurestaskutil}- :model-imports #{:model/McpSessionLog- :model/McpToolCallLog}}+ :model-imports #{:model/McpGroupPermission+ :model/McpSessionLog+ :model/McpToolCallLog+ :model/PermissionsGroup+ :model/PermissionsGroupMembership}}enterprise/memoize-monitor{:team "Graphy"@@ -4012,9 +4020,7 @@:module-exports #{enterprise/metabot.agent-apienterprise/metabot.analyticsenterprise/metabot.data-complexity-score}- :api #{metabase-enterprise.metabot.api- metabase-enterprise.metabot.api.routes- metabase-enterprise.metabot.init}+ :api #{metabase-enterprise.metabot.api metabase-enterprise.metabot.api.routes metabase-enterprise.metabot.init}:uses #{apilib.schemametabotdiff --git a/docs/ai/mcp-tools.md b/docs/ai/mcp-tools.mdindex ad1c98d00f7..cbaa0e08dc3 100644--- a/docs/ai/mcp-tools.md+++ b/docs/ai/mcp-tools.md@@ -337,7 +337,7 @@ Arguments:| `id` | integer or string | Numeric id of the question to update. 21-character entity_id of the question to update. || `method` | string | One of: `create`, `update`. "create" makes a new question or model (requires `name` and exactly one of `query_handle`, `query`, or `native`); "update" edits the one named by `id`. || `name` | string | Question title. Required on create. |-| `native` | object | A native SQL query to save: {database_id, sql, template_tags?}. Requires the agent:sql:run scope and the mcp-execute-sql-enabled setting. Call learn("native-parameters") before first passing template_tags. |+| `native` | object | A native SQL query to save: {database_id, sql, template_tags?}. Requires the agent:sql:run scope, the mcp-execute-sql-enabled setting, and the execute_sql tool enabled for your groups. Call learn("native-parameters") before first passing template_tags. || `query` | object | An inline query with numeric ids and a top-level database id (learn("query-dialect")). Prefer `query_handle`. || `query_handle` | string | A handle returned by execute_query, execute_sql, or visualize_query. The preferred query source on create: it saves exactly the query that tool validated. || `visualization_settings` | object | Display settings for the chosen `display`; learn("visualization-settings") lists the keys. |diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.cljindex 630dcdd4866..7f81a3c1c42 100644--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj@@ -28,6 +28,7 @@[metabase-enterprise.erd.api][metabase-enterprise.gsheets.api :as gsheets.api][metabase-enterprise.library.api]+ [metabase-enterprise.mcp.api.permissions][metabase-enterprise.metabot-analytics.api][metabase-enterprise.metabot.api][metabase-enterprise.metabot.api.routes]@@ -113,7 +114,12 @@;; Postponing a granular flag for :actions until it's used more widely.{"/action-v2" (premium-handler metabase-enterprise.action-v2.api/routes :table-data-editing)"/advanced-permissions" (premium-handler metabase-enterprise.advanced-permissions.api.routes/routes :advanced-permissions)- "/ai-controls" (premium-handler metabase-enterprise.metabot.api.routes/routes :ai-controls)+ ;; MCP permissions check :ai-controls per endpoint and must come first: the Metabot handler refuses every+ ;; request without the feature, matching or not.+ "/ai-controls" (handlers/routes+ (handlers/route-map-handler+ {"/mcp-permissions" metabase-enterprise.mcp.api.permissions/routes})+ (premium-handler metabase-enterprise.metabot.api.routes/routes :ai-controls))"/audit-app" (premium-handler metabase-enterprise.audit-app.api.routes/routes :audit-app)"/billing" metabase-enterprise.billing.api.routes/routes"/content-diagnostics" (premium-handler metabase-enterprise.content-diagnostics.api/routes :content-diagnostics)diff --git a/enterprise/backend/src/metabase_enterprise/mcp/api/permissions.clj b/enterprise/backend/src/metabase_enterprise/mcp/api/permissions.cljnew file mode 100644index 00000000000..6312174d61c--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mcp/api/permissions.clj@@ -0,0 +1,146 @@+(ns metabase-enterprise.mcp.api.permissions+ "`/api/ee/ai-controls/mcp-permissions` routes for managing which MCP tools each permissions group may use. Every+ route is superuser-only. Setting a group's policy and entering group-level mode need the `:ai-controls` feature;+ reading the policy and switching back to All Users do not, since the rows stay enforced without the feature."+ (:require+ [metabase-enterprise.mcp.db :as mcp.db]+ [metabase.api.common :as api]+ [metabase.api.macros :as api.macros]+ [metabase.api.routes.common :refer [+auth]]+ [metabase.app-db.cluster-lock :as cluster-lock]+ [metabase.mcp.permissions :as mcp.perms]+ [metabase.mcp.v2.api :as mcp.v2.api]+ [metabase.models.interface :as mi]+ [metabase.premium-features.core :as premium-features]+ [metabase.util :as u]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(def ^:private group-permission-schema+ [:map {:closed true}+ [:group_id ms/PositiveInt]+ [:mcp_enabled :boolean]+ [:tool_access ::mcp.perms/tool-access]])++(def ^:private permissions-response-schema+ [:map {:closed true}+ [:advanced :boolean]+ [:tools [:sequential [:map {:closed true}+ [:name :string]+ [:scope :string]+ [:description :string]+ [:default_access [:enum "allowed" "denied"]]]]]+ [:permissions [:sequential group-permission-schema]]])++(def ^:private policy-lock+ "Serializes every write to the MCP tool policy across the cluster, so a PUT validated against one mode can't land+ after a switch to the other, and two PUTs can't both insert a group's first row."+ ::mcp-policy-lock)++(def ^:private no-access-permission+ "What a group with no row gets."+ {:mcp_enabled false :tool_access {}})++(def ^:private seeded-permission+ "What a group gets when a mode switch seeds it: MCP on, every tool at its author's default."+ {:mcp_enabled true :tool_access {}})++(defn- under-current-names+ "`tool-access` with each entry stored under a former tool name (`renamed`, former to current) presented under the+ current name; the current name's own entry wins."+ [renamed tool-access]+ (let [former (select-keys tool-access (keys renamed))]+ (merge (update-keys former renamed)+ (apply dissoc tool-access (keys former)))))++(defn- permissions-response+ "The policy of every group, defaults filled in for groups without a row, with the tool catalog and the mode."+ []+ (let [by-group (u/index-by :group_id (filter mi/can-read? (mcp.db/all-group-permissions)))+ renamed (mcp.v2.api/renamed-tool-names)]+ {:advanced (mcp.db/advanced-mode?)+ :tools (mcp.v2.api/tool-catalog)+ :permissions (mapv (fn [group-id]+ (-> (get by-group group-id no-access-permission)+ (select-keys [:mcp_enabled :tool_access])+ (update :tool_access #(under-current-names renamed %))+ (assoc :group_id group-id)))+ (mcp.db/all-group-ids))}))++(api.macros/defendpoint :get "/" :- permissions-response-schema+ "List the MCP tool policy of every group, with the tools it can name and the current permission mode."+ []+ (api/check-superuser)+ (permissions-response))++(defn- check-writable+ "Throw a 403 unless the current user may write the row of each group in `permissions`, or create one for a group+ that has none."+ [permissions]+ (let [by-group (u/index-by :group_id (mcp.db/all-group-permissions))]+ (doseq [{:keys [group_id] :as permission} permissions]+ (if-let [row (by-group group_id)]+ (api/write-check row)+ (api/create-check :model/McpGroupPermission permission)))))++(defn- check-visible-groups+ "Throw a 400 naming the first `group_id` in `permissions` that is not a group the current mode shows, since such a+ row would take effect unseen on the next mode switch."+ [permissions]+ (let [visible (mcp.db/visible-group-ids (mcp.db/advanced-mode?))]+ (doseq [{:keys [group_id]} permissions]+ (api/check-400 (contains? visible group_id)+ (tru "Unknown group, or one the current permission mode hides: {0}" (str group_id))))))++(api.macros/defendpoint :put "/" :- permissions-response-schema+ "Set the MCP tool policy of the given groups, in one transaction, and return the policy of every group."+ [_route-params+ _query-params+ {:keys [permissions]} :- [:map {:closed true}+ [:permissions [:sequential group-permission-schema]]]]+ (api/check-superuser)+ (premium-features/assert-has-feature :ai-controls (tru "AI Controls"))+ (cluster-lock/with-cluster-lock policy-lock+ (check-writable permissions)+ (check-visible-groups permissions)+ (t2/with-transaction [_conn]+ (doseq [{:keys [group_id] :as permission} permissions]+ (mcp.db/upsert-group-permission! group_id (select-keys permission [:mcp_enabled :tool_access])))))+ (permissions-response))++(defn- switch-mode!+ "Switch permission modes in one transaction: delete the rows of the groups the destination mode hides and seed the+ groups it enables on entry that have no row yet."+ [advanced?]+ (cluster-lock/with-cluster-lock policy-lock+ (run! api/write-check (mcp.db/hidden-group-permissions advanced?))+ (api/create-check :model/McpGroupPermission seeded-permission)+ (t2/with-transaction [_conn]+ (mcp.db/delete-hidden-group-permissions! advanced?)+ (doseq [group-id (mcp.db/seeded-group-ids advanced?)]+ (mcp.db/insert-group-permission-unless-exists! group-id seeded-permission)))))++(api.macros/defendpoint :post "/advanced" :- permissions-response-schema+ "Switch to group-level MCP tool access. Removes the rows of All Users and All tenant users, so access comes only+ from the rows of the other groups, and enables Data Analysts with every tool at its default when it has no row."+ []+ (api/check-superuser)+ (premium-features/assert-has-feature :ai-controls (tru "AI Controls"))+ (switch-mode! true)+ (permissions-response))++(api.macros/defendpoint :delete "/advanced" :- permissions-response-schema+ "Switch back to All Users only. Removes the rows of every group other than Administrators, All Users and All+ tenant users, and enables All Users and All tenant users with every tool at its default, the state the migration+ leaves."+ []+ (api/check-superuser)+ (switch-mode! false)+ (permissions-response))++(def ^{:arglists '([request respond raise])} routes+ "`/api/ee/ai-controls/mcp-permissions` routes."+ (api.macros/ns-handler *ns* +auth))diff --git a/enterprise/backend/src/metabase_enterprise/mcp/db.clj b/enterprise/backend/src/metabase_enterprise/mcp/db.cljindex 5819f652ebd..42bddcbe804 100644--- a/enterprise/backend/src/metabase_enterprise/mcp/db.clj+++ b/enterprise/backend/src/metabase_enterprise/mcp/db.clj@@ -3,11 +3,17 @@additional logic, so the rest of the module never talks to `toucan2.core` itself."(:require[metabase.lib.schema.id :as lib.schema.id]+ [metabase.mcp.permissions :as mcp.perms][metabase.mcp.schema :as mcp.schema]+ [metabase.metabot.usage-controls :as usage-controls]+ [metabase.permissions.core :as perms]+ [metabase.util :as u][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][toucan2.core :as t2]))+(set! *warn-on-reflection* true)+(mu/defn session-log-exists?"Whether an McpSessionLog with `session-id` exists."[session-id :- :string]@@ -49,3 +55,73 @@"Delete the McpSessionLogs created before `cutoff`, returning the number deleted."[cutoff :- ms/TemporalInstant](t2/delete! :model/McpSessionLog {:where [:< :created_at cutoff]}))++(mu/defn advanced-mode? :- :boolean+ "Whether MCP tool access is set per group instead of for All Users only. That is the state in which All Users has no+ McpGroupPermission: the migration seeds one, only entering group-level mode deletes it, and leaving re-seeds it."+ []+ (not (t2/exists? :model/McpGroupPermission :group_id (u/the-id (perms/all-users-group)))))++(mu/defn seeded-group-ids :- [:sequential ms/PositiveInt]+ "The IDs of the groups the mode selected by `advanced?` enables on entry: Data Analysts in group-level mode, All+ Users and All tenant users in simple mode."+ [advanced? :- :boolean]+ (if advanced?+ [(u/the-id (perms/data-analyst-group))]+ (usage-controls/simple-mode-group-ids)))++(mu/defn visible-group-ids :- [:set ms/PositiveInt]+ "The IDs of the groups the mode selected by `advanced?` shows."+ [advanced? :- :boolean]+ (t2/select-pks-set :model/PermissionsGroup {:where (usage-controls/visible-groups-clause :id advanced?)}))++(mu/defn group-permissions-for-user+ "The McpGroupPermission rows of the groups of the User with `user-id`."+ [user-id :- ::lib.schema.id/user]+ (t2/select :model/McpGroupPermission+ {:where [:in :group_id+ ^:allow-subquery+ {:select [:group_id]+ :from [(t2/table-name :model/PermissionsGroupMembership)]+ :where [:= :user_id user-id]}]}))++(mu/defn all-group-ids+ "Every PermissionsGroup id, in ID order."+ []+ (t2/select-pks-vec :model/PermissionsGroup {:order-by [[:id :asc]]}))++(mu/defn all-group-permissions+ "Every McpGroupPermission row, in group order."+ []+ (t2/select :model/McpGroupPermission {:order-by [[:group_id :asc]]}))++(mu/defn upsert-group-permission!+ "Set the McpGroupPermission of the group with `group-id` to `values`, creating the row when the group has none."+ [group-id :- ms/PositiveInt+ values :- [:map {:closed true}+ [:mcp_enabled :boolean]+ [:tool_access ::mcp.perms/tool-access]]]+ (if (t2/exists? :model/McpGroupPermission :group_id group-id)+ (t2/update! :model/McpGroupPermission {:group_id group-id} values)+ (t2/insert! :model/McpGroupPermission (assoc values :group_id group-id))))++(mu/defn insert-group-permission-unless-exists!+ "Give the group with `group-id` an McpGroupPermission with `values` when it has none."+ [group-id :- ms/PositiveInt+ values :- [:map {:closed true}+ [:mcp_enabled :boolean]+ [:tool_access ::mcp.perms/tool-access]]]+ (when-not (t2/exists? :model/McpGroupPermission :group_id group-id)+ (t2/insert! :model/McpGroupPermission (assoc values :group_id group-id))))++(mu/defn hidden-group-permissions+ "The McpGroupPermission rows of the groups the mode selected by `advanced?` hides."+ [advanced? :- :boolean]+ (t2/select :model/McpGroupPermission+ {:where [:not (usage-controls/visible-groups-clause :group_id advanced?)]}))++(mu/defn delete-hidden-group-permissions!+ "Delete the McpGroupPermission rows of the groups the mode selected by `advanced?` hides."+ [advanced? :- :boolean]+ (t2/delete! :model/McpGroupPermission+ {:where [:not (usage-controls/visible-groups-clause :group_id advanced?)]}))diff --git a/enterprise/backend/src/metabase_enterprise/mcp/init.clj b/enterprise/backend/src/metabase_enterprise/mcp/init.cljindex d3bd3c298ca..49dff269369 100644--- a/enterprise/backend/src/metabase_enterprise/mcp/init.clj+++ b/enterprise/backend/src/metabase_enterprise/mcp/init.clj@@ -1,5 +1,6 @@(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)."+ "Startup wiring for the enterprise MCP module: the scheduled MCP usage trimmer and the per-group tool access+ resolver."(:require+ [metabase-enterprise.mcp.permissions][metabase-enterprise.mcp.task.mcp-usage-trimmer]))diff --git a/enterprise/backend/src/metabase_enterprise/mcp/permissions.clj b/enterprise/backend/src/metabase_enterprise/mcp/permissions.cljnew file mode 100644index 00000000000..131f04e6fdf--- /dev/null+++ b/enterprise/backend/src/metabase_enterprise/mcp/permissions.clj@@ -0,0 +1,22 @@+(ns metabase-enterprise.mcp.permissions+ "Enterprise implementation of per-group MCP tool access: collects the `mcp_group_permission` rows of a user's+ groups into their effective policy."+ (:require+ [metabase-enterprise.mcp.db :as mcp.db]+ [metabase.premium-features.core :refer [defenterprise]]))++(set! *warn-on-reflection* true)++(defenterprise effective-policy+ "The effective MCP policy of the User with `user-id`: the `tool_access` of each of their groups that enables MCP,+ so a tool is allowed when any of those groups resolves it to yes. The rows alone decide it: each mode switch+ deletes the rows of the groups the new mode hides, so no request reads the mode."+ ;; Enforced without the `:ai-controls` feature too: losing the license (an expired token, a failed token check)+ ;; must not hand MCP back to the groups an admin turned it off for. The feature gates editing the rows, not reading+ ;; them.+ :feature :none+ [user-id]+ (into []+ (comp (filter :mcp_enabled)+ (map :tool_access))+ (mcp.db/group-permissions-for-user user-id)))diff --git a/enterprise/backend/src/metabase_enterprise/metabot/db.clj b/enterprise/backend/src/metabase_enterprise/metabot/db.cljindex fad5db9cafb..4cd872780ec 100644--- a/enterprise/backend/src/metabase_enterprise/metabot/db.clj+++ b/enterprise/backend/src/metabase_enterprise/metabot/db.clj@@ -4,25 +4,11 @@(:require[metabase.lib.schema.id :as lib.schema.id][metabase.metabot.schema :as metabot.schema]- [metabase.permissions.core :as perms]- [metabase.util :as u]+ [metabase.metabot.usage-controls :as usage-controls][metabase.util.malli :as mu][metabase.util.malli.schema :as ms][toucan2.core :as t2]))-(defn- default-group-ids- "The IDs of the groups visible only in simple mode: All Users and, on tenant instances, All tenant users."- []- [(u/the-id (perms/all-users-group)) (u/the-id (perms/all-external-users-group))])--(defn- visible-groups-expr- "Matches the groups the admin UI shows in the mode selected by `advanced?`: Administrators, All Users, and All- tenant users in simple mode, every other group in group-level mode."- [advanced?]- (if advanced?- [:not-in :group_id (default-group-ids)]- [:in :group_id (conj (default-group-ids) (u/the-id (perms/admin-group)))]))-(mu/defn all-groups"Every PermissionsGroup, in ID order."[]@@ -44,7 +30,7 @@{:select [:group_id]:from [(t2/table-name :model/PermissionsGroupMembership)]:where [:= :user_id user-id]}]- (visible-groups-expr advanced?)]}))+ (usage-controls/visible-groups-clause :group_id advanced?)]}))(mu/defn permission-exists?"Whether the group with `group-id` has a MetabotPermissions row of `perm-type`."@@ -71,7 +57,8 @@(mu/defn delete-hidden-group-permissions!"Delete the MetabotPermissions rows of the groups the mode selected by `advanced?` hides."[advanced? :- :boolean]- (t2/delete! :model/MetabotPermissions {:where [:not (visible-groups-expr advanced?)]}))+ (t2/delete! :model/MetabotPermissions+ {:where [:not (usage-controls/visible-groups-clause :group_id advanced?)]}))(mu/defn group-limits"Every MetabotGroupLimit, in group order."diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.cljindex f5f4659f3a9..767312b3441 100644--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj@@ -112,6 +112,7 @@"ImplicitAction""LoginHistory""McpFeedback"+ "McpGroupPermission""McpQueryHandle""McpSessionLog""McpToolCallLog"diff --git a/enterprise/backend/test/metabase_enterprise/mcp/api/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/mcp/api/permissions_test.cljnew file mode 100644index 00000000000..c34d3b4614b--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mcp/api/permissions_test.clj@@ -0,0 +1,326 @@+(ns metabase-enterprise.mcp.api.permissions-test+ (:require+ [clojure.test :refer [deftest is testing use-fixtures]]+ [metabase-enterprise.mcp.permissions]+ [metabase-enterprise.mcp.test-util :as mcp.tu]+ [metabase.mcp.v2.api]+ [metabase.mcp.v2.registry :as registry]+ [metabase.mcp.v2.test-util :as v2.tu]+ [metabase.permissions.core :as perms]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :db :test-users))++(def ^:private endpoint "ee/ai-controls/mcp-permissions")++(defn- group-permission+ "The `:permissions` entry a response reports for `group-id`."+ [response group-id]+ (u/seek #(= (:group_id %) group-id) (:permissions response)))++(deftest ^:parallel get-permissions-requires-superuser-test+ (mt/with-premium-features #{:ai-controls}+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :get 403 endpoint)))))++(deftest ^:parallel get-permissions-defaults-and-seeds-test+ (mt/with-premium-features #{:ai-controls}+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Rowless Group"}]+ (let [response (mt/user-http-request :crowberto :get 200 endpoint)]+ (testing "a group with no row has no MCP access"+ (is (= {:group_id group-id :mcp_enabled false :tool_access {}}+ (group-permission response group-id))))+ (testing "the migration enabled MCP for the magic groups with every tool at its default"+ (is (= {:group_id (u/the-id (perms/all-users-group)) :mcp_enabled true :tool_access {}}+ (group-permission response (u/the-id (perms/all-users-group))))))+ (testing "the mode rides along"+ (is (boolean? (:advanced response))))))))++(deftest ^:parallel get-permissions-tool-catalog-test+ (mt/with-premium-features #{:ai-controls}+ (let [{:keys [tools]} (mt/user-http-request :crowberto :get 200 endpoint)]+ (is (=? {:name "execute_sql" :scope "agent:sql:run" :description string? :default_access "allowed"}+ (u/seek #(= (:name %) "execute_sql") tools)))+ (testing "a tool's author decides its default"+ (is (= "denied" (:default_access (u/seek #(= (:name %) "test_off_by_default") tools)))))+ (testing "sorted by scope then name, so the admin page can group tools by bucket without re-sorting"+ (is (= (sort-by (juxt :scope :name) tools) tools))))))++(deftest get-permissions-stored-row-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Stored Group"}+ :model/McpGroupPermission _ {:group_id group-id+ :mcp_enabled true+ :tool_access {}}]+ (mcp.tu/store-stale-tool-access! group-id {"execute_sql" "no" "dodo" "yes"})+ (testing "entries come back as stored, a stale name included"+ (is (= {:group_id group-id :mcp_enabled true :tool_access {:execute_sql "no" :dodo "yes"}}+ (group-permission (mt/user-http-request :crowberto :get 200 endpoint) group-id))))))))++(defn- do-with-renamed-tool!+ "Run `thunk` while `test_echo` also answers to the former name `test_ping`."+ [thunk]+ (v2.tu/do-with-temp-tool! (assoc (get @@#'registry/tools* "test_echo") :renamed-from ["test_ping"]) thunk))++(deftest get-permissions-presents-renamed-entry-under-current-name-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (do-with-renamed-tool!+ (fn []+ (mt/with-temp [:model/PermissionsGroup {former-id :id} {:name "Former Name Group"}+ :model/PermissionsGroup {both-id :id} {:name "Both Names Group"}+ :model/McpGroupPermission _ {:group_id former-id+ :mcp_enabled true+ :tool_access {"test_ping" "no"}}+ :model/McpGroupPermission _ {:group_id both-id+ :mcp_enabled true+ :tool_access {"test_ping" "no" "test_echo" "yes"}}]+ (let [response (mt/user-http-request :crowberto :get 200 endpoint)]+ (testing "an entry stored under a former name is presented under the current one"+ (is (= {:test_echo "no"} (:tool_access (group-permission response former-id)))))+ (testing "the current name's own entry wins"+ (is (= {:test_echo "yes"} (:tool_access (group-permission response both-id))))))))))))++(deftest ^:parallel put-permissions-requires-superuser-test+ (mt/with-premium-features #{:ai-controls}+ (is (= "You don't have permissions to do that."+ (mt/user-http-request :rasta :put 403 endpoint+ {:permissions [{:group_id 1 :mcp_enabled true :tool_access {}}]})))))++(deftest put-permissions-upserts-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {group-a :id} {:name "Group A"}+ :model/PermissionsGroup {group-b :id} {:name "Group B"}+ :model/McpGroupPermission _ {:group_id group-b+ :mcp_enabled false+ :tool_access {"search" "no"}}]+ (let [response (mt/user-http-request :crowberto :put 200 endpoint+ {:permissions [{:group_id group-a+ :mcp_enabled true+ :tool_access {"execute_sql" "no"+ "question_write" "yes"}}+ {:group_id group-b+ :mcp_enabled true+ :tool_access {}}]})]+ (testing "a group without a row gets one"+ (is (= {:group_id group-a :mcp_enabled true :tool_access {:execute_sql "no" :question_write "yes"}}+ (group-permission response group-a))))+ (testing "a group with a row has it replaced wholesale, not duplicated or merged"+ (is (= {:group_id group-b :mcp_enabled true :tool_access {}}+ (group-permission response group-b)))+ (is (= 1 (t2/count :model/McpGroupPermission :group_id group-b))))+ (testing "the response is the GET body"+ (is (= (mt/user-http-request :crowberto :get 200 endpoint) response))))))))++(deftest put-permissions-unknown-tool-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Group"}]+ (is (= "Unknown MCP tool: not_a_tool"+ (mt/user-http-request :crowberto :put 400 endpoint+ {:permissions [{:group_id group-id+ :mcp_enabled true+ :tool_access {"not_a_tool" "no"}}]})))+ (testing "nothing was written"+ (is (not (t2/exists? :model/McpGroupPermission :group_id group-id))))))))++(deftest put-permissions-accepts-stored-stale-name-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {stale-id :id} {:name "Stale Group"}+ :model/PermissionsGroup {other-id :id} {:name "Other Group"}+ :model/McpGroupPermission _ {:group_id stale-id+ :mcp_enabled true+ :tool_access {}}]+ (mcp.tu/store-stale-tool-access! stale-id {"dodo" "no"})+ (testing "a name the group already stores is accepted, so an untouched stale entry never blocks a save"+ (is (= {:group_id stale-id :mcp_enabled false :tool_access {:dodo "no"}}+ (group-permission (mt/user-http-request :crowberto :put 200 endpoint+ {:permissions [{:group_id stale-id+ :mcp_enabled false+ :tool_access {"dodo" "no"}}]})+ stale-id))))+ (testing "the same name is refused for a group that does not store it"+ (is (= "Unknown MCP tool: dodo"+ (mt/user-http-request :crowberto :put 400 endpoint+ {:permissions [{:group_id other-id+ :mcp_enabled true+ :tool_access {"dodo" "no"}}]}))))))))++(deftest put-permissions-accepts-former-name-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (do-with-renamed-tool!+ (fn []+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Group"}]+ (is (= {:group_id group-id :mcp_enabled true :tool_access {:test_echo "no"}}+ (group-permission (mt/user-http-request :crowberto :put 200 endpoint+ {:permissions [{:group_id group-id+ :mcp_enabled true+ :tool_access {"test_ping" "no"}}]})+ group-id)))))))))++(deftest ^:parallel put-permissions-rejects-other-access-values-test+ (mt/with-premium-features #{:ai-controls}+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Group"}]+ (is (=? {:errors {:permissions some?}}+ (mt/user-http-request :crowberto :put 400 endpoint+ {:permissions [{:group_id group-id+ :mcp_enabled true+ :tool_access {"execute_sql" "maybe"}}]}))))))++(deftest ^:parallel put-permissions-unknown-group-test+ (mt/with-premium-features #{:ai-controls}+ (let [group-id Integer/MAX_VALUE]+ (is (= (str "Unknown group, or one the current permission mode hides: " group-id)+ (mt/user-http-request :crowberto :put 400 endpoint+ {:permissions [{:group_id group-id+ :mcp_enabled true+ :tool_access {}}]}))))))++(deftest put-permissions-rejects-hidden-group-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-mcp-group-permissions-snapshot+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Hidden Group"}]+ (let [all-users-id (u/the-id (perms/all-users-group))+ refusal #(str "Unknown group, or one the current permission mode hides: " %)+ put! (fn [group-id]+ (mt/user-http-request :crowberto :put 400 endpoint+ {:permissions [{:group_id group-id+ :mcp_enabled true+ :tool_access {}}]}))]+ (testing "simple mode refuses a group it hides, so the row cannot go live unseen on the next switch"+ (is (= (refusal group-id) (put! group-id)))+ (is (not (t2/exists? :model/McpGroupPermission :group_id group-id))))+ (testing "group-level mode refuses All Users, whose row would switch the mode back"+ (mt/user-http-request :crowberto :post 200 "ee/ai-controls/mcp-permissions/advanced")+ (is (= (refusal all-users-id) (put! all-users-id)))+ (is (not (t2/exists? :model/McpGroupPermission :group_id all-users-id)))))))))++(deftest ^:parallel writes-require-ai-controls-feature-test+ (mt/with-premium-features #{}+ (testing "setting a group's policy"+ (mt/assert-has-premium-feature-error "AI Controls" (mt/user-http-request :crowberto :put 402 endpoint+ {:permissions []})))+ (testing "entering group-level mode"+ (mt/assert-has-premium-feature-error+ "AI Controls"+ (mt/user-http-request :crowberto :post 402 "ee/ai-controls/mcp-permissions/advanced")))))++(deftest get-permissions-without-ai-controls-feature-test+ (mcp.tu/with-mcp-group-permissions-snapshot+ (let [all-users-id (u/the-id (perms/all-users-group))]+ (t2/delete! :model/McpGroupPermission)+ (t2/insert! :model/McpGroupPermission {:group_id all-users-id+ :mcp_enabled true+ :tool_access {"execute_sql" "no"}})+ (mt/with-premium-features #{}+ (testing "an admin can still read the policy the rows enforce"+ (let [response (mt/user-http-request :crowberto :get 200 endpoint)]+ (is (=? {:advanced false :tools seq} response))+ (is (= {:group_id all-users-id :mcp_enabled true :tool_access {:execute_sql "no"}}+ (group-permission response all-users-id)))))))))++(deftest disable-advanced-mode-without-ai-controls-feature-test+ (mcp.tu/with-group-level-mode+ (mt/with-premium-features #{}+ (testing "an admin who lost the feature in group-level mode can switch back to All Users"+ (let [all-users-id (u/the-id (perms/all-users-group))+ response (mt/user-http-request :crowberto :delete 200 "ee/ai-controls/mcp-permissions/advanced")]+ (is (false? (:advanced response)))+ (is (= {:group_id all-users-id :mcp_enabled true :tool_access {}}+ (group-permission response all-users-id))))))))++(deftest ^:parallel permissions-require-superuser-without-ai-controls-feature-test+ (mt/with-premium-features #{}+ (doseq [[method path body] [[:get endpoint]+ [:put endpoint {:permissions []}]+ [:post "ee/ai-controls/mcp-permissions/advanced"]+ [:delete "ee/ai-controls/mcp-permissions/advanced"]]]+ (testing (str method " " path)+ (is (= "You don't have permissions to do that."+ (apply mt/user-http-request :rasta method 403 path (when body [body]))))))))++(deftest enable-advanced-mode-test+ (mt/with-premium-features #{:ai-controls}+ (testing "POST /api/ee/ai-controls/mcp-permissions/advanced drops the rows of the simple-mode groups and enables+ Data Analysts"+ (mcp.tu/with-mcp-group-permissions-snapshot+ (t2/delete! :model/McpGroupPermission)+ (let [all-users-id (u/the-id (perms/all-users-group))+ all-external-id (u/the-id (perms/all-external-users-group))+ data-analyst-id (u/the-id (perms/data-analyst-group))]+ (mt/with-temp [:model/McpGroupPermission _ {:group_id all-users-id+ :mcp_enabled true+ :tool_access {}}+ :model/McpGroupPermission _ {:group_id all-external-id+ :mcp_enabled true+ :tool_access {}}]+ (let [response (mt/user-http-request :crowberto :post 200 "ee/ai-controls/mcp-permissions/advanced")]+ (is (true? (:advanced response)))+ (is (= #{data-analyst-id} (t2/select-fn-set :group_id :model/McpGroupPermission))+ "only the groups group-level mode shows have rows")+ (is (= {:group_id all-users-id :mcp_enabled false :tool_access {}}+ (group-permission response all-users-id)))+ (is (= {:group_id data-analyst-id :mcp_enabled true :tool_access {}}+ (group-permission response data-analyst-id))+ "Data Analysts is enabled with every tool at its default"))+ (testing "switching again keeps the admin's Data Analysts edits"+ (mt/user-http-request :crowberto :put 200 endpoint+ {:permissions [{:group_id data-analyst-id+ :mcp_enabled true+ :tool_access {"search" "no"}}]})+ (is (= {:group_id data-analyst-id :mcp_enabled true :tool_access {:search "no"}}+ (group-permission (mt/user-http-request :crowberto :post 200+ "ee/ai-controls/mcp-permissions/advanced")+ data-analyst-id))))))))))++(deftest disable-advanced-mode-test+ (mt/with-premium-features #{:ai-controls}+ (testing "DELETE /api/ee/ai-controls/mcp-permissions/advanced drops the rows of every non-simple-mode group and+ enables All Users and All tenant users"+ (mcp.tu/with-mcp-group-permissions-snapshot+ (t2/delete! :model/McpGroupPermission)+ (let [all-users-id (u/the-id (perms/all-users-group))+ all-external-id (u/the-id (perms/all-external-users-group))+ data-analyst-id (u/the-id (perms/data-analyst-group))]+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Specific Group"}+ :model/McpGroupPermission _ {:group_id data-analyst-id+ :mcp_enabled true+ :tool_access {"search" "no"}}+ :model/McpGroupPermission _ {:group_id group-id+ :mcp_enabled true+ :tool_access {}}]+ (let [response (mt/user-http-request :crowberto :delete 200 "ee/ai-controls/mcp-permissions/advanced")]+ (is (false? (:advanced response)))+ (is (= #{all-users-id all-external-id} (t2/select-fn-set :group_id :model/McpGroupPermission))+ "only the groups simple mode enables have rows")+ (is (= {:group_id all-users-id :mcp_enabled true :tool_access {}}+ (group-permission response all-users-id))+ "All Users is back to MCP on with every tool at its default")+ (is (= {:group_id all-external-id :mcp_enabled true :tool_access {}}+ (group-permission response all-external-id))+ "All tenant users is seeded too"))))))))++(deftest rows-of-both-modes-never-coexist-test+ (mcp.tu/with-mcp-group-permissions-snapshot+ (t2/delete! :model/McpGroupPermission)+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Group"}]+ (let [all-users-id (u/the-id (perms/all-users-group))+ admin-id (u/the-id (perms/admin-group))+ insert! #(t2/insert! :model/McpGroupPermission {:group_id % :mcp_enabled true :tool_access {}})]+ (testing "while All Users has a row, no other group but Administrators gets one"+ (insert! all-users-id)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"while All Users has one" (insert! group-id)))+ (insert! admin-id))+ (testing "while another group has a row, All Users gets none"+ (t2/delete! :model/McpGroupPermission :group_id all-users-id)+ (insert! group-id)+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"while groups have their own" (insert! all-users-id))))))))diff --git a/enterprise/backend/test/metabase_enterprise/mcp/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/mcp/permissions_test.cljnew file mode 100644index 00000000000..97220388afb--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mcp/permissions_test.clj@@ -0,0 +1,170 @@+(ns metabase-enterprise.mcp.permissions-test+ "How a user's effective MCP policy is collected from their groups' `mcp_group_permission` rows."+ (:require+ [clojure.test :refer [deftest is testing use-fixtures]]+ [metabase-enterprise.mcp.db :as mcp.db]+ [metabase-enterprise.mcp.permissions]+ [metabase-enterprise.mcp.test-util :as mcp.tu]+ [metabase.mcp.permissions :as mcp.perms]+ [metabase.mcp.v2.registry :as registry]+ [metabase.mcp.v2.test-util]+ ;; Register execute_sql and question_write, the tools the native-save test denies and calls.+ [metabase.mcp.v2.tools.query]+ [metabase.mcp.v2.tools.question]+ [metabase.permissions.core :as perms]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :db :test-users))++(def ^:private no-access-policy+ [])++(defn- listed-tool-names+ "The names `tools/list` returns for the current user."+ []+ (into #{} (map :name) (registry/list-tools)))++(deftest without-ai-controls-feature-rows-are-still-enforced-test+ (mt/with-premium-features #{}+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}+ :model/PermissionsGroupMembership _ {:group_id group-id+ :user_id (mt/user->id :rasta)}+ :model/McpGroupPermission _ {:group_id group-id+ :mcp_enabled false+ :tool_access {"test_echo" "no"}}]+ (is (= no-access-policy (mcp.perms/effective-policy (mt/user->id :rasta))))))))++(deftest without-ai-controls-feature-seeded-rows-keep-mcp-on-test+ (testing "an instance that never configured MCP tool access keeps MCP, with each tool's default, after losing the+ feature"+ (mt/with-premium-features #{}+ (mcp.tu/with-mcp-group-permissions-snapshot+ (t2/delete! :model/McpGroupPermission)+ (t2/insert! :model/McpGroupPermission {:group_id (u/the-id (perms/all-users-group))+ :mcp_enabled true+ :tool_access {}})+ (mt/with-current-user (mt/user->id :rasta)+ (let [names (listed-tool-names)]+ (is (contains? names "test_echo"))+ (is (not (contains? names "test_off_by_default")))))))))++(deftest stored-entries-override-defaults-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}+ :model/PermissionsGroupMembership _ {:group_id group-id+ :user_id (mt/user->id :rasta)}+ :model/McpGroupPermission _ {:group_id group-id+ :mcp_enabled true+ :tool_access {}}]+ (mcp.tu/store-stale-tool-access! group-id {"search" "no"+ "test_off_by_default" "yes"+ "dodo" "no"})+ (mt/with-current-user (mt/user->id :rasta)+ (testing "the row's map is the policy, string keys and values as stored"+ (is (= [{"search" "no" "test_off_by_default" "yes" "dodo" "no"}] (mcp.perms/policy-for-current-user))))+ (let [names (listed-tool-names)]+ (testing "explicit no hides a tool allowed by default"+ (is (not (contains? names "search"))))+ (testing "explicit yes shows a tool denied by default"+ (is (contains? names "test_off_by_default")))+ (testing "a tool with no entry takes its default"+ (is (contains? names "test_echo")))))))))++(deftest any-enabled-group-allowing-wins-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {denying-id :id} {}+ :model/PermissionsGroup {allowing-id :id} {}+ :model/PermissionsGroup {untouched-id :id} {}+ :model/PermissionsGroupMembership _ {:group_id denying-id+ :user_id (mt/user->id :rasta)}+ :model/PermissionsGroupMembership _ {:group_id allowing-id+ :user_id (mt/user->id :rasta)}+ :model/PermissionsGroupMembership _ {:group_id untouched-id+ :user_id (mt/user->id :rasta)}+ :model/McpGroupPermission _ {:group_id denying-id+ :mcp_enabled true+ :tool_access {"test_echo" "no"+ "search" "no"}}+ :model/McpGroupPermission _ {:group_id allowing-id+ :mcp_enabled true+ :tool_access {"search" "yes"}}+ :model/McpGroupPermission _ {:group_id untouched-id+ :mcp_enabled true+ :tool_access {}}]+ (mt/with-current-user (mt/user->id :rasta)+ (let [names (listed-tool-names)]+ (testing "yes in one group beats no in another"+ (is (contains? names "search")))+ (testing "an untouched group's default allowed beats another group's explicit no"+ (is (contains? names "test_echo")))+ (testing "a tool denied by default stays hidden until some group says yes"+ (is (not (contains? names "test_off_by_default"))))))))))++(deftest disabled-group-contributes-nothing-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}+ :model/PermissionsGroupMembership _ {:group_id group-id+ :user_id (mt/user->id :rasta)}+ :model/McpGroupPermission _ {:group_id group-id+ :mcp_enabled false+ :tool_access {"test_echo" "yes"}}]+ (testing "a disabled group's entries are not read, so its yes enables nothing"+ (is (= no-access-policy (mcp.perms/effective-policy (mt/user->id :rasta)))))+ (testing "a group with no row is the same as a disabled one"+ (mt/with-temp [:model/PermissionsGroup {rowless-id :id} {}+ :model/PermissionsGroupMembership _ {:group_id rowless-id+ :user_id (mt/user->id :rasta)}]+ (is (= no-access-policy (mcp.perms/effective-policy (mt/user->id :rasta))))))))))++(deftest rows-alone-decide-the-policy-test+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-mcp-group-permissions-snapshot+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}+ :model/PermissionsGroupMembership _ {:group_id group-id+ :user_id (mt/user->id :rasta)}]+ (testing "simple mode: All Users' seeded row enables every user"+ (is (= [{}] (mcp.perms/effective-policy (mt/user->id :rasta)))))+ (testing "group-level mode: All Users has no row, so a user in no enabled group has no access"+ (mcp.db/delete-hidden-group-permissions! true)+ (is (= no-access-policy (mcp.perms/effective-policy (mt/user->id :rasta)))))))))++(deftest rows-denying-execute-sql-refuse-a-native-question-test+ (testing "a group row denying execute_sql makes question_write refuse a native save, read from the rows rather+ than a stubbed policy"+ (mt/with-premium-features #{:ai-controls}+ (mcp.tu/with-group-level-mode+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {}+ :model/PermissionsGroupMembership _ {:group_id group-id+ :user_id (mt/user->id :rasta)}+ :model/McpGroupPermission _ {:group_id group-id+ :mcp_enabled true+ :tool_access {"execute_sql" "no"}}]+ (mt/with-model-cleanup [:model/Card]+ (mt/with-current-user (mt/user->id :rasta)+ (let [save! (fn [card-name]+ (:result (registry/call-tool #{"agent:content:write" "agent:sql:run"}+ (str (random-uuid))+ "question_write"+ {:method "create"+ :name card-name+ :native {:database_id (mt/id) :sql "SELECT 1"}})))]+ (testing "denied: refused, naming the tool, and nothing is written"+ (let [result (save! "EE Denied Native Q")]+ (is (:isError result))+ (is (re-find #"needs the \"execute_sql\" tool, which is not enabled for your groups"+ (-> result :content first :text)))+ (is (zero? (t2/count :model/Card :name "EE Denied Native Q")))))+ (testing "allowed once the row says so"+ (t2/update! :model/McpGroupPermission {:group_id group-id} {:tool_access {"execute_sql" "yes"}})+ (let [result (save! "EE Allowed Native Q")]+ (is (not (:isError result)) (-> result :content first :text))+ (is (= 1 (t2/count :model/Card :name "EE Allowed Native Q")))))))))))))diff --git a/enterprise/backend/test/metabase_enterprise/mcp/test_util.clj b/enterprise/backend/test/metabase_enterprise/mcp/test_util.cljnew file mode 100644index 00000000000..6b06a17417a--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/mcp/test_util.clj@@ -0,0 +1,40 @@+(ns metabase-enterprise.mcp.test-util+ "Helpers for tests that change the `mcp_group_permission` rows, which also record the permission mode."+ (:require+ [metabase-enterprise.mcp.db :as mcp.db]+ [metabase.util.json :as json]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(defn do-with-mcp-group-permissions-snapshot!+ "Run `thunk`, then restore every `mcp_group_permission` row to its prior state."+ [thunk]+ (let [snapshot (t2/select :model/McpGroupPermission)]+ (try+ (thunk)+ (finally+ (t2/delete! :model/McpGroupPermission)+ (when (seq snapshot)+ (t2/insert! :mcp_group_permission+ (map #(-> (select-keys % [:group_id :mcp_enabled :tool_access :created_at :updated_at])+ (update :tool_access json/encode))+ snapshot)))))))++(defmacro with-mcp-group-permissions-snapshot+ "Run `body`, then restore every `mcp_group_permission` row to its prior state."+ [& body]+ `(do-with-mcp-group-permissions-snapshot! (fn [] ~@body)))++(defmacro with-group-level-mode+ "Run `body` in group-level mode, with the rows of All Users and All tenant users deleted, then restore every row."+ [& body]+ `(with-mcp-group-permissions-snapshot+ (mcp.db/delete-hidden-group-permissions! true)+ ~@body))++(defn store-stale-tool-access!+ "Give the row of the group with `group-id` the `tool-access` of a row saved before some of its tools were removed,+ writing past the model's check that every name is a registered tool."+ [group-id tool-access]+ (t2/update! :mcp_group_permission {:group_id group-id} {:tool_access (json/encode tool-access)}))diff --git a/enterprise/backend/test/metabase_enterprise/mcp/usage_test.clj b/enterprise/backend/test/metabase_enterprise/mcp/usage_test.cljindex c3b964f1e74..1d2cf59b954 100644--- a/enterprise/backend/test/metabase_enterprise/mcp/usage_test.clj+++ b/enterprise/backend/test/metabase_enterprise/mcp/usage_test.clj@@ -276,11 +276,12 @@(let [sid (str "throw-session-" (mt/random-name))tool-name (str "throwing-" (mt/random-name))](try- (v2.registry/register-tool! {:name tool-name- :scope "agent:content:read"- :description "throws on purpose"- :args [:map]- :handler (fn [_ _] (throw (ex-info "kaboom" {})))})+ (v2.registry/register-tool! {:name tool-name+ :scope "agent:content:read"+ :default-access :allowed+ :description "throws on purpose"+ :args [:map]+ :handler (fn [_ _] (throw (ex-info "kaboom" {})))})(let [{:keys [result error]} (v2.registry/call-tool #{"agent:content:read"} sid tool-name {})](is (or error (:isError result)) "the client sees an error result"))(let [row (t2/select-one :model/McpToolCallLog :tool_name tool-name)]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 283d92819c0..66bc5594d17 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@@ -78,6 +78,7 @@:model/DashboardCardSeries:model/LoginHistory:model/McpFeedback+ :model/McpGroupPermission:model/McpQueryHandle:model/McpSessionLog:model/McpToolCallLogdiff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AiFeatureAccessTable.module.css b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/AccessTable.module.csssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AiFeatureAccessTable.module.cssrename to enterprise/frontend/src/metabase-enterprise/ai-controls/components/AccessTable.module.cssdiff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/AdvancedGroupModeButton.module.css b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/AdvancedGroupModeButton.module.csssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/AdvancedGroupModeButton.module.cssrename to enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/AdvancedGroupModeButton.module.cssdiff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/AdvancedGroupModeButton.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/AdvancedGroupModeButton.tsxnew file mode 100644index 00000000000..d32e9e0d0e1--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/AdvancedGroupModeButton.tsx@@ -0,0 +1,47 @@+import { useDisclosure } from "@mantine/hooks";+import { t } from "ttag";++import { Button } from "metabase/ui";++import type { SwitchAdvancedMode } from "../../types";++import S from "./AdvancedGroupModeButton.module.css";+import { EnableAdvancedModal } from "./EnableAdvancedModal";++type Props = {+ message: string;+ loading: boolean;+ disabled?: boolean;+ onConfirm: SwitchAdvancedMode;+};++export function AdvancedGroupModeButton({+ message,+ loading,+ disabled,+ onConfirm,+}: Props) {+ const [showEnableModal, { toggle: toggleShowEnableModal }] =+ useDisclosure(false);++ return (+ <>+ <Button+ className={S.button}+ disabled={disabled}+ onClick={toggleShowEnableModal}+ size="sm"+ >+ {t`Switch to group-level permissions`}+ </Button>+ {showEnableModal && (+ <EnableAdvancedModal+ message={message}+ loading={loading}+ onConfirm={onConfirm}+ onClose={toggleShowEnableModal}+ />+ )}+ </>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/EnableAdvancedModal.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/EnableAdvancedModal.tsxnew file mode 100644index 00000000000..666c38a0300--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/EnableAdvancedModal.tsx@@ -0,0 +1,42 @@+import { t } from "ttag";++import { ConfirmModal } from "metabase/common/components/ConfirmModal";++import type { SwitchAdvancedMode } from "../../types";++type Props = {+ message: string;+ loading: boolean;+ onConfirm: SwitchAdvancedMode;+ onClose: () => void;+};++export function EnableAdvancedModal({+ message,+ loading,+ onConfirm,+ onClose,+}: Props) {+ const handleConfirm = async () => {+ if (await onConfirm()) {+ onClose();+ }+ };++ return (+ <ConfirmModal+ opened+ onClose={onClose}+ title={t`Switch to group-level permissions?`}+ message={message}+ confirmButtonText={t`Switch`}+ confirmButtonProps={{+ color: "brand",+ variant: "filled",+ loading,+ }}+ closeButtonProps={{ disabled: loading, variant: "subtle" }}+ onConfirm={handleConfirm}+ />+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/index.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/index.tsrename to enterprise/frontend/src/metabase-enterprise/ai-controls/components/AdvancedGroupMode/index.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/GearIconMenu/DisableAdvancedModal.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GearIconMenu/DisableAdvancedModal.tsxsimilarity index 65%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/GearIconMenu/DisableAdvancedModal.tsxrename to enterprise/frontend/src/metabase-enterprise/ai-controls/components/GearIconMenu/DisableAdvancedModal.tsxindex 39758d7c46c..57543902e0f 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/GearIconMenu/DisableAdvancedModal.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GearIconMenu/DisableAdvancedModal.tsx@@ -1,25 +1,20 @@import { t } from "ttag";import { ConfirmModal } from "metabase/common/components/ConfirmModal";-import { useMetadataToasts } from "metabase/common/hooks";import { Text } from "metabase/ui";-import { useDisableAdvancedAIControlsPermissionsMutation } from "metabase-enterprise/api";++import type { SwitchAdvancedMode } from "../../types";type Props = {+ loading: boolean;+ onConfirm: SwitchAdvancedMode;onClose: () => void;};-export function DisableAdvancedModal({ onClose }: Props) {- const [disableAdvanced, { isLoading: loading }] =- useDisableAdvancedAIControlsPermissionsMutation();- const { sendErrorToast } = useMetadataToasts();-+export function DisableAdvancedModal({ loading, onConfirm, onClose }: Props) {const handleConfirm = async () => {- try {- await disableAdvanced().unwrap();+ if (await onConfirm()) {onClose();- } catch {- sendErrorToast(t`Failed to remove group-level access`);}};diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/GearIconMenu/GearIconMenu.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GearIconMenu/GearIconMenu.tsxsimilarity index 69%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/GearIconMenu/GearIconMenu.tsxrename to enterprise/frontend/src/metabase-enterprise/ai-controls/components/GearIconMenu/GearIconMenu.tsxindex cbfa58a13d0..7fdebbdb7e6 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/GearIconMenu/GearIconMenu.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GearIconMenu/GearIconMenu.tsx@@ -3,9 +3,17 @@ import { t } from "ttag";import { ActionIcon, Icon, Menu } from "metabase/ui";+import type { SwitchAdvancedMode } from "../../types";+import { DisableAdvancedModal } from "./DisableAdvancedModal";-export function GearIconMenu() {+type Props = {+ loading: boolean;+ disabled?: boolean;+ onConfirm: SwitchAdvancedMode;+};++export function GearIconMenu({ loading, disabled, onConfirm }: Props) {const [showDisableModal, { toggle: toggleShowDisableModal }] =useDisclosure(false);@@ -17,6 +25,7 @@ export function GearIconMenu() {aria-label={t`Settings`}bd="1px solid var(--mb-color-border-neutral)"c="text-primary"+ disabled={disabled}size="lg"variant="outline">@@ -30,7 +39,11 @@ export function GearIconMenu() {</Menu.Dropdown></Menu>{showDisableModal && (- <DisableAdvancedModal onClose={toggleShowDisableModal} />+ <DisableAdvancedModal+ loading={loading}+ onConfirm={onConfirm}+ onClose={toggleShowDisableModal}+ />)}</>);diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GearIconMenu/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GearIconMenu/index.tsnew file mode 100644index 00000000000..4ac1f0759bf--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GearIconMenu/index.ts@@ -0,0 +1 @@+export { GearIconMenu } from "./GearIconMenu";diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/GroupCategoryTabs.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GroupCategoryTabs/GroupCategoryTabs.tsxsimilarity index 95%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/GroupCategoryTabs.tsxrename to enterprise/frontend/src/metabase-enterprise/ai-controls/components/GroupCategoryTabs/GroupCategoryTabs.tsxindex 9c6b8468173..620dedafcf5 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/GroupCategoryTabs.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GroupCategoryTabs/GroupCategoryTabs.tsx@@ -2,7 +2,7 @@ import { t } from "ttag";import { Button, Group } from "metabase/ui";-import type { GroupTab } from "../utils";+import type { GroupTab } from "../../types";type TabOption = {tab: GroupTab;diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GroupCategoryTabs/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GroupCategoryTabs/index.tsnew file mode 100644index 00000000000..7b43a425ab2--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/GroupCategoryTabs/index.ts@@ -0,0 +1 @@+export { GroupCategoryTabs } from "./GroupCategoryTabs";diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/components/RequireMetabotConfigured.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/RequireMetabotConfigured.tsxindex 942055bb165..e93ca19cd07 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/components/RequireMetabotConfigured.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/RequireMetabotConfigured.tsx@@ -5,24 +5,42 @@ import { useSetting } from "metabase/settings";const FALLBACK_PATH = "/admin/metabot/";-/** Redirects Metabot admin sub-pages to the index until AI is configured. */-export const RequireMetabotConfigured = ({+function RequireEnabled({+ isEnabled,children = <Outlet />,}: {+ isEnabled: boolean;children?: React.ReactNode;-}) => {- const isConfigured = useSetting("llm-metabot-configured?");+}) {const navigate = useNavigate();useLayoutEffect(() => {- if (!isConfigured) {+ if (!isEnabled) {navigate(FALLBACK_PATH, { replace: true });}- }, [isConfigured, navigate]);+ }, [isEnabled, navigate]);- if (!isConfigured) {+ if (!isEnabled) {return null;}return <>{children}</>;+}++export const RequireMetabotConfigured = ({+ children,+}: {+ children?: React.ReactNode;+}) => {+ const isConfigured = useSetting("llm-metabot-configured?");+ return <RequireEnabled isEnabled={!!isConfigured}>{children}</RequireEnabled>;+};++export const RequireMcpEnabled = ({+ children,+}: {+ children?: React.ReactNode;+}) => {+ const isMcpEnabled = useSetting("mcp-enabled?");+ return <RequireEnabled isEnabled={isMcpEnabled}>{children}</RequireEnabled>;};diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/components/RequireMetabotConfigured.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/RequireMetabotConfigured.unit.spec.tsxindex c177767c5d7..332ad063b53 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/components/RequireMetabotConfigured.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/components/RequireMetabotConfigured.unit.spec.tsx@@ -2,15 +2,26 @@ import { createMockSettingsState } from "__support__/state";import { renderWithProviders, screen } from "__support__/ui";import { Route } from "metabase/router";-import { RequireMetabotConfigured } from "./RequireMetabotConfigured";+import {+ RequireMcpEnabled,+ RequireMetabotConfigured,+} from "./RequireMetabotConfigured";const SUB_PAGE_PATH = "/admin/metabot/1/usage-controls/ai-usage-limits";const INDEX_PATH = "/admin/metabot/";-function setup({ configured }: { configured: boolean }) {+function setup({+ gate: Gate = RequireMetabotConfigured,+ configured = true,+ mcpEnabled = true,+}: {+ gate?: typeof RequireMetabotConfigured;+ configured?: boolean;+ mcpEnabled?: boolean;+}) {return renderWithProviders(<>- <Route element={<RequireMetabotConfigured />}>+ <Route element={<Gate />}><Route path={SUB_PAGE_PATH} element={<div>SUB PAGE CONTENT</div>} /></Route><Route path={INDEX_PATH} element={<div>METABOT INDEX</div>} />@@ -21,6 +32,7 @@ function setup({ configured }: { configured: boolean }) {storeInitialState: {settings: createMockSettingsState({"llm-metabot-configured?": configured,+ "mcp-enabled?": mcpEnabled,}),},},@@ -36,7 +48,31 @@ describe("RequireMetabotConfigured", () => {});it("renders the requested sub-page when AI is configured", async () => {- const { router } = setup({ configured: true });+ const { router } = setup({ configured: true, mcpEnabled: false });++ expect(await screen.findByText("SUB PAGE CONTENT")).toBeInTheDocument();+ expect(router?.location.pathname).toBe(SUB_PAGE_PATH);+ });+});++describe("RequireMcpEnabled", () => {+ it("redirects to the AI settings index when the MCP server is off", async () => {+ const { router } = setup({+ gate: RequireMcpEnabled,+ configured: true,+ mcpEnabled: false,+ });++ expect(await screen.findByText("METABOT INDEX")).toBeInTheDocument();+ expect(router?.location.pathname).toBe(INDEX_PATH);+ });++ it("renders the sub-page with only the MCP server on", async () => {+ const { router } = setup({+ gate: RequireMcpEnabled,+ configured: false,+ mcpEnabled: true,+ });expect(await screen.findByText("SUB PAGE CONTENT")).toBeInTheDocument();expect(router?.location.pathname).toBe(SUB_PAGE_PATH);diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.tsindex f1a1149cc90..fa078fcb456 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/index.ts@@ -1,2 +1,4 @@+export { useAccessGroups } from "./useAccessGroups";export { useAdminSettingWithBlurInput } from "./useAdminSettingWithBlurInput";export { useAdminSettingWithDebouncedInput } from "./useAdminSettingWithDebouncedInput";+export { useAdvancedModeSwitch } from "./useAdvancedModeSwitch";diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAccessGroups.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAccessGroups.tsnew file mode 100644index 00000000000..a824149817b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAccessGroups.ts@@ -0,0 +1,49 @@+import { useState } from "react";++import { useListPermissionsGroupsQuery } from "metabase/api";+import { useSetting } from "metabase/settings";+import type { GroupInfo } from "metabase-types/api";++import type { GroupTab } from "../types";++type AccessGroups = {+ isUsingTenants: boolean;+ activeTab: GroupTab;+ setActiveTab: (tab: GroupTab) => void;+ groups: GroupInfo[] | undefined;+ isLoading: boolean;+ error: unknown;+};++export function useAccessGroups(): AccessGroups {+ const isUsingTenants = useSetting("use-tenants");+ const [activeTab, setActiveTab] = useState<GroupTab>("user-groups");++ const {+ data: userGroups,+ isLoading: isLoadingUserGroups,+ error: userGroupsError,+ } = useListPermissionsGroupsQuery(+ isUsingTenants ? { tenancy: "internal" } : undefined,+ );++ const {+ data: tenantGroups,+ isLoading: isLoadingTenantGroups,+ error: tenantGroupsError,+ } = useListPermissionsGroupsQuery(+ isUsingTenants ? { tenancy: "external" } : undefined,+ { skip: !isUsingTenants },+ );++ const isTenantTab = activeTab === "tenant-groups";++ return {+ isUsingTenants,+ activeTab,+ setActiveTab,+ groups: isTenantTab ? tenantGroups : userGroups,+ isLoading: isTenantTab ? isLoadingTenantGroups : isLoadingUserGroups,+ error: isTenantTab ? tenantGroupsError : userGroupsError,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdvancedModeSwitch.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdvancedModeSwitch.tsnew file mode 100644index 00000000000..d83be2f2e4e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/hooks/useAdvancedModeSwitch.ts@@ -0,0 +1,52 @@+import { useCallback } from "react";+import { t } from "ttag";++import { useMetadataToasts } from "metabase/common/hooks";++import type { SwitchAdvancedMode } from "../types";++type AdvancedModeMutation = readonly [+ () => { unwrap: () => Promise<unknown> },+ { isLoading: boolean },+];++type UseAdvancedModeSwitchOptions = {+ enable: AdvancedModeMutation;+ disable: AdvancedModeMutation;+};++type AdvancedModeSwitch = {+ enable: SwitchAdvancedMode;+ disable: SwitchAdvancedMode;+ isEnabling: boolean;+ isDisabling: boolean;+};++export function useAdvancedModeSwitch({+ enable: [enableAdvanced, { isLoading: isEnabling }],+ disable: [disableAdvanced, { isLoading: isDisabling }],+}: UseAdvancedModeSwitchOptions): AdvancedModeSwitch {+ const { sendErrorToast } = useMetadataToasts();++ const enable = useCallback(async () => {+ try {+ await enableAdvanced().unwrap();+ return true;+ } catch {+ sendErrorToast(t`Failed to switch to group-level permissions`);+ return false;+ }+ }, [enableAdvanced, sendErrorToast]);++ const disable = useCallback(async () => {+ try {+ await disableAdvanced().unwrap();+ return true;+ } catch {+ sendErrorToast(t`Failed to remove group-level access`);+ return false;+ }+ }, [disableAdvanced, sendErrorToast]);++ return { enable, disable, isEnabling, isDisabling };+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsxindex 7423e2c7ce7..c308005ab56 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx@@ -5,6 +5,7 @@ import { getAiControlsNavItems, getAiControlsUpsellNavItems } from "./nav";import {getAiControlsRoutes,getAiControlsUpsellRoutes,+ getMcpToolsAccessRoutes,registerAiControlsPagePrefetch,registerAiControlsUpsellPagePrefetch,} from "./routes";@@ -13,11 +14,13 @@ export function initializePlugin() {if (hasPremiumFeature("ai_controls")) {PLUGIN_AI_CONTROLS.isEnabled = true;PLUGIN_AI_CONTROLS.getAiControlsRoutes = getAiControlsRoutes;+ PLUGIN_AI_CONTROLS.getMcpToolsAccessRoutes = getMcpToolsAccessRoutes;PLUGIN_AI_CONTROLS.getAiControlsNavItems = getAiControlsNavItems;registerAiControlsPagePrefetch();} else {PLUGIN_AI_CONTROLS.isEnabled = false;PLUGIN_AI_CONTROLS.getAiControlsRoutes = getAiControlsUpsellRoutes;+ PLUGIN_AI_CONTROLS.getMcpToolsAccessRoutes = () => null;PLUGIN_AI_CONTROLS.getAiControlsNavItems = getAiControlsUpsellNavItems;registerAiControlsUpsellPagePrefetch();}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsxindex eaf51e6cbf3..a70be206a44 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx@@ -14,6 +14,7 @@ export function getAiControlsUpsellNavItems() {function AiControlsNavItems() {const isConfigured = useSetting("llm-metabot-configured?");+ const isMcpEnabled = useSetting("mcp-enabled?");const areAiFeaturesEnabled = useSetting("ai-features-enabled?");if (!areAiFeaturesEnabled) {@@ -26,17 +27,26 @@ function AiControlsNavItems() {icon="lock"label={t`Usage controls`}folderPattern="usage-controls"- disabled={!isConfigured}+ disabled={!isConfigured && !isMcpEnabled}>- <AdminNavItem- label={t`Access`}- path="/admin/metabot/usage-controls/ai-feature-access"- disabled={!isConfigured}- />- <AdminNavItem- label={t`Limits`}- path="/admin/metabot/usage-controls/ai-usage-limits"- />+ {isConfigured && (+ <AdminNavItem+ label={t`AI feature access`}+ path="/admin/metabot/usage-controls/ai-feature-access"+ />+ )}+ {isMcpEnabled && (+ <AdminNavItem+ label={t`MCP tools access`}+ path="/admin/metabot/usage-controls/mcp-tools-access"+ />+ )}+ {isConfigured && (+ <AdminNavItem+ label={t`Limits`}+ path="/admin/metabot/usage-controls/ai-usage-limits"+ />+ )}</AdminNavItem><AdminNavItemicon="palette"diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/AiFeatureAccessPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/AiFeatureAccessPage.tsxnew file mode 100644index 00000000000..c446ceb6aba--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/AiFeatureAccessPage.tsx@@ -0,0 +1,74 @@+import { t } from "ttag";++import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { SettingsPageWrapper } from "metabase/settings-components";+import { Group, Stack, Text, Title } from "metabase/ui";+import {+ useDisableAdvancedAIControlsPermissionsMutation,+ useEnableAdvancedAIControlsPermissionsMutation,+} from "metabase-enterprise/api";++import { GearIconMenu } from "../../components/GearIconMenu";+import { GroupCategoryTabs } from "../../components/GroupCategoryTabs";+import { useAccessGroups, useAdvancedModeSwitch } from "../../hooks";++import { AiFeatureAccessTable } from "./components/AiFeatureAccessTable";+import { useMetabotGroupPermissions } from "./useMetabotGroupPermissions";++export function AiFeatureAccessPage() {+ const groups = useAccessGroups();+ const {+ groupPermissions,+ onPermissionChange,+ advanced,+ error: permissionsError,+ } = useMetabotGroupPermissions();++ const advancedMode = useAdvancedModeSwitch({+ enable: useEnableAdvancedAIControlsPermissionsMutation(),+ disable: useDisableAdvancedAIControlsPermissionsMutation(),+ });++ return (+ <SettingsPageWrapper mt="sm" gap="lg">+ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <Stack gap="sm">+ <Title order={1}>{t`AI feature access`}</Title>+ <Text c="text-secondary" lh={1.5} maw="40rem">+ {t`Choose which AI features each group can use. Administrators always have every feature.`}+ </Text>+ </Stack>+ {advanced && (+ <GearIconMenu+ loading={advancedMode.isDisabling}+ onConfirm={advancedMode.disable}+ />+ )}+ </Group>++ {groups.isUsingTenants && (+ <GroupCategoryTabs+ setActiveTab={groups.setActiveTab}+ activeTab={groups.activeTab}+ />+ )}++ <LoadingAndErrorWrapper+ loading={groups.isLoading}+ error={groups.error || permissionsError}+ >+ {groups.groups && (+ <AiFeatureAccessTable+ groups={groups.groups}+ groupPermissions={groupPermissions}+ onPermissionChange={onPermissionChange}+ advanced={advanced}+ activeTab={groups.activeTab}+ isEnablingAdvanced={advancedMode.isEnabling}+ onEnableAdvanced={advancedMode.enable}+ />+ )}+ </LoadingAndErrorWrapper>+ </SettingsPageWrapper>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/AiFeatureAccessPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/AiFeatureAccessPage.unit.spec.tsxnew file mode 100644index 00000000000..a4263d9d07b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/AiFeatureAccessPage.unit.spec.tsx@@ -0,0 +1,463 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupGroupsEndpoint } from "__support__/server-mocks/group";+import {+ setupMetabotGroupPermissionsEndpoint,+ setupUpdateMetabotGroupPermissionsEndpoint,+} from "__support__/server-mocks/metabot";+import { createMockSettingsState } from "__support__/state";+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";+import { Route } from "metabase/router";+import { AIToolKey, type MetabotGroupPermission } from "metabase-types/api";+import { createMockGroup } from "metabase-types/api/mocks";+import { createMockMetabotGroupPermissions } from "metabase-types/api/mocks/metabot";++import { AiFeatureAccessPage } from "./AiFeatureAccessPage";+import { AiFeatureAccessUpsellPage } from "./AiFeatureAccessUpsellPage";++const FEATURE_ACCESS_PATH = "/admin/metabot/usage-controls/ai-feature-access";+const METABOT_ADVANCED_URL = "path:/api/ee/ai-controls/permissions/advanced";+const MCP_PERMISSIONS_URL = "path:/api/ee/ai-controls/mcp-permissions";++const adminGroup = createMockGroup({+ id: 1,+ name: "Administrators",+ member_count: 1,+ magic_group_type: "admin",+});++const allUsersGroup = createMockGroup({+ id: 2,+ name: "All Users",+ member_count: 5,+ magic_group_type: "all-internal-users",+});++const marketingGroup = createMockGroup({+ id: 3,+ name: "Marketing",+ member_count: 3,+ magic_group_type: null,+});++const defaultGroups = [adminGroup, allUsersGroup, marketingGroup];++function createDefaultPermissions(): MetabotGroupPermission[] {+ return [+ ...createMockMetabotGroupPermissions(adminGroup.id),+ ...createMockMetabotGroupPermissions(allUsersGroup.id, {+ [AIToolKey.SQLGeneration]: "no",+ }),+ ...createMockMetabotGroupPermissions(marketingGroup.id, {+ [AIToolKey.Metabot]: "no",+ [AIToolKey.ChatAndNLQ]: "no",+ [AIToolKey.SQLGeneration]: "no",+ [AIToolKey.OtherTools]: "no",+ }),+ ];+}++function setup({+ permissions = createDefaultPermissions(),+ groups = defaultGroups,+ useTenants = false,+ advanced = false,+}: {+ permissions?: MetabotGroupPermission[];+ groups?: typeof defaultGroups;+ useTenants?: boolean;+ advanced?: boolean;+} = {}) {+ setupGroupsEndpoint(groups);+ setupMetabotGroupPermissionsEndpoint(permissions, advanced);+ setupUpdateMetabotGroupPermissionsEndpoint();+ fetchMock.post(METABOT_ADVANCED_URL, 200);+ fetchMock.delete(METABOT_ADVANCED_URL, 200);++ renderWithProviders(+ <Route path={FEATURE_ACCESS_PATH} element={<AiFeatureAccessPage />} />,+ {+ withRouter: true,+ withUndos: true,+ initialRoute: FEATURE_ACCESS_PATH,+ storeInitialState: {+ settings: createMockSettingsState({+ "use-tenants": useTenants,+ "llm-metabot-configured?": true,+ "mcp-enabled?": true,+ }),+ },+ },+ );+}++function getPermissionRow(groupName: string) {+ return screen.getByRole("row", {+ name: new RegExp(`${groupName} permissions`),+ });+}++function getSwitchModeButton() {+ return screen.getByRole("button", {+ name: "Switch to group-level permissions",+ });+}++describe("AiFeatureAccessPage", () => {+ const originalGetBoundingClientRect =+ HTMLElement.prototype.getBoundingClientRect;++ beforeAll(() => {+ // needed for @tanstack/react-virtual, see https://github.com/TanStack/virtual/issues/29#issuecomment-657519522+ HTMLElement.prototype.getBoundingClientRect = jest+ .fn()+ .mockReturnValue({ height: 400, width: 800, top: 0, left: 0 });+ });++ afterAll(() => {+ HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect;+ });++ it("renders the Metabot table only, with no tab strip and no MCP request", async () => {+ setup();+ await screen.findByTestId("ai-feature-access-table");++ expect(+ screen.getByRole("heading", { name: "AI feature access" }),+ ).toBeInTheDocument();+ expect(screen.queryByRole("tab")).not.toBeInTheDocument();+ expect(screen.queryByRole("tablist")).not.toBeInTheDocument();+ expect(fetchMock.callHistory.called(MCP_PERMISSIONS_URL)).toBe(false);+ });++ it("the switch button posts to the Metabot advanced endpoint", async () => {+ setup();+ await screen.findByTestId("ai-feature-access-table");++ await userEvent.click(getSwitchModeButton());+ const modal = await screen.findByRole("dialog", {+ name: "Switch to group-level permissions?",+ });+ await userEvent.click(+ within(modal).getByRole("button", { name: "Switch" }),+ );++ await waitFor(() =>+ expect(+ fetchMock.callHistory.called(METABOT_ADVANCED_URL, {+ method: "POST",+ }),+ ).toBe(true),+ );+ });++ describe("table", () => {+ it("renders groups with their permission states", async () => {+ setup({ advanced: true });++ expect(+ await screen.findByTestId("ai-feature-access-table"),+ ).toBeInTheDocument();++ expect(screen.getByText("Administrators")).toBeInTheDocument();+ expect(screen.queryByText("All Users")).not.toBeInTheDocument();+ expect(screen.getByText("Marketing")).toBeInTheDocument();+ });++ it("hides non-admin/non-all-users groups in simple mode", async () => {+ setup();++ await screen.findByTestId("ai-feature-access-table");++ expect(screen.getByText("Administrators")).toBeInTheDocument();+ expect(screen.getByText("All Users")).toBeInTheDocument();+ expect(screen.queryByText("Marketing")).not.toBeInTheDocument();+ });++ it("renders column headers for each AI tool", async () => {+ setup();+ await screen.findByTestId("ai-feature-access-table");++ expect(screen.getByText("AI features")).toBeInTheDocument();+ expect(screen.getByText("Chat and NLQ")).toBeInTheDocument();+ expect(screen.getByText("SQL generation")).toBeInTheDocument();+ expect(screen.getByText("Other tools")).toBeInTheDocument();+ });++ it("shows all admin group controls as checked and disabled", async () => {+ setup();+ await screen.findByTestId("ai-feature-access-table");++ const adminRow = getPermissionRow("Administrators");++ const metabotSwitch = within(adminRow).getByRole("switch");+ expect(metabotSwitch).toBeChecked();+ expect(metabotSwitch).toBeDisabled();++ const checkboxes = within(adminRow).getAllByRole("checkbox");+ checkboxes.forEach((checkbox) => {+ expect(checkbox).toBeChecked();+ expect(checkbox).toBeDisabled();+ });+ });++ it("shows correct permission states for a group with mixed permissions", async () => {+ setup();+ await screen.findByTestId("ai-feature-access-table");++ const allUsersRow = getPermissionRow("All Users");++ // Wait for permissions to propagate through the async state pipeline+ await waitFor(() => {+ const metabotSwitch = within(allUsersRow).getByRole("switch");+ expect(metabotSwitch).toBeChecked();+ });++ const sqlCheckbox = within(allUsersRow).getByRole("checkbox", {+ name: /SQL generation/,+ });+ expect(sqlCheckbox).not.toBeChecked();++ const chatCheckbox = within(allUsersRow).getByRole("checkbox", {+ name: /Chat and NLQ/,+ });+ expect(chatCheckbox).toBeChecked();+ });++ it("leaves sub-permission checkboxes enabled when metabot is off for a group", async () => {+ setup({ advanced: true });+ await screen.findByTestId("ai-feature-access-table");++ const marketingRow = getPermissionRow("Marketing");+ const metabotSwitch = within(marketingRow).getByRole("switch");+ expect(metabotSwitch).not.toBeChecked();++ const checkboxes = within(marketingRow).getAllByRole("checkbox");+ checkboxes.forEach((checkbox) => {+ expect(checkbox).toBeEnabled();+ expect(checkbox).not.toBeChecked();+ });+ });++ it("checks every sub-permission when toggling metabot on for a group", async () => {+ setup({ advanced: true });+ await screen.findByTestId("ai-feature-access-table");++ const marketingRow = getPermissionRow("Marketing");+ const metabotSwitch = within(marketingRow).getByRole("switch");++ await userEvent.click(metabotSwitch);++ expect(metabotSwitch).toBeChecked();+ const checkboxes = within(marketingRow).getAllByRole("checkbox");+ checkboxes.forEach((checkbox) => {+ expect(checkbox).toBeEnabled();+ expect(checkbox).toBeChecked();+ });+ });++ it("unchecks every sub-permission when toggling metabot off for a group", async () => {+ setup();+ await screen.findByTestId("ai-feature-access-table");++ const allUsersRow = getPermissionRow("All Users");+ const metabotSwitch = within(allUsersRow).getByRole("switch");++ // Wait for permissions to load so the switch reflects the initial "yes" state+ await waitFor(() => {+ expect(metabotSwitch).toBeChecked();+ });++ await userEvent.click(metabotSwitch);++ expect(metabotSwitch).not.toBeChecked();+ const checkboxes = within(allUsersRow).getAllByRole("checkbox");+ checkboxes.forEach((checkbox) => {+ expect(checkbox).toBeEnabled();+ expect(checkbox).not.toBeChecked();+ });+ });++ it("auto-enables metabot when a tool is checked while metabot is off", async () => {+ setup({ advanced: true });+ await screen.findByTestId("ai-feature-access-table");++ const marketingRow = getPermissionRow("Marketing");+ const metabotSwitch = within(marketingRow).getByRole("switch");+ expect(metabotSwitch).not.toBeChecked();++ const chatCheckbox = within(marketingRow).getByRole("checkbox", {+ name: /Chat and NLQ/,+ });+ await userEvent.click(chatCheckbox);++ expect(metabotSwitch).toBeChecked();+ expect(chatCheckbox).toBeChecked();+ // Other tools should remain unchecked — only the clicked one and metabot flip on+ expect(+ within(marketingRow).getByRole("checkbox", { name: /SQL generation/ }),+ ).not.toBeChecked();+ expect(+ within(marketingRow).getByRole("checkbox", { name: /Other tools/ }),+ ).not.toBeChecked();+ });++ it("auto-disables metabot when the last enabled tool is unchecked", async () => {+ const onlyChatEnabled = [+ ...createMockMetabotGroupPermissions(adminGroup.id),+ ...createMockMetabotGroupPermissions(allUsersGroup.id, {+ [AIToolKey.SQLGeneration]: "no",+ [AIToolKey.OtherTools]: "no",+ }),+ ...createMockMetabotGroupPermissions(marketingGroup.id, {+ [AIToolKey.Metabot]: "no",+ [AIToolKey.ChatAndNLQ]: "no",+ [AIToolKey.SQLGeneration]: "no",+ [AIToolKey.OtherTools]: "no",+ }),+ ];+ setup({ permissions: onlyChatEnabled });+ await screen.findByTestId("ai-feature-access-table");++ const allUsersRow = getPermissionRow("All Users");+ const metabotSwitch = within(allUsersRow).getByRole("switch");+ await waitFor(() => expect(metabotSwitch).toBeChecked());++ const chatCheckbox = within(allUsersRow).getByRole("checkbox", {+ name: /Chat and NLQ/,+ });+ await waitFor(() => expect(chatCheckbox).toBeChecked());++ await userEvent.click(chatCheckbox);++ expect(chatCheckbox).not.toBeChecked();+ expect(metabotSwitch).not.toBeChecked();+ });++ it("does not affect other groups when one group's permissions change", async () => {+ const engineeringGroup = createMockGroup({+ id: 4,+ name: "Engineering",+ member_count: 4,+ magic_group_type: null,+ });+ const permissions = [+ ...createMockMetabotGroupPermissions(adminGroup.id),+ ...createMockMetabotGroupPermissions(allUsersGroup.id),+ ...createMockMetabotGroupPermissions(marketingGroup.id, {+ [AIToolKey.Metabot]: "no",+ [AIToolKey.ChatAndNLQ]: "no",+ [AIToolKey.SQLGeneration]: "no",+ [AIToolKey.OtherTools]: "no",+ }),+ ...createMockMetabotGroupPermissions(engineeringGroup.id),+ ];+ setup({+ advanced: true,+ groups: [...defaultGroups, engineeringGroup],+ permissions,+ });+ await screen.findByTestId("ai-feature-access-table");++ const engineeringRow = getPermissionRow("Engineering");+ const engineeringSwitch = within(engineeringRow).getByRole("switch");+ const engineeringCheckboxes =+ within(engineeringRow).getAllByRole("checkbox");++ // Wait for the fully-enabled engineering row to settle+ await waitFor(() => expect(engineeringSwitch).toBeChecked());+ engineeringCheckboxes.forEach((checkbox) => {+ expect(checkbox).toBeChecked();+ });++ // Auto-enable on a tool in Marketing — would have flipped engineering's metabot+ // in the previous (buggy) implementation that didn't filter by group_id+ const marketingRow = getPermissionRow("Marketing");+ await userEvent.click(+ within(marketingRow).getByRole("checkbox", { name: /Chat and NLQ/ }),+ );++ // Sanity: the change landed on Marketing+ expect(within(marketingRow).getByRole("switch")).toBeChecked();++ // Engineering must remain fully enabled — no cross-group leak+ expect(engineeringSwitch).toBeChecked();+ engineeringCheckboxes.forEach((checkbox) => {+ expect(checkbox).toBeChecked();+ });++ // And the inverse leak: unchecking Marketing's last enabled tool would+ // previously disable Engineering's metabot via the shared cascade path+ await userEvent.click(+ within(marketingRow).getByRole("checkbox", { name: /Chat and NLQ/ }),+ );+ expect(within(marketingRow).getByRole("switch")).not.toBeChecked();+ expect(engineeringSwitch).toBeChecked();+ engineeringCheckboxes.forEach((checkbox) => {+ expect(checkbox).toBeChecked();+ });+ });++ it("does not show tenant tabs when use-tenants is false", async () => {+ setup({ useTenants: false });+ await screen.findByTestId("ai-feature-access-table");++ expect(screen.queryByText("User groups")).not.toBeInTheDocument();+ expect(screen.queryByText("Tenant groups")).not.toBeInTheDocument();+ });++ it("shows tenant tabs when use-tenants is true", async () => {+ setup({ useTenants: true });+ await screen.findByTestId("ai-feature-access-table");++ expect(screen.getByText("User groups")).toBeInTheDocument();+ expect(screen.getByText("Tenant groups")).toBeInTheDocument();+ });++ it("renders the group name next to its AI features switch in the first cell", async () => {+ setup();+ await screen.findByTestId("ai-feature-access-table");++ const adminRow = getPermissionRow("Administrators");+ const gridcell = within(adminRow).getAllByRole("gridcell")[0];+ expect(within(gridcell).getByRole("switch")).toBeInTheDocument();+ expect(within(gridcell).getByText("Administrators")).toBeInTheDocument();+ });++ it("shows the 'Switch to group-level permissions' button in simple mode", async () => {+ setup();+ await screen.findByTestId("ai-feature-access-table");++ expect(+ screen.getByRole("button", {+ name: "Switch to group-level permissions",+ }),+ ).toBeInTheDocument();+ });++ it("hides the 'Switch to group-level permissions' button in advanced mode", async () => {+ setup({ advanced: true });+ await screen.findByTestId("ai-feature-access-table");++ expect(+ screen.queryByRole("button", {+ name: "Switch to group-level permissions",+ }),+ ).not.toBeInTheDocument();+ });+ });+});++describe("AiFeatureAccessUpsellPage", () => {+ it("renders the upsell instead of the table", () => {+ renderWithProviders(<AiFeatureAccessUpsellPage />);++ expect(+ screen.getByText("Set AI usage limits and controls"),+ ).toBeInTheDocument();+ expect(+ screen.queryByTestId("ai-feature-access-table"),+ ).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessUpsellPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/AiFeatureAccessUpsellPage.tsxsimilarity index 91%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessUpsellPage.tsxrename to enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/AiFeatureAccessUpsellPage.tsxindex 95753d541b0..17d8112c81c 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessUpsellPage.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/AiFeatureAccessUpsellPage.tsx@@ -4,7 +4,7 @@ import upsellAiUsageControlsImage from "assets/img/upsell-ai-usage-controls.png"import { MetabotUpsellPage } from "../MetabotUpsellPage";-export function MetabotFeatureAccessUpsellPage() {+export function AiFeatureAccessUpsellPage() {return (<MetabotUpsellPagecampaign="ai-controls-usage-controls"diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AiFeatureAccessTable.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/AiFeatureAccessTable.tsxsimilarity index 64%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AiFeatureAccessTable.tsxrename to enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/AiFeatureAccessTable.tsxindex d8a07c28d06..71017c604c5 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AiFeatureAccessTable.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/AiFeatureAccessTable.tsx@@ -1,39 +1,30 @@import { useMemo } from "react";import { c, t } from "ttag";-import {- isAdminGroup,- isDefaultGroup,- isDefaultTenantGroup,-} from "metabase/common/utils/groups";import { Box, Card, TreeTable } from "metabase/ui";-import { AdvancedGroupModeButton } from "./AdvancedGroupMode";-import S from "./AiFeatureAccessTable.module.css";+import S from "../../../../components/AccessTable.module.css";+import { AdvancedGroupModeButton } from "../../../../components/AdvancedGroupMode";+import { getVisibleGroups } from "../../../../utils";+import { useAiFeaturesTreeTableInstance } from "./useAiFeaturesTreeTableInstance";import type { AiFeatureAccessTableProps } from "./utils";export function AiFeatureAccessTable(props: AiFeatureAccessTableProps) {- const { groups, groupPermissions, advanced, activeTab, onPermissionChange } =- props;-- const visibleGroups = useMemo(() => {- if (advanced) {- return groups.filter(- (group) => !isDefaultGroup(group) && !isDefaultTenantGroup(group),- );- }-- if (activeTab === "tenant-groups") {- return groups.filter(- (group) => isAdminGroup(group) || isDefaultTenantGroup(group),- );- }+ const {+ groups,+ groupPermissions,+ advanced,+ activeTab,+ isEnablingAdvanced,+ onEnableAdvanced,+ onPermissionChange,+ } = props;- return groups.filter(- (group) => isAdminGroup(group) || isDefaultGroup(group),- );- }, [groups, advanced, activeTab]);+ const visibleGroups = useMemo(+ () => getVisibleGroups(groups, advanced, activeTab),+ [groups, advanced, activeTab],+ );const instance = useAiFeaturesTreeTableInstance(visibleGroups,@@ -73,7 +64,11 @@ export function AiFeatureAccessTable(props: AiFeatureAccessTableProps) {/>{showSwitchButton && (<Box className={S.buttonRow}>- <AdvancedGroupModeButton />+ <AdvancedGroupModeButton+ message={t`This will remove all AI feature access from the "All Users" group, so users won't have access to AI features unless they're added to a group that has access.`}+ loading={isEnablingAdvanced}+ onConfirm={onEnableAdvanced}+ /></Box>)}</Card>diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AiFeaturesCell.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/AiFeaturesCell.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AiFeaturesCell.tsxrename to enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/AiFeaturesCell.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AiToolCell.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/AiToolCell.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AiToolCell.tsxrename to enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/AiToolCell.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/index.tssimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/index.tsrename to enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/index.tsdiff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/useAiFeaturesTreeTableInstance.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/useAiFeaturesTreeTableInstance.tsxsimilarity index 100%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/useAiFeaturesTreeTableInstance.tsxrename to enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/useAiFeaturesTreeTableInstance.tsxdiff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/utils.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/utils.tssimilarity index 77%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/utils.tsrename to enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/utils.tsindex e056f3a0398..50fec95fbe0 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/components/AiFeatureAccessTable/utils.ts@@ -4,11 +4,15 @@ import type {MetabotGroupPermission,} from "metabase-types/api";+import type { GroupTab, SwitchAdvancedMode } from "../../../../types";+export type AiFeatureAccessTableProps = {groups: GroupInfo[];groupPermissions: MetabotGroupPermission[];advanced: boolean;- activeTab: "user-groups" | "tenant-groups";+ activeTab: GroupTab;+ isEnablingAdvanced: boolean;+ onEnableAdvanced: SwitchAdvancedMode;onPermissionChange: (groupId: number,toolKey: AIToolKey,diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/index.tsnew file mode 100644index 00000000000..e8f64656849--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/index.ts@@ -0,0 +1,2 @@+export { AiFeatureAccessPage } from "./AiFeatureAccessPage";+export { AiFeatureAccessUpsellPage } from "./AiFeatureAccessUpsellPage";diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/useMetabotGroupPermissions.tssimilarity index 98%rename from enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.tsrename to enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/useMetabotGroupPermissions.tsindex 8dcffb40cb3..2105b98cb16 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.ts+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/AiFeatureAccessPage/useMetabotGroupPermissions.ts@@ -10,8 +10,6 @@ import {} from "metabase-enterprise/api";import { AIToolKey, type MetabotGroupPermission } from "metabase-types/api";-export type GroupTab = "user-groups" | "tenant-groups";-const PERMISSIONS_SAVE_DEBOUNCE = 500;export const useMetabotGroupPermissions = () => {diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/McpToolsAccessPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/McpToolsAccessPage.tsxnew file mode 100644index 00000000000..d1331261b28--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/McpToolsAccessPage.tsx@@ -0,0 +1,139 @@+import { useMemo, useState } from "react";+import { t } from "ttag";++import { LeaveRouteConfirmModal } from "metabase/common/components/LeaveConfirmModal";+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";+import { SettingsPageWrapper } from "metabase/settings-components";+import { Card, Group, Icon, Stack, Text, TextInput, Title } from "metabase/ui";+import {+ useDisableAdvancedMcpToolPermissionsMutation,+ useEnableAdvancedMcpToolPermissionsMutation,+} from "metabase-enterprise/api";+import type { GroupInfo } from "metabase-types/api";++import { AdvancedGroupModeButton } from "../../components/AdvancedGroupMode";+import { GearIconMenu } from "../../components/GearIconMenu";+import { GroupCategoryTabs } from "../../components/GroupCategoryTabs";+import { useAccessGroups, useAdvancedModeSwitch } from "../../hooks";+import { getVisibleGroups } from "../../utils";++import { McpToolsSaveBar } from "./McpToolsSaveBar";+import {+ McpToolsGrid,+ buildGridColumns,+ buildGridRows,+ filterGridColumns,+} from "./components/McpToolsGrid";+import { useMcpToolPermissions } from "./useMcpToolPermissions";++const NO_GROUPS: GroupInfo[] = [];++export function McpToolsAccessPage() {+ const groups = useAccessGroups();+ const mcp = useMcpToolPermissions();+ const advancedMode = useAdvancedModeSwitch({+ enable: useEnableAdvancedMcpToolPermissionsMutation(),+ disable: useDisableAdvancedMcpToolPermissionsMutation(),+ });+ const [query, setQuery] = useState("");++ const rows = useMemo(() => buildGridRows(mcp.tools), [mcp.tools]);+ const columns = useMemo(+ () =>+ buildGridColumns(+ getVisibleGroups(+ groups.groups ?? NO_GROUPS,+ mcp.advanced,+ groups.activeTab,+ ),+ mcp.permissionsByGroup,+ ),+ [groups.groups, groups.activeTab, mcp.advanced, mcp.permissionsByGroup],+ );+ const groupQuery = mcp.advanced ? query : "";+ const visibleColumns = filterGridColumns(columns, groupQuery);++ const showSwitchButton = !mcp.advanced && groups.activeTab === "user-groups";+ const noMatches = visibleColumns.length === 0 && groupQuery.trim() !== "";++ return (+ <SettingsPageWrapper h="100%" mih={0} w="100%" p="xxl" gap="lg">+ <LeaveRouteConfirmModal+ isEnabled={mcp.isDirty}+ onConfirm={mcp.onCancel}+ />++ <Group justify="space-between" align="flex-start" wrap="nowrap">+ <Stack gap="sm">+ <Title order={1}>{t`MCP tools access`}</Title>+ <Text c="text-secondary" lh={1.5} maw="40rem">+ {t`Choose which MCP tools each group's AI clients can use. Administrators always have every tool, and people still need their usual data and collection permissions.`}+ </Text>+ </Stack>+ {mcp.advanced && (+ <GearIconMenu+ loading={advancedMode.isDisabling}+ disabled={mcp.isSaving}+ onConfirm={advancedMode.disable}+ />+ )}+ </Group>++ {groups.isUsingTenants && (+ <GroupCategoryTabs+ setActiveTab={groups.setActiveTab}+ activeTab={groups.activeTab}+ />+ )}++ {mcp.advanced && (+ <TextInput+ leftSection={<Icon name="search" />}+ placeholder={t`Search for a group...`}+ aria-label={t`Search for a group`}+ value={query}+ onChange={(event) => setQuery(event.currentTarget.value)}+ />+ )}++ <LoadingAndErrorWrapper+ loading={groups.isLoading || mcp.isLoading}+ error={groups.error || mcp.error}+ noWrapper+ >+ <Card withBorder p={0} radius="sm" mih={0}>+ {noMatches ? (+ <Text c="text-secondary" p="xl" ta="center">+ {t`No groups match your search`}+ </Text>+ ) : (+ <McpToolsGrid+ rows={rows}+ columns={visibleColumns}+ allTools={mcp.tools}+ disabled={mcp.isSaving}+ headerTrailing={+ showSwitchButton ? (+ <AdvancedGroupModeButton+ message={t`This will remove MCP tool access from the "All Users" group, so users won't have MCP tool access unless they're added to a group that has it.`}+ loading={advancedMode.isEnabling}+ disabled={mcp.isSaving}+ onConfirm={advancedMode.enable}+ />+ ) : undefined+ }+ onPermissionChange={mcp.onPermissionChange}+ />+ )}+ {mcp.isDirty && (+ <McpToolsSaveBar+ isSaving={mcp.isSaving}+ onSave={mcp.onSave}+ onCancel={mcp.onCancel}+ />+ )}+ </Card>+ </LoadingAndErrorWrapper>+ </SettingsPageWrapper>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/McpToolsAccessPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/McpToolsAccessPage.unit.spec.tsxnew file mode 100644index 00000000000..3c1314e545b--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/McpToolsAccessPage.unit.spec.tsx@@ -0,0 +1,733 @@+import userEvent from "@testing-library/user-event";+import fetchMock from "fetch-mock";++import { setupGroupsEndpoint } from "__support__/server-mocks/group";+import {+ setupDisableAdvancedMcpToolPermissionsEndpoint,+ setupEnableAdvancedMcpToolPermissionsEndpoint,+ setupMcpToolPermissionsEndpoint,+ setupUpdateMcpToolPermissionsEndpoint,+} from "__support__/server-mocks/metabot";+import { createMockSettingsState } from "__support__/state";+import {+ act,+ renderWithProviders,+ screen,+ waitFor,+ within,+} from "__support__/ui";+import { Route } from "metabase/router";+import type {+ McpGroupPermission,+ McpTool,+ McpToolPermissionsResponse,+} from "metabase-types/api";+import { createMockGroup } from "metabase-types/api/mocks";+import {+ createMockMcpGroupPermission,+ createMockMcpTool,+ createMockMcpToolPermissionsResponse,+} from "metabase-types/api/mocks/metabot";++import { McpToolsAccessPage } from "./McpToolsAccessPage";++const MCP_TOOLS_ACCESS_PATH = "/admin/metabot/usage-controls/mcp-tools-access";+const USAGE_LIMITS_PATH = "/admin/metabot/usage-controls/ai-usage-limits";+const MCP_PERMISSIONS_URL = "path:/api/ee/ai-controls/mcp-permissions";+const MCP_ADVANCED_URL = "path:/api/ee/ai-controls/mcp-permissions/advanced";++const adminGroup = createMockGroup({+ id: 1,+ name: "Administrators",+ member_count: 1,+ magic_group_type: "admin",+});++const allUsersGroup = createMockGroup({+ id: 2,+ name: "All Users",+ member_count: 5,+ magic_group_type: "all-internal-users",+});++const marketingGroup = createMockGroup({+ id: 3,+ name: "Marketing",+ member_count: 3,+ magic_group_type: null,+});++const engineeringGroup = createMockGroup({+ id: 4,+ name: "Engineering",+ member_count: 4,+ magic_group_type: null,+});++const defaultGroups = [adminGroup, allUsersGroup, marketingGroup];++const mcpTools = [+ createMockMcpTool({+ name: "search",+ scope: "agent:content:read",+ description: "Search for content.",+ }),+ createMockMcpTool({+ name: "run_query",+ scope: "agent:query:run",+ description: "Run a saved question.",+ }),+ createMockMcpTool({+ name: "run_sql",+ scope: "agent:sql:run",+ description: "Run raw SQL against a database.",+ }),+ createMockMcpTool({+ name: "question_write",+ scope: "agent:content:write",+ description: "Create, update, or archive a saved question.",+ }),+ createMockMcpTool({+ name: "segment_write",+ scope: "agent:content:write",+ description: "Create or update a segment.",+ }),+];++function createDefaultMcpPermissions(): McpGroupPermission[] {+ return [+ createMockMcpGroupPermission({ group_id: adminGroup.id }),+ createMockMcpGroupPermission({+ group_id: allUsersGroup.id,+ tool_access: { run_sql: "no" },+ }),+ createMockMcpGroupPermission({+ group_id: marketingGroup.id,+ tool_access: { question_write: "no" },+ }),+ ];+}++function setup({+ mcpPermissions = createDefaultMcpPermissions(),+ tools = mcpTools,+ groups = defaultGroups,+ useTenants = false,+ advanced = false,+}: {+ mcpPermissions?: McpGroupPermission[];+ tools?: McpTool[];+ groups?: typeof defaultGroups;+ useTenants?: boolean;+ advanced?: boolean;+} = {}) {+ setupGroupsEndpoint(groups);++ const response = createMockMcpToolPermissionsResponse({+ advanced,+ tools,+ permissions: mcpPermissions,+ });+ setupMcpToolPermissionsEndpoint(response);+ setupUpdateMcpToolPermissionsEndpoint(response);+ setupEnableAdvancedMcpToolPermissionsEndpoint({+ ...response,+ advanced: true,+ });+ setupDisableAdvancedMcpToolPermissionsEndpoint({+ ...response,+ advanced: false,+ });++ const { router } = renderWithProviders(+ <>+ <Route path={MCP_TOOLS_ACCESS_PATH} element={<McpToolsAccessPage />} />+ <Route path={USAGE_LIMITS_PATH} element={<div>USAGE LIMITS</div>} />+ </>,+ {+ withRouter: true,+ withUndos: true,+ initialRoute: MCP_TOOLS_ACCESS_PATH,+ storeInitialState: {+ settings: createMockSettingsState({+ "use-tenants": useTenants,+ "mcp-enabled?": true,+ }),+ },+ },+ );++ return { response, router };+}++async function findGrid() {+ return screen.findByRole("table", { name: "MCP tools access" });+}++function getHeaderRow() {+ return screen.getAllByRole("row")[0];+}++function queryColumnHeader(name: string) {+ return screen.queryByRole("columnheader", { name });+}++function getToolCheckbox(groupName: string, toolName: string) {+ return screen.getByRole("checkbox", {+ name: `Allow ${groupName} user group to use the ${toolName} MCP tool.`,+ });+}++function getBucketCheckbox(groupName: string, bucketLabel: string) {+ return screen.getByRole("checkbox", {+ name: `Allow ${groupName} user group to use all ${bucketLabel} MCP tools.`,+ });+}++function querySaveButton() {+ return screen.queryByRole("button", { name: "Save changes" });+}++function querySwitchModeButton() {+ return screen.queryByRole("button", {+ name: "Switch to group-level permissions",+ });+}++function querySearchInput() {+ return screen.queryByRole("textbox", { name: "Search for a group" });+}++async function switchToGroupLevelMode() {+ await userEvent.click(+ screen.getByRole("button", { name: "Switch to group-level permissions" }),+ );+ const modal = await screen.findByRole("dialog", {+ name: "Switch to group-level permissions?",+ });+ await userEvent.click(within(modal).getByRole("button", { name: "Switch" }));+}++async function removeGroupLevelAccess() {+ await userEvent.click(screen.getByRole("button", { name: "Settings" }));+ await userEvent.click(+ await screen.findByRole("menuitem", { name: "Remove group-level access" }),+ );+ const modal = await screen.findByRole("dialog", {+ name: "Remove group-level access?",+ });+ await userEvent.click(+ within(modal).getByRole("button", {+ name: "Remove access from all groups",+ }),+ );+}++async function savedPermissions() {+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));+ await waitFor(() =>+ expect(+ fetchMock.callHistory.called(MCP_PERMISSIONS_URL, { method: "PUT" }),+ ).toBe(true),+ );+ const calls = fetchMock.callHistory.calls(MCP_PERMISSIONS_URL, {+ method: "PUT",+ });+ expect(calls).toHaveLength(1);+ const body: { permissions: McpGroupPermission[] } =+ await calls[0].request?.json();+ return body.permissions;+}++describe("McpToolsAccessPage", () => {+ const originalGetBoundingClientRect =+ HTMLElement.prototype.getBoundingClientRect;++ beforeAll(() => {+ // needed for @tanstack/react-virtual, see https://github.com/TanStack/virtual/issues/29#issuecomment-657519522+ HTMLElement.prototype.getBoundingClientRect = jest+ .fn()+ .mockReturnValue({ height: 400, width: 800, top: 0, left: 0 });+ });++ afterAll(() => {+ HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect;+ });++ it("renders the title, the subtitle, and a row per bucket and tool", async () => {+ setup();+ await findGrid();++ expect(+ screen.getByRole("heading", { name: "MCP tools access" }),+ ).toBeInTheDocument();+ expect(+ screen.getByText(/Choose which MCP tools each group's AI clients/),+ ).toBeInTheDocument();+ expect(+ screen.getAllByRole("rowheader").map((cell) => cell.textContent),+ ).toEqual([+ "Read",+ "search",+ "Query",+ "run_query",+ "Raw SQL",+ "run_sql",+ "Write",+ "question_write",+ "segment_write",+ ]);+ });++ it("shows the admin and default groups with the Switch button in the header row in simple mode", async () => {+ setup();+ await findGrid();++ expect(queryColumnHeader("Administrators")).toBeInTheDocument();+ expect(queryColumnHeader("All Users")).toBeInTheDocument();+ expect(queryColumnHeader("Marketing")).not.toBeInTheDocument();+ expect(+ within(getHeaderRow()).getByRole("button", {+ name: "Switch to group-level permissions",+ }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Settings" }),+ ).not.toBeInTheDocument();+ expect(querySearchInput()).not.toBeInTheDocument();+ });++ it("shows every group but the default one, the gear, and the search in group-level mode", async () => {+ setup({ advanced: true });+ await findGrid();++ expect(queryColumnHeader("Administrators")).toBeInTheDocument();+ expect(queryColumnHeader("All Users")).not.toBeInTheDocument();+ expect(queryColumnHeader("Marketing")).toBeInTheDocument();+ expect(querySwitchModeButton()).not.toBeInTheDocument();+ expect(+ screen.getByRole("button", { name: "Settings" }),+ ).toBeInTheDocument();+ expect(querySearchInput()).toBeInTheDocument();+ });++ it("locks Administrators on", async () => {+ setup();+ await findGrid();++ for (const tool of mcpTools) {+ const checkbox = getToolCheckbox("Administrators", tool.name);+ expect(checkbox).toBeChecked();+ expect(checkbox).toBeDisabled();+ }+ });++ it("reads each tool from the group's entries and the tools' defaults", async () => {+ setup();+ await findGrid();++ expect(getToolCheckbox("All Users", "search")).toBeChecked();+ expect(getToolCheckbox("All Users", "run_sql")).not.toBeChecked();+ expect(getToolCheckbox("All Users", "question_write")).toBeChecked();+ expect(getToolCheckbox("All Users", "search")).toBeEnabled();+ });++ it("unchecking a tool denies that tool only", async () => {+ setup();+ await findGrid();+ expect(querySaveButton()).not.toBeInTheDocument();++ await userEvent.click(getToolCheckbox("All Users", "question_write"));++ expect(getToolCheckbox("All Users", "question_write")).not.toBeChecked();+ expect(getToolCheckbox("All Users", "segment_write")).toBeChecked();+ expect(getToolCheckbox("Administrators", "question_write")).toBeChecked();+ expect(+ fetchMock.callHistory.called(MCP_PERMISSIONS_URL, { method: "PUT" }),+ ).toBe(false);+ expect(await savedPermissions()).toEqual([+ {+ group_id: allUsersGroup.id,+ mcp_enabled: true,+ tool_access: { run_sql: "no", question_write: "no" },+ },+ ]);+ });++ it("unchecking the last allowed tool turns the group off and keeps its entries", async () => {+ setup({+ mcpPermissions: [+ createMockMcpGroupPermission({ group_id: adminGroup.id }),+ createMockMcpGroupPermission({+ group_id: allUsersGroup.id,+ tool_access: {+ search: "no",+ run_query: "no",+ run_sql: "no",+ question_write: "no",+ },+ }),+ ],+ });+ await findGrid();+ expect(getToolCheckbox("All Users", "segment_write")).toBeChecked();++ await userEvent.click(getToolCheckbox("All Users", "segment_write"));++ expect(getToolCheckbox("All Users", "segment_write")).not.toBeChecked();+ expect(await savedPermissions()).toEqual([+ {+ group_id: allUsersGroup.id,+ mcp_enabled: false,+ tool_access: {},+ },+ ]);+ });++ it("a tool with a denied default shows unchecked with no entry and checking it writes yes", async () => {+ setup({+ tools: [+ ...mcpTools,+ createMockMcpTool({+ name: "document_write",+ scope: "agent:content:write",+ description: "Create or update a document.",+ default_access: "denied",+ }),+ ],+ });+ await findGrid();+ expect(getToolCheckbox("All Users", "document_write")).not.toBeChecked();++ await userEvent.click(getToolCheckbox("All Users", "document_write"));++ expect(getToolCheckbox("All Users", "document_write")).toBeChecked();+ expect(await savedPermissions()).toEqual([+ {+ group_id: allUsersGroup.id,+ mcp_enabled: true,+ tool_access: { run_sql: "no", document_write: "yes" },+ },+ ]);+ });++ it("an edit on a group without a saved row turns it on with only that tool allowed", async () => {+ setup({+ mcpPermissions: [+ createMockMcpGroupPermission({ group_id: adminGroup.id }),+ ],+ });+ await findGrid();+ for (const tool of mcpTools) {+ expect(getToolCheckbox("All Users", tool.name)).not.toBeChecked();+ }++ await userEvent.click(getToolCheckbox("All Users", "search"));++ expect(getToolCheckbox("All Users", "search")).toBeChecked();+ expect(getToolCheckbox("All Users", "run_query")).not.toBeChecked();+ expect(await savedPermissions()).toEqual([+ {+ group_id: allUsersGroup.id,+ mcp_enabled: true,+ tool_access: {+ run_query: "no",+ run_sql: "no",+ question_write: "no",+ segment_write: "no",+ },+ },+ ]);+ });++ it("checking a bucket allows its tools for that group", async () => {+ setup();+ await findGrid();+ expect(getBucketCheckbox("All Users", "Raw SQL")).not.toBeChecked();++ await userEvent.click(getBucketCheckbox("All Users", "Raw SQL"));++ expect(getBucketCheckbox("All Users", "Raw SQL")).toBeChecked();++ for (const tool of mcpTools) {+ expect(getToolCheckbox("All Users", tool.name)).toBeChecked();+ }+ expect(await savedPermissions()).toEqual([+ {+ group_id: allUsersGroup.id,+ mcp_enabled: true,+ tool_access: {},+ },+ ]);+ });++ it("unchecking and re-checking a tool leaves nothing to save", async () => {+ setup();+ await findGrid();++ await userEvent.click(getToolCheckbox("All Users", "search"));+ await userEvent.click(getToolCheckbox("All Users", "search"));++ expect(+ screen.queryByText("You've made changes to MCP tool access."),+ ).not.toBeInTheDocument();+ });++ it("Cancel restores the saved permissions and hides the bar", async () => {+ setup();+ await findGrid();++ await userEvent.click(getToolCheckbox("All Users", "search"));+ expect(+ screen.getByText("You've made changes to MCP tool access."),+ ).toBeInTheDocument();++ await userEvent.click(screen.getByRole("button", { name: "Cancel" }));++ expect(getToolCheckbox("All Users", "search")).toBeChecked();+ expect(querySaveButton()).not.toBeInTheDocument();+ });++ it("shows the saved state from the PUT body without refetching", async () => {+ setup();+ await findGrid();+ fetchMock.modifyRoute("update-mcp-tool-permissions", {+ response: createMockMcpToolPermissionsResponse({+ tools: mcpTools,+ permissions: createDefaultMcpPermissions().map((permission) =>+ permission.group_id === allUsersGroup.id+ ? { ...permission, tool_access: { run_sql: "no", search: "no" } }+ : permission,+ ),+ }),+ });++ await userEvent.click(getToolCheckbox("All Users", "search"));+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));++ await waitFor(() => expect(querySaveButton()).not.toBeInTheDocument());+ expect(getToolCheckbox("All Users", "search")).not.toBeChecked();+ expect(+ fetchMock.callHistory.calls(MCP_PERMISSIONS_URL, { method: "GET" }),+ ).toHaveLength(1);+ });++ it("disables the checkboxes while a save is in flight", async () => {+ const { response } = setup();+ await findGrid();+ const { promise: savedResponse, resolve: finishSave } =+ Promise.withResolvers<McpToolPermissionsResponse>();+ fetchMock.modifyRoute("update-mcp-tool-permissions", {+ response: savedResponse,+ });++ await userEvent.click(getToolCheckbox("All Users", "search"));+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));++ await waitFor(() =>+ expect(getToolCheckbox("All Users", "run_query")).toBeDisabled(),+ );+ expect(getBucketCheckbox("All Users", "Raw SQL")).toBeDisabled();+ expect(querySwitchModeButton()).toBeDisabled();++ finishSave(response);++ await waitFor(() => expect(querySaveButton()).not.toBeInTheDocument());+ expect(getToolCheckbox("All Users", "run_query")).toBeEnabled();+ expect(getBucketCheckbox("All Users", "Raw SQL")).toBeEnabled();+ expect(querySwitchModeButton()).toBeEnabled();+ });++ it("disables the gear menu while a save is in flight", async () => {+ const { response } = setup({ advanced: true });+ await findGrid();+ const { promise: savedResponse, resolve: finishSave } =+ Promise.withResolvers<McpToolPermissionsResponse>();+ fetchMock.modifyRoute("update-mcp-tool-permissions", {+ response: savedResponse,+ });++ await userEvent.click(getToolCheckbox("Marketing", "search"));+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));++ await waitFor(() =>+ expect(screen.getByRole("button", { name: "Settings" })).toBeDisabled(),+ );++ finishSave(response);++ await waitFor(() => expect(querySaveButton()).not.toBeInTheDocument());+ expect(screen.getByRole("button", { name: "Settings" })).toBeEnabled();+ });++ it("reports a failed save and keeps the draft", async () => {+ setup();+ await findGrid();+ fetchMock.modifyRoute("update-mcp-tool-permissions", {+ response: { status: 500, body: {} },+ });++ await userEvent.click(getToolCheckbox("All Users", "search"));+ await userEvent.click(screen.getByRole("button", { name: "Save changes" }));++ expect(+ await screen.findByText("Failed to save MCP tool permissions"),+ ).toBeInTheDocument();+ expect(getToolCheckbox("All Users", "search")).not.toBeChecked();+ expect(querySaveButton()).toBeInTheDocument();+ });++ it("the switch button posts to the MCP advanced endpoint and drops unsaved edits", async () => {+ const { response } = setup();+ await findGrid();+ await userEvent.click(getToolCheckbox("All Users", "search"));+ expect(querySaveButton()).toBeInTheDocument();++ setupMcpToolPermissionsEndpoint({ ...response, advanced: true });+ await switchToGroupLevelMode();++ await waitFor(() =>+ expect(+ fetchMock.callHistory.called(MCP_ADVANCED_URL, { method: "POST" }),+ ).toBe(true),+ );+ expect(+ await screen.findByRole("columnheader", { name: "Marketing" }),+ ).toBeInTheDocument();+ expect(queryColumnHeader("All Users")).not.toBeInTheDocument();+ expect(querySaveButton()).not.toBeInTheDocument();+ });++ it("edits made before a mode round trip do not come back", async () => {+ const { response } = setup();+ await findGrid();+ await userEvent.click(getToolCheckbox("All Users", "search"));++ setupMcpToolPermissionsEndpoint({ ...response, advanced: true });+ await switchToGroupLevelMode();+ await screen.findByRole("columnheader", { name: "Marketing" });++ setupMcpToolPermissionsEndpoint({ ...response, advanced: false });+ await removeGroupLevelAccess();++ expect(+ await screen.findByRole("columnheader", { name: "All Users" }),+ ).toBeInTheDocument();+ expect(getToolCheckbox("All Users", "search")).toBeChecked();+ expect(querySaveButton()).not.toBeInTheDocument();+ });++ it("the gear menu deletes the MCP advanced endpoint", async () => {+ setup({ advanced: true });+ await findGrid();++ await removeGroupLevelAccess();++ await waitFor(() =>+ expect(+ fetchMock.callHistory.called(MCP_ADVANCED_URL, { method: "DELETE" }),+ ).toBe(true),+ );+ await waitFor(() =>+ expect(+ screen.queryByRole("dialog", { name: "Remove group-level access?" }),+ ).not.toBeInTheDocument(),+ );+ });++ it("the search filters the group columns by name and clearing it restores them", async () => {+ setup({ advanced: true, groups: [...defaultGroups, engineeringGroup] });+ await findGrid();+ expect(queryColumnHeader("Engineering")).toBeInTheDocument();++ const search = screen.getByRole("textbox", { name: "Search for a group" });+ await userEvent.type(search, " mark ");++ expect(queryColumnHeader("Marketing")).toBeInTheDocument();+ expect(queryColumnHeader("Engineering")).not.toBeInTheDocument();+ expect(queryColumnHeader("Administrators")).not.toBeInTheDocument();+ expect(getToolCheckbox("Marketing", "search")).toBeInTheDocument();++ await userEvent.clear(search);++ expect(queryColumnHeader("Administrators")).toBeInTheDocument();+ expect(queryColumnHeader("Marketing")).toBeInTheDocument();+ expect(queryColumnHeader("Engineering")).toBeInTheDocument();+ });++ it("stops filtering by the group search once group-level access is removed", async () => {+ const { response } = setup({ advanced: true });+ await findGrid();+ await userEvent.type(+ screen.getByRole("textbox", { name: "Search for a group" }),+ "marketing",+ );+ expect(queryColumnHeader("Administrators")).not.toBeInTheDocument();++ setupMcpToolPermissionsEndpoint({ ...response, advanced: false });+ await removeGroupLevelAccess();++ expect(+ await screen.findByRole("columnheader", { name: "All Users" }),+ ).toBeInTheDocument();+ expect(queryColumnHeader("Administrators")).toBeInTheDocument();+ expect(+ screen.queryByText("No groups match your search"),+ ).not.toBeInTheDocument();+ });++ it("says when no group matches the search", async () => {+ setup({ advanced: true });+ await findGrid();++ await userEvent.type(+ screen.getByRole("textbox", { name: "Search for a group" }),+ "nobody",+ );++ expect(screen.getByText("No groups match your search")).toBeInTheDocument();+ expect(+ screen.queryByRole("table", { name: "MCP tools access" }),+ ).not.toBeInTheDocument();+ });++ it("asks before leaving with unsaved changes and keeps the draft on Cancel", async () => {+ const { router } = setup();+ await findGrid();+ await userEvent.click(getToolCheckbox("All Users", "search"));++ act(() => {+ router?.navigate(USAGE_LIMITS_PATH);+ });++ const modal = await screen.findByTestId("leave-confirmation");+ await userEvent.click(+ within(modal).getByRole("button", { name: "Cancel" }),+ );++ await waitFor(() =>+ expect(+ screen.queryByTestId("leave-confirmation"),+ ).not.toBeInTheDocument(),+ );+ expect(router?.location.pathname).toBe(MCP_TOOLS_ACCESS_PATH);+ expect(getToolCheckbox("All Users", "search")).not.toBeChecked();+ expect(querySaveButton()).toBeInTheDocument();+ });++ it("shows tenant tabs only when use-tenants is on", async () => {+ setup({ useTenants: true });+ await findGrid();++ expect(screen.getByText("User groups")).toBeInTheDocument();+ expect(screen.getByText("Tenant groups")).toBeInTheDocument();+ });++ it("does not show tenant tabs when use-tenants is off", async () => {+ setup();+ await findGrid();++ expect(screen.queryByText("User groups")).not.toBeInTheDocument();+ expect(screen.queryByText("Tenant groups")).not.toBeInTheDocument();+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/McpToolsSaveBar.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/McpToolsSaveBar.tsxnew file mode 100644index 00000000000..f9a514038f6--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/McpToolsSaveBar.tsx@@ -0,0 +1,35 @@+import { t } from "ttag";++import { Button, Group, Text } from "metabase/ui";++import S from "../../components/AccessTable.module.css";++type McpToolsSaveBarProps = {+ isSaving: boolean;+ onSave: () => void;+ onCancel: () => void;+};++export function McpToolsSaveBar({+ isSaving,+ onSave,+ onCancel,+}: McpToolsSaveBarProps) {+ return (+ <Group+ justify="space-between"+ className={S.buttonRow}+ data-testid="mcp-tool-access-save-bar"+ >+ <Text>{t`You've made changes to MCP tool access.`}</Text>+ <Group gap="sm">+ <Button variant="subtle" disabled={isSaving} onClick={onCancel}>+ {t`Cancel`}+ </Button>+ <Button variant="filled" loading={isSaving} onClick={onSave}>+ {t`Save changes`}+ </Button>+ </Group>+ </Group>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/BucketAccessCell.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/BucketAccessCell.tsxnew file mode 100644index 00000000000..dd366234ddc--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/BucketAccessCell.tsx@@ -0,0 +1,52 @@+import { c } from "ttag";++import { getGroupNameLocalized } from "metabase/common/utils/groups";+import { Checkbox, Flex } from "metabase/ui";+import type { McpGroupPermission, McpTool } from "metabase-types/api";++import S from "./McpToolsGrid.module.css";+import type { McpToolsGridColumn } from "./types";+import { getToolsAccessState, setToolsAllowed } from "./utils";++type BucketAccessCellProps = {+ column: McpToolsGridColumn;+ label: string;+ tools: McpTool[];+ allTools: McpTool[];+ disabled: boolean;+ onPermissionChange: (permission: McpGroupPermission) => void;+};++export function BucketAccessCell({+ column,+ label,+ tools,+ allTools,+ disabled,+ onPermissionChange,+}: BucketAccessCellProps) {+ const { group, permission, isAdminGroup } = column;+ const state = isAdminGroup ? "all" : getToolsAccessState(permission, tools);++ return (+ <td className={S.cell}>+ <Flex justify="center" align="center">+ <Checkbox+ aria-label={c(+ "{0} is the user group name, {1} is a group of MCP tools",+ )+ .t`Allow ${getGroupNameLocalized(group)} user group to use all ${label} MCP tools.`}+ checked={state === "all"}+ indeterminate={state === "some"}+ disabled={disabled || isAdminGroup}+ // A partly allowed bucket allows the rest on click, like a select-all checkbox.+ onChange={() =>+ onPermissionChange(+ setToolsAllowed(permission, allTools, tools, state !== "all"),+ )+ }+ />+ </Flex>+ </td>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGrid.module.css b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGrid.module.cssnew file mode 100644index 00000000000..8749899df0a--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGrid.module.css@@ -0,0 +1,62 @@+.scroller {+ flex: 1 1 auto;+ min-height: 0;+ overflow: auto;+}++.table {+ table-layout: fixed;+ border-collapse: separate;+ border-spacing: 0;+ min-width: 100%;+}++.cell {+ height: 2.5rem;+ padding: 0 1rem;+ border-bottom: 1px solid var(--mb-color-border-neutral-subtle);+ border-right: 1px solid var(--mb-color-border-neutral-subtle);+}++.spacerCell {+ padding: 0;+ border: none;+}++.headerCell {+ position: sticky;+ top: 0;+ z-index: 2;+ background: var(--mb-color-background_page-primary);+ font-weight: bold;+ text-align: center;+}++.cornerCell {+ left: 0;+ z-index: 3;+ color: var(--mb-color-text-secondary);+ text-align: left;+}++.fillerHeaderCell {+ text-align: left;+}++.pinnedCell {+ position: sticky;+ font-weight: normal;+ left: 0;+ z-index: 1;+ background: var(--mb-color-background_page-primary);+ text-align: left;+}++.bucketRow th,+.bucketRow td {+ background: var(--mb-color-background_page-secondary);+}++.fillerCell {+ border-right: none;+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGrid.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGrid.tsxnew file mode 100644index 00000000000..274b6a2a9d3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGrid.tsx@@ -0,0 +1,113 @@+import cx from "classnames";+import type { ReactNode } from "react";+import { t } from "ttag";++import { getGroupNameLocalized } from "metabase/common/utils/groups";+import { Ellipsified } from "metabase/ui";+import type { McpGroupPermission, McpTool } from "metabase-types/api";++import S from "./McpToolsGrid.module.css";+import { McpToolsGridRow } from "./McpToolsGridRow";+import {+ GROUP_COLUMN_WIDTH_PX,+ SWITCH_COLUMN_MIN_WIDTH_PX,+ TOOL_COLUMN_WIDTH_PX,+} from "./constants";+import type { McpToolsGridRow as GridRow, McpToolsGridColumn } from "./types";+import { useGroupColumnVirtualizer } from "./use-group-column-virtualizer";++type McpToolsGridProps = {+ rows: GridRow[];+ columns: McpToolsGridColumn[];+ allTools: McpTool[];+ headerTrailing?: ReactNode;+ disabled: boolean;+ onPermissionChange: (permission: McpGroupPermission) => void;+};++export function McpToolsGrid({+ rows,+ columns,+ allTools,+ headerTrailing,+ disabled,+ onPermissionChange,+}: McpToolsGridProps) {+ const {+ scrollRef,+ virtualColumns,+ leadingSpacerWidth,+ trailingSpacerWidth,+ tableMinWidth,+ } = useGroupColumnVirtualizer(columns.length);+ const tableWidth = headerTrailing+ ? tableMinWidth + SWITCH_COLUMN_MIN_WIDTH_PX+ : tableMinWidth;++ return (+ <div ref={scrollRef} className={S.scroller}>+ <table+ className={S.table}+ style={{ width: tableWidth }}+ aria-label={t`MCP tools access`}+ >+ <colgroup>+ <col style={{ width: TOOL_COLUMN_WIDTH_PX }} />+ <col style={{ width: leadingSpacerWidth }} />+ {virtualColumns.map((virtualColumn) => (+ <col+ key={columns[virtualColumn.index].group.id}+ style={{ width: GROUP_COLUMN_WIDTH_PX }}+ />+ ))}+ <col style={{ width: trailingSpacerWidth }} />+ <col />+ </colgroup>+ <thead>+ <tr>+ <th scope="col" className={cx(S.cell, S.headerCell, S.cornerCell)}>+ {t`MCP tools`}+ </th>+ <td className={S.spacerCell} aria-hidden />+ {virtualColumns.map((virtualColumn) => {+ const { group } = columns[virtualColumn.index];+ return (+ <th+ key={group.id}+ scope="col"+ className={cx(S.cell, S.headerCell)}+ >+ <Ellipsified>{getGroupNameLocalized(group)}</Ellipsified>+ </th>+ );+ })}+ <td className={S.spacerCell} aria-hidden />+ <td+ className={cx(+ S.cell,+ S.headerCell,+ S.fillerHeaderCell,+ S.fillerCell,+ )}+ >+ {headerTrailing}+ </td>+ </tr>+ </thead>+ <tbody>+ {rows.map((row) => (+ <McpToolsGridRow+ key={row.id}+ row={row}+ columns={columns}+ virtualColumns={virtualColumns}+ allTools={allTools}+ disabled={disabled}+ onPermissionChange={onPermissionChange}+ />+ ))}+ </tbody>+ </table>+ </div>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGrid.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGrid.unit.spec.tsxnew file mode 100644index 00000000000..78b6354784f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGrid.unit.spec.tsx@@ -0,0 +1,348 @@+import userEvent from "@testing-library/user-event";+import type { ReactNode } from "react";++import { renderWithProviders, screen, within } from "__support__/ui";+import type { GroupInfo, McpGroupPermission } from "metabase-types/api";+import { createMockGroup } from "metabase-types/api/mocks";+import {+ createMockMcpGroupPermission,+ createMockMcpTool,+} from "metabase-types/api/mocks/metabot";++import { McpToolsGrid } from "./McpToolsGrid";+import {+ GROUP_COLUMN_WIDTH_PX,+ SWITCH_COLUMN_MIN_WIDTH_PX,+ TOOL_COLUMN_WIDTH_PX,+} from "./constants";+import { useGroupColumnVirtualizer } from "./use-group-column-virtualizer";+import { buildGridColumns, buildGridRows, setToolsAllowed } from "./utils";++const search = createMockMcpTool({+ name: "search",+ scope: "agent:content:read",+ description: "Search for content.",+});+const runSql = createMockMcpTool({+ name: "run_sql",+ scope: "agent:sql:run",+ default_access: "denied",+});+const questionWrite = createMockMcpTool({+ name: "question_write",+ scope: "agent:content:write",+});+const transformWrite = createMockMcpTool({+ name: "transform_write",+ scope: "agent:content:write",+});+const tools = [search, runSql, questionWrite, transformWrite];++const adminGroup = createMockGroup({+ id: 1,+ name: "Administrators",+ magic_group_type: "admin",+});+const allUsersGroup = createMockGroup({+ id: 2,+ name: "All Users",+ magic_group_type: "all-internal-users",+});+const marketingGroup = createMockGroup({+ id: 3,+ name: "Marketing",+ magic_group_type: null,+});++const allUsersPermission = createMockMcpGroupPermission({+ group_id: allUsersGroup.id,+ tool_access: { search: "no", transform_write: "no" },+});+const marketingPermission = createMockMcpGroupPermission({+ group_id: marketingGroup.id,+ tool_access: { run_sql: "yes" },+});++type SetupOptions = {+ groups?: GroupInfo[];+ permissionsByGroup?: Record<number, McpGroupPermission>;+ headerTrailing?: ReactNode;+};++function setup({+ groups = [adminGroup, allUsersGroup, marketingGroup],+ permissionsByGroup = {+ [allUsersGroup.id]: allUsersPermission,+ [marketingGroup.id]: marketingPermission,+ },+ headerTrailing,+}: SetupOptions = {}) {+ const onPermissionChange = jest.fn();+ const columns = buildGridColumns(groups, permissionsByGroup);+ renderWithProviders(+ <McpToolsGrid+ rows={buildGridRows(tools)}+ columns={columns}+ allTools={tools}+ headerTrailing={headerTrailing}+ disabled={false}+ onPermissionChange={onPermissionChange}+ />,+ );+ return { onPermissionChange, columns };+}++function getCheckbox(groupName: string, toolName: string) {+ return screen.getByRole("checkbox", {+ name: `Allow ${groupName} user group to use the ${toolName} MCP tool.`,+ });+}++function getBucketCheckbox(groupName: string, bucketLabel: string) {+ return screen.getByRole("checkbox", {+ name: `Allow ${groupName} user group to use all ${bucketLabel} MCP tools.`,+ });+}++type VirtualizerProbeProps = { columnCount: number };++function VirtualizerProbe({ columnCount }: VirtualizerProbeProps) {+ const virtualizer = useGroupColumnVirtualizer(columnCount);+ return (+ <div+ ref={virtualizer.scrollRef}+ data-testid="virtualizer-probe"+ data-rendered={virtualizer.virtualColumns.length}+ data-leading={virtualizer.leadingSpacerWidth}+ data-trailing={virtualizer.trailingSpacerWidth}+ data-table-min-width={virtualizer.tableMinWidth}+ />+ );+}++describe("McpToolsGrid", () => {+ const originalGetBoundingClientRect =+ HTMLElement.prototype.getBoundingClientRect;++ beforeAll(() => {+ // needed for @tanstack/react-virtual, see https://github.com/TanStack/virtual/issues/29#issuecomment-657519522+ HTMLElement.prototype.getBoundingClientRect = jest+ .fn()+ .mockReturnValue({ height: 400, width: 800, top: 0, left: 0 });+ });++ afterAll(() => {+ HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect;+ });++ it("renders a column header per group and a row header per bucket and tool", () => {+ setup();++ expect(+ screen.getAllByRole("columnheader").map((cell) => cell.textContent),+ ).toEqual(["MCP tools", "Administrators", "All Users", "Marketing"]);+ expect(+ screen.getAllByRole("rowheader").map((cell) => cell.textContent),+ ).toEqual([+ "Read",+ "search",+ "Raw SQL",+ "run_sql",+ "Write",+ "question_write",+ "transform_write",+ ]);+ });++ it("renders one checkbox per bucket and tool per group reflecting entries and defaults", () => {+ setup();++ expect(screen.getAllByRole("checkbox")).toHaveLength(+ buildGridRows(tools).length * 3,+ );+ expect(getCheckbox("All Users", "search")).not.toBeChecked();+ expect(getCheckbox("All Users", "run_sql")).not.toBeChecked();+ expect(getCheckbox("All Users", "question_write")).toBeChecked();+ expect(getCheckbox("All Users", "transform_write")).not.toBeChecked();+ expect(getCheckbox("Marketing", "search")).toBeChecked();+ expect(getCheckbox("Marketing", "run_sql")).toBeChecked();+ });++ it("shows Administrators checked and disabled", () => {+ setup();++ for (const tool of tools) {+ const checkbox = getCheckbox("Administrators", tool.name);+ expect(checkbox).toBeChecked();+ expect(checkbox).toBeDisabled();+ }+ });++ it("reports the permission setToolsAllowed derives when a cell is clicked", async () => {+ const { onPermissionChange } = setup();++ await userEvent.click(getCheckbox("All Users", "question_write"));++ expect(onPermissionChange).toHaveBeenCalledTimes(1);+ expect(onPermissionChange).toHaveBeenCalledWith(+ setToolsAllowed(allUsersPermission, tools, [questionWrite], false),+ );+ });++ it("renders group headers as plain text", () => {+ setup();++ expect(+ screen.getByRole("columnheader", { name: "Marketing" }),+ ).toBeInTheDocument();+ expect(+ screen.queryByRole("button", { name: "Marketing" }),+ ).not.toBeInTheDocument();+ });++ describe("bucket checkboxes", () => {+ it("are checked, partly checked, or unchecked by how many of the bucket's tools the group can use", () => {+ setup();++ expect(getBucketCheckbox("All Users", "Read")).not.toBeChecked();+ expect(getBucketCheckbox("All Users", "Write")).toBePartiallyChecked();+ expect(getBucketCheckbox("Marketing", "Read")).toBeChecked();+ expect(getBucketCheckbox("Marketing", "Raw SQL")).toBeChecked();+ expect(getBucketCheckbox("Marketing", "Write")).toBeChecked();+ });++ it("shows Administrators checked and disabled", () => {+ setup();++ for (const label of ["Read", "Raw SQL", "Write"]) {+ const checkbox = getBucketCheckbox("Administrators", label);+ expect(checkbox).toBeChecked();+ expect(checkbox).toBeDisabled();+ }+ });++ it("allows the rest of a partly allowed bucket", async () => {+ const { onPermissionChange } = setup();++ await userEvent.click(getBucketCheckbox("All Users", "Write"));++ expect(onPermissionChange).toHaveBeenCalledWith({+ group_id: allUsersGroup.id,+ mcp_enabled: true,+ tool_access: { search: "no" },+ });+ });++ it("blocks every tool of a fully allowed bucket", async () => {+ const { onPermissionChange } = setup();++ await userEvent.click(getBucketCheckbox("Marketing", "Write"));++ expect(onPermissionChange).toHaveBeenCalledWith({+ group_id: marketingGroup.id,+ mcp_enabled: true,+ tool_access: {+ run_sql: "yes",+ question_write: "no",+ transform_write: "no",+ },+ });+ });++ it("turns a group that is off on with only the bucket's tools", async () => {+ const { onPermissionChange } = setup({+ permissionsByGroup: { [allUsersGroup.id]: allUsersPermission },+ });++ await userEvent.click(getBucketCheckbox("Marketing", "Read"));++ expect(onPermissionChange).toHaveBeenCalledWith({+ group_id: marketingGroup.id,+ mcp_enabled: true,+ tool_access: { question_write: "no", transform_write: "no" },+ });+ });++ it("turns the group off when it blocks the last allowed tools", async () => {+ const { onPermissionChange } = setup({+ permissionsByGroup: {+ [marketingGroup.id]: createMockMcpGroupPermission({+ group_id: marketingGroup.id,+ tool_access: { question_write: "no", transform_write: "no" },+ }),+ },+ });++ await userEvent.click(getBucketCheckbox("Marketing", "Read"));++ expect(onPermissionChange).toHaveBeenCalledWith({+ group_id: marketingGroup.id,+ mcp_enabled: false,+ tool_access: {},+ });+ });+ });++ it("shows the tool description from the info button", async () => {+ setup();++ await userEvent.hover(screen.getByRole("button", { name: "About search" }));++ expect(await screen.findByRole("tooltip")).toHaveTextContent(+ "Search for content.",+ );+ });++ it("renders headerTrailing in the header row and widens the table for it", () => {+ setup({ headerTrailing: <button>Switch</button> });++ const headerRow = screen.getAllByRole("row")[0];+ expect(+ within(headerRow).getByRole("button", { name: "Switch" }),+ ).toBeInTheDocument();+ expect(screen.getByRole("table")).toHaveStyle({+ width: `${TOOL_COLUMN_WIDTH_PX + 3 * GROUP_COLUMN_WIDTH_PX + SWITCH_COLUMN_MIN_WIDTH_PX}px`,+ });+ });++ describe("with 150 groups", () => {+ const manyGroups = Array.from({ length: 150 }, (_, index) =>+ createMockGroup({+ id: index + 10,+ name: `Perf group ${String(index + 1).padStart(3, "0")}`,+ magic_group_type: null,+ }),+ );++ it("renders only the columns near the viewport", () => {+ setup({ groups: manyGroups, permissionsByGroup: {} });++ const headers = screen.getAllByRole("columnheader");+ expect(headers.length).toBeGreaterThan(1);+ expect(headers.length).toBeLessThan(40);+ expect(headers[0]).toHaveTextContent("MCP tools");+ expect(headers[1]).toHaveTextContent("Perf group 001");+ });++ it("keeps the spacers and rendered columns summing to the full group width", () => {+ renderWithProviders(<VirtualizerProbe columnCount={manyGroups.length} />);++ const probe = screen.getByTestId("virtualizer-probe");+ const rendered = Number(probe.getAttribute("data-rendered"));+ const leading = Number(probe.getAttribute("data-leading"));+ const trailing = Number(probe.getAttribute("data-trailing"));+ const groupsTotalWidth = manyGroups.length * GROUP_COLUMN_WIDTH_PX;++ expect(rendered).toBeGreaterThan(0);+ expect(rendered).toBeLessThan(manyGroups.length);+ expect(leading).toBe(0);+ expect(leading + rendered * GROUP_COLUMN_WIDTH_PX + trailing).toBe(+ groupsTotalWidth,+ );+ expect(probe).toHaveAttribute(+ "data-table-min-width",+ String(TOOL_COLUMN_WIDTH_PX + groupsTotalWidth),+ );+ });+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGridRow.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGridRow.tsxnew file mode 100644index 00000000000..52d5fbdc2a0--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/McpToolsGridRow.tsx@@ -0,0 +1,80 @@+import type { VirtualItem } from "@tanstack/react-virtual";+import cx from "classnames";++import { Text } from "metabase/ui";+import type { McpGroupPermission, McpTool } from "metabase-types/api";++import { BucketAccessCell } from "./BucketAccessCell";+import S from "./McpToolsGrid.module.css";+import { ToolAccessCell } from "./ToolAccessCell";+import { ToolNameCell } from "./ToolNameCell";+import type { McpToolsGridRow as GridRow, McpToolsGridColumn } from "./types";++type McpToolsGridRowProps = {+ row: GridRow;+ columns: McpToolsGridColumn[];+ virtualColumns: VirtualItem[];+ allTools: McpTool[];+ disabled: boolean;+ onPermissionChange: (permission: McpGroupPermission) => void;+};++export function McpToolsGridRow({+ row,+ columns,+ virtualColumns,+ allTools,+ disabled,+ onPermissionChange,+}: McpToolsGridRowProps) {+ if (row.kind === "bucket") {+ return (+ <tr className={S.bucketRow}>+ <th scope="row" className={cx(S.cell, S.pinnedCell)}>+ <Text fw="bold" c="text-secondary">+ {row.label}+ </Text>+ </th>+ <td className={S.spacerCell} aria-hidden />+ {virtualColumns.map((virtualColumn) => {+ const column = columns[virtualColumn.index];+ return (+ <BucketAccessCell+ key={column.group.id}+ column={column}+ label={row.label}+ tools={row.tools}+ allTools={allTools}+ disabled={disabled}+ onPermissionChange={onPermissionChange}+ />+ );+ })}+ <td className={S.spacerCell} aria-hidden />+ <td className={cx(S.cell, S.fillerCell)} aria-hidden />+ </tr>+ );+ }++ return (+ <tr>+ <ToolNameCell tool={row.tool} />+ <td className={S.spacerCell} aria-hidden />+ {virtualColumns.map((virtualColumn) => {+ const column = columns[virtualColumn.index];+ return (+ <ToolAccessCell+ key={column.group.id}+ column={column}+ tool={row.tool}+ allTools={allTools}+ disabled={disabled}+ onPermissionChange={onPermissionChange}+ />+ );+ })}+ <td className={S.spacerCell} aria-hidden />+ <td className={cx(S.cell, S.fillerCell)} />+ </tr>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/ToolAccessCell.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/ToolAccessCell.tsxnew file mode 100644index 00000000000..127958875d9--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/ToolAccessCell.tsx@@ -0,0 +1,50 @@+import { c } from "ttag";++import { getGroupNameLocalized } from "metabase/common/utils/groups";+import { Checkbox, Flex } from "metabase/ui";+import type { McpGroupPermission, McpTool } from "metabase-types/api";++import S from "./McpToolsGrid.module.css";+import type { McpToolsGridColumn } from "./types";+import { isToolAllowed, setToolsAllowed } from "./utils";++type ToolAccessCellProps = {+ column: McpToolsGridColumn;+ tool: McpTool;+ allTools: McpTool[];+ disabled: boolean;+ onPermissionChange: (permission: McpGroupPermission) => void;+};++export function ToolAccessCell({+ column,+ tool,+ allTools,+ disabled,+ onPermissionChange,+}: ToolAccessCellProps) {+ const { group, permission, isAdminGroup } = column;++ return (+ <td className={S.cell}>+ <Flex justify="center" align="center">+ <Checkbox+ aria-label={c("{0} is the user group name, {1} is an MCP tool name")+ .t`Allow ${getGroupNameLocalized(group)} user group to use the ${tool.name} MCP tool.`}+ checked={isAdminGroup || isToolAllowed(permission, tool)}+ disabled={disabled || isAdminGroup}+ onChange={(event) =>+ onPermissionChange(+ setToolsAllowed(+ permission,+ allTools,+ [tool],+ event.target.checked,+ ),+ )+ }+ />+ </Flex>+ </td>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/ToolNameCell.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/ToolNameCell.tsxnew file mode 100644index 00000000000..d4894c08b7e--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/ToolNameCell.tsx@@ -0,0 +1,37 @@+import cx from "classnames";+import { c } from "ttag";++import { ActionIcon, Group, Icon, Text, Tooltip } from "metabase/ui";+import type { McpTool } from "metabase-types/api";++import S from "./McpToolsGrid.module.css";++const INFO_ICON_SIZE = 14;+const TOOLTIP_MAX_WIDTH = 320;++type ToolNameCellProps = { tool: McpTool };++export function ToolNameCell({ tool }: ToolNameCellProps) {+ return (+ <th scope="row" className={cx(S.cell, S.pinnedCell)}>+ <Group gap="sm" justify="space-between" wrap="nowrap">+ <Text truncate>{tool.name}</Text>+ <Tooltip+ label={tool.description}+ multiline+ maw={TOOLTIP_MAX_WIDTH}+ position="right"+ >+ <ActionIcon+ variant="subtle"+ size="xs"+ c="text-tertiary"+ aria-label={c("{0} is an MCP tool name").t`About ${tool.name}`}+ >+ <Icon name="info" size={INFO_ICON_SIZE} />+ </ActionIcon>+ </Tooltip>+ </Group>+ </th>+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/constants.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/constants.tsnew file mode 100644index 00000000000..ffad2855c9f--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/constants.ts@@ -0,0 +1,4 @@+export const TOOL_COLUMN_WIDTH_PX = 240;+export const GROUP_COLUMN_WIDTH_PX = 160;+export const SWITCH_COLUMN_MIN_WIDTH_PX = 256;+export const COLUMN_OVERSCAN = 5;diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/index.tsnew file mode 100644index 00000000000..ef8269124bc--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/index.ts@@ -0,0 +1,3 @@+export { McpToolsGrid } from "./McpToolsGrid";+export type { McpToolsGridColumn, McpToolsGridRow } from "./types";+export { buildGridColumns, buildGridRows, filterGridColumns } from "./utils";diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/types.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/types.tsnew file mode 100644index 00000000000..4c4bc2df202--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/types.ts@@ -0,0 +1,21 @@+import type {+ GroupInfo,+ McpGroupPermission,+ McpTool,+} from "metabase-types/api";++export type McpToolsGridRow =+ | {+ kind: "bucket";+ id: string;+ scope: string;+ label: string;+ tools: McpTool[];+ }+ | { kind: "tool"; id: string; tool: McpTool };++export type McpToolsGridColumn = {+ group: GroupInfo;+ permission: McpGroupPermission;+ isAdminGroup: boolean;+};diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/use-group-column-virtualizer.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/use-group-column-virtualizer.tsnew file mode 100644index 00000000000..8064cb87e56--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/use-group-column-virtualizer.ts@@ -0,0 +1,48 @@+import { type VirtualItem, useVirtualizer } from "@tanstack/react-virtual";+import { type RefObject, useRef } from "react";++import {+ COLUMN_OVERSCAN,+ GROUP_COLUMN_WIDTH_PX,+ TOOL_COLUMN_WIDTH_PX,+} from "./constants";++export type GroupColumnVirtualizer = {+ scrollRef: RefObject<HTMLDivElement>;+ virtualColumns: VirtualItem[];+ leadingSpacerWidth: number;+ trailingSpacerWidth: number;+ tableMinWidth: number;+};++export function useGroupColumnVirtualizer(+ columnCount: number,+): GroupColumnVirtualizer {+ const scrollRef = useRef<HTMLDivElement>(null);+ const virtualizer = useVirtualizer({+ horizontal: true,+ count: columnCount,+ getScrollElement: () => scrollRef.current,+ estimateSize: () => GROUP_COLUMN_WIDTH_PX,+ overscan: COLUMN_OVERSCAN,+ scrollMargin: TOOL_COLUMN_WIDTH_PX,+ });++ const virtualColumns = virtualizer.getVirtualItems();+ const first = virtualColumns.at(0);+ const last = virtualColumns.at(-1);+ // Item offsets include scrollMargin; getTotalSize() excludes it.+ const totalSize = virtualizer.getTotalSize();+ const leadingSpacerWidth = first ? first.start - TOOL_COLUMN_WIDTH_PX : 0;+ const trailingSpacerWidth = last+ ? totalSize - (last.end - TOOL_COLUMN_WIDTH_PX)+ : 0;++ return {+ scrollRef,+ virtualColumns,+ leadingSpacerWidth,+ trailingSpacerWidth,+ tableMinWidth: TOOL_COLUMN_WIDTH_PX + totalSize,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/utils.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/utils.tsnew file mode 100644index 00000000000..1b0a326c2d7--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/utils.ts@@ -0,0 +1,202 @@+import { t } from "ttag";+import _ from "underscore";++import {+ getGroupNameLocalized,+ getGroupSortOrder,+ isAdminGroup,+} from "metabase/common/utils/groups";+import type {+ GroupId,+ GroupInfo,+ McpGroupPermission,+ McpTool,+ McpToolAccess,+} from "metabase-types/api";++import type { McpToolsGridColumn, McpToolsGridRow } from "./types";++export type McpToolBucket = { scope: string; tools: McpTool[] };++const SCOPE_LABELS: Record<string, () => string> = {+ "agent:content:read": () => t`Read`,+ "agent:query:run": () => t`Query`,+ "agent:sql:run": () => t`Raw SQL`,+ "agent:content:write": () => t`Write`,+ "agent:delivery:write": () => t`Deliveries`,+};++const SCOPE_ORDER = Object.keys(SCOPE_LABELS);++export function getScopeLabel(scope: string): string {+ return SCOPE_LABELS[scope]?.() ?? scope;+}++export function getDisabledPermission(groupId: GroupId): McpGroupPermission {+ return { group_id: groupId, mcp_enabled: false, tool_access: {} };+}++function resolveToolAccess(+ permission: McpGroupPermission,+ tool: McpTool,+): McpToolAccess {+ return (+ permission.tool_access[tool.name] ??+ (tool.default_access === "allowed" ? "yes" : "no")+ );+}++export function isToolAllowed(+ permission: McpGroupPermission,+ tool: McpTool,+): boolean {+ return (+ permission.mcp_enabled && resolveToolAccess(permission, tool) === "yes"+ );+}++export type ToolsAccessState = "all" | "some" | "none";++export function getToolsAccessState(+ permission: McpGroupPermission,+ tools: McpTool[],+): ToolsAccessState {+ const allowedCount = tools.filter((tool) =>+ isToolAllowed(permission, tool),+ ).length;+ if (allowedCount === 0) {+ return "none";+ }+ return allowedCount === tools.length ? "all" : "some";+}++// A tool set to its author's default gets no entry, so it keeps following the default if that changes.+function withToolsAllowed(+ toolAccess: Record<string, McpToolAccess>,+ tools: McpTool[],+ allowed: boolean,+): Record<string, McpToolAccess> {+ const [atDefault, overridden] = _.partition(+ tools,+ (tool) => (tool.default_access === "allowed") === allowed,+ );+ return {+ ..._.omit(+ toolAccess,+ atDefault.map((tool) => tool.name),+ ),+ ...Object.fromEntries(+ overridden.map((tool): [string, McpToolAccess] => [+ tool.name,+ allowed ? "yes" : "no",+ ]),+ ),+ };+}++function enableGroupWithOnlyTools(+ permission: McpGroupPermission,+ allTools: McpTool[],+ tools: McpTool[],+): McpGroupPermission {+ return {+ ...permission,+ mcp_enabled: true,+ tool_access: withToolsAllowed(+ withToolsAllowed(permission.tool_access, allTools, false),+ tools,+ true,+ ),+ };+}++export function setToolsAllowed(+ permission: McpGroupPermission,+ allTools: McpTool[],+ tools: McpTool[],+ allowed: boolean,+): McpGroupPermission {+ if (allowed && !permission.mcp_enabled) {+ return enableGroupWithOnlyTools(permission, allTools, tools);+ }+ const next: McpGroupPermission = {+ ...permission,+ tool_access: withToolsAllowed(permission.tool_access, tools, allowed),+ };+ if (allowed) {+ return next;+ }+ const anyAllowed = allTools.some(+ (other) => resolveToolAccess(next, other) === "yes",+ );+ return anyAllowed ? next : getDisabledPermission(permission.group_id);+}++function getScopeRank(scope: string): number {+ const index = SCOPE_ORDER.indexOf(scope);+ return index === -1 ? SCOPE_ORDER.length : index;+}++export function groupToolsByScope(tools: McpTool[]): McpToolBucket[] {+ const toolsByScope = new Map<string, McpTool[]>();+ for (const tool of tools) {+ const scopeTools = toolsByScope.get(tool.scope);+ if (scopeTools) {+ scopeTools.push(tool);+ } else {+ toolsByScope.set(tool.scope, [tool]);+ }+ }++ return [...toolsByScope.entries()]+ .sort(([a], [b]) => getScopeRank(a) - getScopeRank(b))+ .map(([scope, scopeTools]) => ({ scope, tools: scopeTools }));+}++export function buildGridRows(tools: McpTool[]): McpToolsGridRow[] {+ return groupToolsByScope(tools).flatMap<McpToolsGridRow>((bucket) => [+ {+ kind: "bucket",+ id: `bucket:${bucket.scope}`,+ scope: bucket.scope,+ label: getScopeLabel(bucket.scope),+ tools: bucket.tools,+ },+ ...bucket.tools.map<McpToolsGridRow>((tool) => ({+ kind: "tool",+ id: `tool:${tool.name}`,+ tool,+ })),+ ]);+}++function compareGroups(a: GroupInfo, b: GroupInfo): number {+ return (+ getGroupSortOrder(a) - getGroupSortOrder(b) ||+ getGroupNameLocalized(a).localeCompare(getGroupNameLocalized(b))+ );+}++export function buildGridColumns(+ groups: GroupInfo[],+ permissionsByGroup: Record<GroupId, McpGroupPermission>,+): McpToolsGridColumn[] {+ return [...groups].sort(compareGroups).map((group) => ({+ group,+ permission: permissionsByGroup[group.id] ?? getDisabledPermission(group.id),+ isAdminGroup: isAdminGroup(group),+ }));+}++export function filterGridColumns(+ columns: McpToolsGridColumn[],+ query: string,+): McpToolsGridColumn[] {+ const needle = query.trim().toLowerCase();+ if (needle === "") {+ return columns;+ }+ return columns.filter((column) =>+ getGroupNameLocalized(column.group).toLowerCase().includes(needle),+ );+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/utils.unit.spec.tsnew file mode 100644index 00000000000..59025dca51c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/components/McpToolsGrid/utils.unit.spec.ts@@ -0,0 +1,388 @@+import { createMockGroup } from "metabase-types/api/mocks";+import {+ createMockMcpGroupPermission,+ createMockMcpTool,+} from "metabase-types/api/mocks/metabot";++import {+ buildGridColumns,+ buildGridRows,+ filterGridColumns,+ getDisabledPermission,+ getScopeLabel,+ getToolsAccessState,+ groupToolsByScope,+ isToolAllowed,+ setToolsAllowed,+} from "./utils";++const search = createMockMcpTool({+ name: "search",+ scope: "agent:content:read",+});+const runQuery = createMockMcpTool({+ name: "run_query",+ scope: "agent:query:run",+});+const runSql = createMockMcpTool({+ name: "run_sql",+ scope: "agent:sql:run",+ default_access: "denied",+});+const questionWrite = createMockMcpTool({+ name: "question_write",+ scope: "agent:content:write",+});+const transformWrite = createMockMcpTool({+ name: "transform_write",+ scope: "agent:content:write",+});+const allTools = [questionWrite, search, runSql, runQuery, transformWrite];+const writeTools = [questionWrite, transformWrite];++const enabled = createMockMcpGroupPermission({ group_id: 2 });+const disabled = createMockMcpGroupPermission({+ group_id: 2,+ mcp_enabled: false,+});++describe("getScopeLabel", () => {+ it("maps known scopes to short labels", () => {+ expect(getScopeLabel("agent:content:read")).toBe("Read");+ expect(getScopeLabel("agent:query:run")).toBe("Query");+ expect(getScopeLabel("agent:sql:run")).toBe("Raw SQL");+ expect(getScopeLabel("agent:content:write")).toBe("Write");+ expect(getScopeLabel("agent:delivery:write")).toBe("Deliveries");+ });++ it("falls back to the scope string", () => {+ expect(getScopeLabel("agent:future:thing")).toBe("agent:future:thing");+ });+});++describe("getDisabledPermission", () => {+ it("is off with no entries", () => {+ expect(getDisabledPermission(7)).toEqual({+ group_id: 7,+ mcp_enabled: false,+ tool_access: {},+ });+ });+});++describe("isToolAllowed", () => {+ it("allows a tool with no entry whose default is allowed", () => {+ expect(isToolAllowed(enabled, search)).toBe(true);+ });++ it("denies a tool with no entry whose default is denied", () => {+ expect(isToolAllowed(enabled, runSql)).toBe(false);+ });++ it("an explicit no beats a default of allowed", () => {+ expect(+ isToolAllowed({ ...enabled, tool_access: { search: "no" } }, search),+ ).toBe(false);+ });++ it("an explicit yes beats a default of denied", () => {+ expect(+ isToolAllowed({ ...enabled, tool_access: { run_sql: "yes" } }, runSql),+ ).toBe(true);+ });++ it("allows nothing while MCP is off, whatever the entries say", () => {+ expect(+ isToolAllowed({ ...disabled, tool_access: { search: "yes" } }, search),+ ).toBe(false);+ });+});++describe("setToolsAllowed", () => {+ it("unchecking and re-checking a tool allowed by default restores the saved permission", () => {+ const unchecked = setToolsAllowed(enabled, allTools, [search], false);+ expect(unchecked.tool_access).toEqual({ search: "no" });+ expect(setToolsAllowed(unchecked, allTools, [search], true)).toEqual(+ enabled,+ );+ });++ it("allowing several tools allowed by default drops their entries and keeps the other entries", () => {+ expect(+ setToolsAllowed(+ {+ ...enabled,+ tool_access: { run_sql: "yes", search: "no", question_write: "yes" },+ },+ allTools,+ writeTools,+ true,+ ),+ ).toEqual({+ group_id: 2,+ mcp_enabled: true,+ tool_access: { run_sql: "yes", search: "no" },+ });+ });++ it("denying one tool writes no for it and keeps the other entries", () => {+ expect(+ setToolsAllowed(+ { ...enabled, tool_access: { run_sql: "yes" } },+ allTools,+ [questionWrite],+ false,+ ),+ ).toEqual({+ group_id: 2,+ mcp_enabled: true,+ tool_access: { run_sql: "yes", question_write: "no" },+ });+ });++ it("denying several tools writes no for each while another tool still resolves to yes", () => {+ expect(setToolsAllowed(enabled, allTools, writeTools, false)).toEqual({+ group_id: 2,+ mcp_enabled: true,+ tool_access: { question_write: "no", transform_write: "no" },+ });+ });++ it("allowing a bucket while MCP is off switches it on, allows the bucket, and turns every other tool off", () => {+ expect(+ setToolsAllowed(+ { ...disabled, tool_access: { search: "yes", run_sql: "yes" } },+ allTools,+ writeTools,+ true,+ ),+ ).toEqual({+ group_id: 2,+ mcp_enabled: true,+ tool_access: { search: "no", run_query: "no" },+ });+ });++ it("denying the last tool that still resolves to yes switches MCP off and clears every entry", () => {+ expect(+ setToolsAllowed(+ {+ ...enabled,+ tool_access: { question_write: "no", search: "no", run_query: "no" },+ },+ allTools,+ [transformWrite],+ false,+ ),+ ).toEqual({+ group_id: 2,+ mcp_enabled: false,+ tool_access: {},+ });+ });++ it("denying every tool switches MCP off with no entries", () => {+ expect(setToolsAllowed(enabled, allTools, allTools, false)).toEqual(+ disabled,+ );+ });++ it("a denied-default tool with no entry reads unchecked and allowing it writes yes", () => {+ expect(isToolAllowed(enabled, runSql)).toBe(false);+ const next = setToolsAllowed(enabled, allTools, [runSql], true);+ expect(next.tool_access).toEqual({ run_sql: "yes" });+ expect(isToolAllowed(next, runSql)).toBe(true);+ });+});++describe("getToolsAccessState", () => {+ it("is all when every tool resolves to yes", () => {+ expect(getToolsAccessState(enabled, writeTools)).toBe("all");+ expect(+ getToolsAccessState({ ...enabled, tool_access: { run_sql: "yes" } }, [+ runSql,+ search,+ ]),+ ).toBe("all");+ });++ it("is some when an explicit no leaves the rest allowed", () => {+ expect(+ getToolsAccessState(+ { ...enabled, tool_access: { question_write: "no" } },+ writeTools,+ ),+ ).toBe("some");+ });++ it("is some when a denied-default tool with no entry sits among allowed ones", () => {+ expect(getToolsAccessState(enabled, allTools)).toBe("some");+ });++ it("is none when no tool resolves to yes", () => {+ expect(+ getToolsAccessState(+ {+ ...enabled,+ tool_access: { question_write: "no", transform_write: "no" },+ },+ writeTools,+ ),+ ).toBe("none");+ });++ it("is none while MCP is off, whatever the entries say", () => {+ expect(+ getToolsAccessState({ ...disabled, tool_access: { search: "yes" } }, [+ search,+ ]),+ ).toBe("none");+ });+});++describe("groupToolsByScope", () => {+ it("orders buckets by the known scope order and keeps registry order inside", () => {+ expect(groupToolsByScope(allTools)).toEqual([+ { scope: "agent:content:read", tools: [search] },+ { scope: "agent:query:run", tools: [runQuery] },+ { scope: "agent:sql:run", tools: [runSql] },+ { scope: "agent:content:write", tools: [questionWrite, transformWrite] },+ ]);+ });++ it("appends unknown scopes after the known ones", () => {+ const custom = createMockMcpTool({ name: "custom", scope: "agent:custom" });+ expect(groupToolsByScope([custom, search]).map((b) => b.scope)).toEqual([+ "agent:content:read",+ "agent:custom",+ ]);+ });+});++describe("buildGridRows", () => {+ it("emits a bucket row followed by its tool rows in scope order with stable ids", () => {+ expect(buildGridRows(allTools)).toEqual([+ {+ kind: "bucket",+ id: "bucket:agent:content:read",+ scope: "agent:content:read",+ label: "Read",+ tools: [search],+ },+ { kind: "tool", id: "tool:search", tool: search },+ {+ kind: "bucket",+ id: "bucket:agent:query:run",+ scope: "agent:query:run",+ label: "Query",+ tools: [runQuery],+ },+ { kind: "tool", id: "tool:run_query", tool: runQuery },+ {+ kind: "bucket",+ id: "bucket:agent:sql:run",+ scope: "agent:sql:run",+ label: "Raw SQL",+ tools: [runSql],+ },+ { kind: "tool", id: "tool:run_sql", tool: runSql },+ {+ kind: "bucket",+ id: "bucket:agent:content:write",+ scope: "agent:content:write",+ label: "Write",+ tools: [questionWrite, transformWrite],+ },+ { kind: "tool", id: "tool:question_write", tool: questionWrite },+ { kind: "tool", id: "tool:transform_write", tool: transformWrite },+ ]);+ });++ it("is empty without tools", () => {+ expect(buildGridRows([])).toEqual([]);+ });+});++const adminGroup = createMockGroup({+ id: 1,+ name: "Administrators",+ magic_group_type: "admin",+});+const allUsersGroup = createMockGroup({+ id: 2,+ name: "All Users",+ magic_group_type: "all-internal-users",+});+const externalGroup = createMockGroup({+ id: 3,+ name: "All External Users",+ magic_group_type: "all-external-users",+});+const zebraGroup = createMockGroup({+ id: 4,+ name: "zebra",+ magic_group_type: null,+});+const alphaGroup = createMockGroup({+ id: 5,+ name: "Alpha",+ magic_group_type: null,+});++describe("buildGridColumns", () => {+ it("orders groups as the permissions pages do: Administrators, All Users, then the rest by name", () => {+ const columns = buildGridColumns(+ [zebraGroup, externalGroup, alphaGroup, allUsersGroup, adminGroup],+ {},+ );+ expect(columns.map((column) => column.group.id)).toEqual([1, 2, 3, 5, 4]);+ expect(columns.map((column) => column.isAdminGroup)).toEqual([+ true,+ false,+ false,+ false,+ false,+ ]);+ });++ it("uses the group's permission row and falls back to a disabled permission", () => {+ const permission = createMockMcpGroupPermission({+ group_id: 4,+ tool_access: { search: "no" },+ });+ const columns = buildGridColumns([zebraGroup, alphaGroup], {+ 4: permission,+ });+ expect(columns.map((column) => column.permission)).toEqual([+ getDisabledPermission(5),+ permission,+ ]);+ });+});++describe("filterGridColumns", () => {+ const columns = buildGridColumns(+ [adminGroup, allUsersGroup, alphaGroup, zebraGroup],+ {},+ );++ it("returns the input array for an empty or blank query", () => {+ expect(filterGridColumns(columns, "")).toBe(columns);+ expect(filterGridColumns(columns, " ")).toBe(columns);+ });++ it("matches group names case-insensitively after trimming", () => {+ expect(+ filterGridColumns(columns, " ALPHA ").map((column) => column.group.name),+ ).toEqual(["Alpha"]);+ expect(+ filterGridColumns(columns, "al").map((column) => column.group.name),+ ).toEqual(["All Users", "Alpha"]);+ });++ it("filters Administrators like any other group", () => {+ expect(+ filterGridColumns(columns, "zebra").map((column) => column.group.name),+ ).toEqual(["zebra"]);+ });+});diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/index.tsnew file mode 100644index 00000000000..4b1d40a35c3--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/index.ts@@ -0,0 +1 @@+export { McpToolsAccessPage } from "./McpToolsAccessPage";diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/useMcpToolPermissions.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/useMcpToolPermissions.tsnew file mode 100644index 00000000000..c745e712f22--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/McpToolsAccessPage/useMcpToolPermissions.ts@@ -0,0 +1,105 @@+import { useCallback, useMemo, useState } from "react";+import { t } from "ttag";+import _ from "underscore";++import { useMetadataToasts } from "metabase/common/hooks";+import {+ useGetMcpToolPermissionsQuery,+ useUpdateMcpToolPermissionsMutation,+} from "metabase-enterprise/api";+import type {+ GroupId,+ McpGroupPermission,+ McpTool,+ McpToolPermissionsResponse,+} from "metabase-types/api";++const NO_TOOLS: McpTool[] = [];+const NO_PERMISSIONS: McpGroupPermission[] = [];+const NO_EDITS: Record<GroupId, McpGroupPermission> = {};++type Draft = {+ base: McpToolPermissionsResponse;+ byGroup: Record<GroupId, McpGroupPermission>;+};++type McpToolPermissionsState = {+ tools: McpTool[];+ permissionsByGroup: Record<GroupId, McpGroupPermission>;+ advanced: boolean;+ isDirty: boolean;+ isSaving: boolean;+ isLoading: boolean;+ error: string | null;+ onPermissionChange: (permission: McpGroupPermission) => void;+ onSave: () => Promise<void>;+ onCancel: () => void;+};++export function useMcpToolPermissions(): McpToolPermissionsState {+ const { data, isLoading, error } = useGetMcpToolPermissionsQuery();+ const [updateMcpPermissions, { isLoading: isSaving }] =+ useUpdateMcpToolPermissionsMutation();+ const { sendErrorToast } = useMetadataToasts();+ const [draft, setDraft] = useState<Draft | null>(null);++ const saved = data?.permissions ?? NO_PERMISSIONS;+ const edits = draft && draft.base === data ? draft.byGroup : NO_EDITS;++ const changed = useMemo(+ () =>+ Object.values(edits).filter(+ (permission) =>+ !_.isEqual(+ permission,+ saved.find((p) => p.group_id === permission.group_id),+ ),+ ),+ [edits, saved],+ );++ const permissionsByGroup = useMemo(+ () => ({ ..._.indexBy(saved, "group_id"), ...edits }),+ [saved, edits],+ );++ const onPermissionChange = useCallback(+ (permission: McpGroupPermission) => {+ if (!data) {+ return;+ }+ setDraft((prev) => ({+ base: data,+ byGroup: {+ ...(prev && prev.base === data ? prev.byGroup : NO_EDITS),+ [permission.group_id]: permission,+ },+ }));+ },+ [data],+ );++ const onCancel = useCallback(() => setDraft(null), []);++ const onSave = useCallback(async () => {+ try {+ await updateMcpPermissions({ permissions: changed }).unwrap();+ setDraft(null);+ } catch {+ sendErrorToast(t`Failed to save MCP tool permissions`);+ }+ }, [changed, updateMcpPermissions, sendErrorToast]);++ return {+ tools: data?.tools ?? NO_TOOLS,+ permissionsByGroup,+ advanced: data?.advanced ?? false,+ isDirty: changed.length > 0,+ isSaving,+ isLoading,+ error: error ? t`Failed to load MCP tool permissions` : null,+ onPermissionChange,+ onSave,+ onCancel,+ };+}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessPage.tsxdeleted file mode 100644index c99f5607321..00000000000--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessPage.tsx+++ /dev/null@@ -1,77 +0,0 @@-import { useState } from "react";-import { t } from "ttag";--import { useListPermissionsGroupsQuery } from "metabase/api";-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";-import { useSetting } from "metabase/settings";-import { SettingsPageWrapper } from "metabase/settings-components";-import { Group, Stack, Title } from "metabase/ui";--import { AiFeatureAccessTable } from "./components/AiFeatureAccessTable";-import { GearIconMenu } from "./components/GearIconMenu/GearIconMenu";-import { GroupCategoryTabs } from "./components/GroupCategoryTabs";-import { type GroupTab, useMetabotGroupPermissions } from "./utils";--export function MetabotFeatureAccessPage() {- const isUsingTenants = useSetting("use-tenants");- const [activeTab, setActiveTab] = useState<GroupTab>("user-groups");-- const {- data: userGroups,- isLoading: isLoadingUserGroups,- error: userGroupsError,- } = useListPermissionsGroupsQuery(- isUsingTenants ? { tenancy: "internal" } : undefined,- );-- const {- data: tenantGroups,- isLoading: isLoadingTenantGroups,- error: tenantGroupsError,- } = useListPermissionsGroupsQuery(- isUsingTenants ? { tenancy: "external" } : undefined,- { skip: !isUsingTenants },- );-- const {- groupPermissions,- onPermissionChange,- advanced,- error: permissionsError,- } = useMetabotGroupPermissions();-- const activeGroups =- activeTab === "tenant-groups" ? tenantGroups : userGroups;- const isLoading =- activeTab === "tenant-groups" ? isLoadingTenantGroups : isLoadingUserGroups;- const groupsError =- activeTab === "tenant-groups" ? tenantGroupsError : userGroupsError;- const error = groupsError || permissionsError;-- return (- <SettingsPageWrapper mt="sm" gap="lg">- <Group justify="space-between" w="100%">- <Title order={1}>{t`AI feature access`}</Title>- {advanced && <GearIconMenu />}- </Group>-- {isUsingTenants && (- <GroupCategoryTabs setActiveTab={setActiveTab} activeTab={activeTab} />- )}-- <Stack gap="lg">- <LoadingAndErrorWrapper loading={isLoading} error={error}>- {activeGroups && (- <AiFeatureAccessTable- groups={activeGroups}- groupPermissions={groupPermissions}- onPermissionChange={onPermissionChange}- advanced={advanced}- activeTab={activeTab}- />- )}- </LoadingAndErrorWrapper>- </Stack>- </SettingsPageWrapper>- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessPage.unit.spec.tsxdeleted file mode 100644index 520878d0ed3..00000000000--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessPage.unit.spec.tsx+++ /dev/null@@ -1,388 +0,0 @@-import userEvent from "@testing-library/user-event";--import { setupGroupsEndpoint } from "__support__/server-mocks/group";-import {- setupMetabotGroupPermissionsEndpoint,- setupUpdateMetabotGroupPermissionsEndpoint,-} from "__support__/server-mocks/metabot";-import { createMockSettingsState } from "__support__/state";-import { renderWithProviders, screen, waitFor, within } from "__support__/ui";-import { AIToolKey, type MetabotGroupPermission } from "metabase-types/api";-import { createMockGroup } from "metabase-types/api/mocks";-import { createMockMetabotGroupPermissions } from "metabase-types/api/mocks/metabot";--import { MetabotFeatureAccessPage } from "./MetabotFeatureAccessPage";--const adminGroup = createMockGroup({- id: 1,- name: "Administrators",- member_count: 1,- magic_group_type: "admin",-});--const allUsersGroup = createMockGroup({- id: 2,- name: "All Users",- member_count: 5,- magic_group_type: "all-internal-users",-});--const marketingGroup = createMockGroup({- id: 3,- name: "Marketing",- member_count: 3,- magic_group_type: null,-});--const defaultGroups = [adminGroup, allUsersGroup, marketingGroup];--function createDefaultPermissions(): MetabotGroupPermission[] {- return [- ...createMockMetabotGroupPermissions(adminGroup.id),- ...createMockMetabotGroupPermissions(allUsersGroup.id, {- [AIToolKey.SQLGeneration]: "no",- }),- ...createMockMetabotGroupPermissions(marketingGroup.id, {- [AIToolKey.Metabot]: "no",- [AIToolKey.ChatAndNLQ]: "no",- [AIToolKey.SQLGeneration]: "no",- [AIToolKey.OtherTools]: "no",- }),- ];-}--function setup({- permissions = createDefaultPermissions(),- groups = defaultGroups,- useTenants = false,- advanced = false,-}: {- permissions?: MetabotGroupPermission[];- groups?: typeof defaultGroups;- useTenants?: boolean;- advanced?: boolean;-} = {}) {- setupGroupsEndpoint(groups);- setupMetabotGroupPermissionsEndpoint(permissions, advanced);- setupUpdateMetabotGroupPermissionsEndpoint();-- renderWithProviders(<MetabotFeatureAccessPage />, {- storeInitialState: {- settings: createMockSettingsState({ "use-tenants": useTenants }),- },- });-}--function getPermissionRow(groupName: string) {- return screen.getByRole("row", {- name: new RegExp(`${groupName} permissions`),- });-}--describe("MetabotFeatureAccessPage", () => {- const originalGetBoundingClientRect =- HTMLElement.prototype.getBoundingClientRect;-- beforeAll(() => {- // needed for @tanstack/react-virtual, see https://github.com/TanStack/virtual/issues/29#issuecomment-657519522- HTMLElement.prototype.getBoundingClientRect = jest- .fn()- .mockReturnValue({ height: 400, width: 800, top: 0, left: 0 });- });-- afterAll(() => {- HTMLElement.prototype.getBoundingClientRect = originalGetBoundingClientRect;- });-- it("renders groups with their permission states", async () => {- setup({ advanced: true });-- expect(- await screen.findByTestId("ai-feature-access-table"),- ).toBeInTheDocument();-- expect(screen.getByText("Administrators")).toBeInTheDocument();- expect(screen.queryByText("All Users")).not.toBeInTheDocument();- expect(screen.getByText("Marketing")).toBeInTheDocument();- });-- it("hides non-admin/non-all-users groups in simple mode", async () => {- setup();-- await screen.findByTestId("ai-feature-access-table");-- expect(screen.getByText("Administrators")).toBeInTheDocument();- expect(screen.getByText("All Users")).toBeInTheDocument();- expect(screen.queryByText("Marketing")).not.toBeInTheDocument();- });-- it("renders column headers for each AI tool", async () => {- setup();- await screen.findByTestId("ai-feature-access-table");-- expect(screen.getByText("AI features")).toBeInTheDocument();- expect(screen.getByText("Chat and NLQ")).toBeInTheDocument();- expect(screen.getByText("SQL generation")).toBeInTheDocument();- expect(screen.getByText("Other tools")).toBeInTheDocument();- });-- it("shows all admin group controls as checked and disabled", async () => {- setup();- await screen.findByTestId("ai-feature-access-table");-- const adminRow = getPermissionRow("Administrators");-- const metabotSwitch = within(adminRow).getByRole("switch");- expect(metabotSwitch).toBeChecked();- expect(metabotSwitch).toBeDisabled();-- const checkboxes = within(adminRow).getAllByRole("checkbox");- checkboxes.forEach((checkbox) => {- expect(checkbox).toBeChecked();- expect(checkbox).toBeDisabled();- });- });-- it("shows correct permission states for a group with mixed permissions", async () => {- setup();- await screen.findByTestId("ai-feature-access-table");-- const allUsersRow = getPermissionRow("All Users");-- // Wait for permissions to propagate through the async state pipeline- await waitFor(() => {- const metabotSwitch = within(allUsersRow).getByRole("switch");- expect(metabotSwitch).toBeChecked();- });-- const sqlCheckbox = within(allUsersRow).getByRole("checkbox", {- name: /SQL generation/,- });- expect(sqlCheckbox).not.toBeChecked();-- const chatCheckbox = within(allUsersRow).getByRole("checkbox", {- name: /Chat and NLQ/,- });- expect(chatCheckbox).toBeChecked();- });-- it("leaves sub-permission checkboxes enabled when metabot is off for a group", async () => {- setup({ advanced: true });- await screen.findByTestId("ai-feature-access-table");-- const marketingRow = getPermissionRow("Marketing");- const metabotSwitch = within(marketingRow).getByRole("switch");- expect(metabotSwitch).not.toBeChecked();-- const checkboxes = within(marketingRow).getAllByRole("checkbox");- checkboxes.forEach((checkbox) => {- expect(checkbox).toBeEnabled();- expect(checkbox).not.toBeChecked();- });- });-- it("checks every sub-permission when toggling metabot on for a group", async () => {- setup({ advanced: true });- await screen.findByTestId("ai-feature-access-table");-- const marketingRow = getPermissionRow("Marketing");- const metabotSwitch = within(marketingRow).getByRole("switch");-- await userEvent.click(metabotSwitch);-- expect(metabotSwitch).toBeChecked();- const checkboxes = within(marketingRow).getAllByRole("checkbox");- checkboxes.forEach((checkbox) => {- expect(checkbox).toBeEnabled();- expect(checkbox).toBeChecked();- });- });-- it("unchecks every sub-permission when toggling metabot off for a group", async () => {- setup();- await screen.findByTestId("ai-feature-access-table");-- const allUsersRow = getPermissionRow("All Users");- const metabotSwitch = within(allUsersRow).getByRole("switch");-- // Wait for permissions to load so the switch reflects the initial "yes" state- await waitFor(() => {- expect(metabotSwitch).toBeChecked();- });-- await userEvent.click(metabotSwitch);-- expect(metabotSwitch).not.toBeChecked();- const checkboxes = within(allUsersRow).getAllByRole("checkbox");- checkboxes.forEach((checkbox) => {- expect(checkbox).toBeEnabled();- expect(checkbox).not.toBeChecked();- });- });-- it("auto-enables metabot when a tool is checked while metabot is off", async () => {- setup({ advanced: true });- await screen.findByTestId("ai-feature-access-table");-- const marketingRow = getPermissionRow("Marketing");- const metabotSwitch = within(marketingRow).getByRole("switch");- expect(metabotSwitch).not.toBeChecked();-- const chatCheckbox = within(marketingRow).getByRole("checkbox", {- name: /Chat and NLQ/,- });- await userEvent.click(chatCheckbox);-- expect(metabotSwitch).toBeChecked();- expect(chatCheckbox).toBeChecked();- // Other tools should remain unchecked — only the clicked one and metabot flip on- expect(- within(marketingRow).getByRole("checkbox", { name: /SQL generation/ }),- ).not.toBeChecked();- expect(- within(marketingRow).getByRole("checkbox", { name: /Other tools/ }),- ).not.toBeChecked();- });-- it("auto-disables metabot when the last enabled tool is unchecked", async () => {- const onlyChatEnabled = [- ...createMockMetabotGroupPermissions(adminGroup.id),- ...createMockMetabotGroupPermissions(allUsersGroup.id, {- [AIToolKey.SQLGeneration]: "no",- [AIToolKey.OtherTools]: "no",- }),- ...createMockMetabotGroupPermissions(marketingGroup.id, {- [AIToolKey.Metabot]: "no",- [AIToolKey.ChatAndNLQ]: "no",- [AIToolKey.SQLGeneration]: "no",- [AIToolKey.OtherTools]: "no",- }),- ];- setup({ permissions: onlyChatEnabled });- await screen.findByTestId("ai-feature-access-table");-- const allUsersRow = getPermissionRow("All Users");- const metabotSwitch = within(allUsersRow).getByRole("switch");- await waitFor(() => expect(metabotSwitch).toBeChecked());-- const chatCheckbox = within(allUsersRow).getByRole("checkbox", {- name: /Chat and NLQ/,- });- await waitFor(() => expect(chatCheckbox).toBeChecked());-- await userEvent.click(chatCheckbox);-- expect(chatCheckbox).not.toBeChecked();- expect(metabotSwitch).not.toBeChecked();- });-- it("does not affect other groups when one group's permissions change", async () => {- const engineeringGroup = createMockGroup({- id: 4,- name: "Engineering",- member_count: 4,- magic_group_type: null,- });- const permissions = [- ...createMockMetabotGroupPermissions(adminGroup.id),- ...createMockMetabotGroupPermissions(allUsersGroup.id),- ...createMockMetabotGroupPermissions(marketingGroup.id, {- [AIToolKey.Metabot]: "no",- [AIToolKey.ChatAndNLQ]: "no",- [AIToolKey.SQLGeneration]: "no",- [AIToolKey.OtherTools]: "no",- }),- ...createMockMetabotGroupPermissions(engineeringGroup.id),- ];- setup({- advanced: true,- groups: [...defaultGroups, engineeringGroup],- permissions,- });- await screen.findByTestId("ai-feature-access-table");-- const engineeringRow = getPermissionRow("Engineering");- const engineeringSwitch = within(engineeringRow).getByRole("switch");- const engineeringCheckboxes =- within(engineeringRow).getAllByRole("checkbox");-- // Wait for the fully-enabled engineering row to settle- await waitFor(() => expect(engineeringSwitch).toBeChecked());- engineeringCheckboxes.forEach((checkbox) => {- expect(checkbox).toBeChecked();- });-- // Auto-enable on a tool in Marketing — would have flipped engineering's metabot- // in the previous (buggy) implementation that didn't filter by group_id- const marketingRow = getPermissionRow("Marketing");- await userEvent.click(- within(marketingRow).getByRole("checkbox", { name: /Chat and NLQ/ }),- );-- // Sanity: the change landed on Marketing- expect(within(marketingRow).getByRole("switch")).toBeChecked();-- // Engineering must remain fully enabled — no cross-group leak- expect(engineeringSwitch).toBeChecked();- engineeringCheckboxes.forEach((checkbox) => {- expect(checkbox).toBeChecked();- });-- // And the inverse leak: unchecking Marketing's last enabled tool would- // previously disable Engineering's metabot via the shared cascade path- await userEvent.click(- within(marketingRow).getByRole("checkbox", { name: /Chat and NLQ/ }),- );- expect(within(marketingRow).getByRole("switch")).not.toBeChecked();- expect(engineeringSwitch).toBeChecked();- engineeringCheckboxes.forEach((checkbox) => {- expect(checkbox).toBeChecked();- });- });-- it("does not show tenant tabs when use-tenants is false", async () => {- setup({ useTenants: false });- await screen.findByTestId("ai-feature-access-table");-- expect(screen.queryByText("User groups")).not.toBeInTheDocument();- expect(screen.queryByText("Tenant groups")).not.toBeInTheDocument();- });-- it("shows tenant tabs when use-tenants is true", async () => {- setup({ useTenants: true });- await screen.findByTestId("ai-feature-access-table");-- expect(screen.getByText("User groups")).toBeInTheDocument();- expect(screen.getByText("Tenant groups")).toBeInTheDocument();- });-- it("renders the group name next to its AI features switch in the first cell", async () => {- setup();- await screen.findByTestId("ai-feature-access-table");-- const adminRow = getPermissionRow("Administrators");- const gridcell = within(adminRow).getAllByRole("gridcell")[0];- expect(within(gridcell).getByRole("switch")).toBeInTheDocument();- expect(within(gridcell).getByText("Administrators")).toBeInTheDocument();- });-- it("shows the 'Switch to group-level permissions' button in simple mode", async () => {- setup();- await screen.findByTestId("ai-feature-access-table");-- expect(- screen.getByRole("button", { name: "Switch to group-level permissions" }),- ).toBeInTheDocument();- });-- it("hides the 'Switch to group-level permissions' button in advanced mode", async () => {- setup({ advanced: true });- await screen.findByTestId("ai-feature-access-table");-- expect(- screen.queryByRole("button", {- name: "Switch to group-level permissions",- }),- ).not.toBeInTheDocument();- });-});diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/AdvancedGroupModeButton.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/AdvancedGroupModeButton.tsxdeleted file mode 100644index b2506506ea7..00000000000--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/AdvancedGroupModeButton.tsx+++ /dev/null@@ -1,23 +0,0 @@-import { useDisclosure } from "@mantine/hooks";-import { t } from "ttag";--import { Button } from "metabase/ui";--import S from "./AdvancedGroupModeButton.module.css";-import { EnableAdvancedModal } from "./EnableAdvancedModal";--export function AdvancedGroupModeButton() {- const [showEnableModal, { toggle: toggleShowEnableModal }] =- useDisclosure(false);-- return (- <>- <Button className={S.button} onClick={toggleShowEnableModal} size="sm">- {t`Switch to group-level permissions`}- </Button>- {showEnableModal && (- <EnableAdvancedModal onClose={toggleShowEnableModal} />- )}- </>- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/EnableAdvancedModal.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/EnableAdvancedModal.tsxdeleted file mode 100644index 7ead37449c3..00000000000--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/components/AiFeatureAccessTable/AdvancedGroupMode/EnableAdvancedModal.tsx+++ /dev/null@@ -1,41 +0,0 @@-import { t } from "ttag";--import { ConfirmModal } from "metabase/common/components/ConfirmModal";-import { useMetadataToasts } from "metabase/common/hooks";-import { useEnableAdvancedAIControlsPermissionsMutation } from "metabase-enterprise/api";--type Props = {- onClose: () => void;-};--export function EnableAdvancedModal({ onClose }: Props) {- const [enableAdvanced, { isLoading: loading }] =- useEnableAdvancedAIControlsPermissionsMutation();- const { sendErrorToast } = useMetadataToasts();-- const handleConfirm = async () => {- try {- await enableAdvanced().unwrap();- onClose();- } catch {- sendErrorToast(t`Failed to switch to group-level permissions`);- }- };-- return (- <ConfirmModal- opened- onClose={onClose}- title={t`Switch to group-level permissions?`}- message={t`This will remove all AI feature access from the "All Users" group, so users won't have access to AI features unless they're added to a group that has access.`}- confirmButtonText={t`Switch`}- confirmButtonProps={{- color: "brand",- variant: "filled",- loading,- }}- closeButtonProps={{ disabled: loading, variant: "subtle" }}- onConfirm={handleConfirm}- />- );-}diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/index.tsdeleted file mode 100644index 63053f639c0..00000000000--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/index.ts+++ /dev/null@@ -1,2 +0,0 @@-export { MetabotFeatureAccessPage } from "./MetabotFeatureAccessPage";-export { MetabotFeatureAccessUpsellPage } from "./MetabotFeatureAccessUpsellPage";diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsxindex 35e0c2268b3..d4e5305946a 100644--- a/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx@@ -1,33 +1,38 @@import { Route, registerPagePrefetch } from "metabase/router";import * as Urls from "metabase/urls";-import { RequireMetabotConfigured } from "./components/RequireMetabotConfigured";+import {+ RequireMcpEnabled,+ RequireMetabotConfigured,+} from "./components/RequireMetabotConfigured";/*** The AI settings pages, each in its own chunk.*- * The nine loaders below resolve to four page modules, and those four share+ * The ten loaders below resolve to five page modules, and those five share* under a tenth of their weight, so one chunk for the section would make a* visit to any single tab pay for all of them.*- * `RequireMetabotConfigured` is not split. It redirects away when Metabot is- * unconfigured, so splitting it would put a fetch in front of a redirect that- * renders nothing.+ * The gates are not split. They redirect away when their feature is off, so+ * splitting them would put a fetch in front of a redirect that renders nothing.*/-const metabotFeatureAccessPage = () =>+const aiFeatureAccessPage = () =>import(- /* webpackChunkName: "metabot-feature-access" */ "./pages/MetabotFeatureAccessPage"- ).then(({ MetabotFeatureAccessPage }) => ({- Component: MetabotFeatureAccessPage,- }));+ /* webpackChunkName: "ai-feature-access" */ "./pages/AiFeatureAccessPage"+ ).then(({ AiFeatureAccessPage }) => ({ Component: AiFeatureAccessPage }));-const metabotFeatureAccessUpsellPage = () =>+const aiFeatureAccessUpsellPage = () =>import(- /* webpackChunkName: "metabot-feature-access" */ "./pages/MetabotFeatureAccessPage"- ).then(({ MetabotFeatureAccessUpsellPage }) => ({- Component: MetabotFeatureAccessUpsellPage,+ /* webpackChunkName: "ai-feature-access" */ "./pages/AiFeatureAccessPage"+ ).then(({ AiFeatureAccessUpsellPage }) => ({+ Component: AiFeatureAccessUpsellPage,}));+const mcpToolsAccessPage = () =>+ import(+ /* webpackChunkName: "mcp-tools-access" */ "./pages/McpToolsAccessPage"+ ).then(({ McpToolsAccessPage }) => ({ Component: McpToolsAccessPage }));+const metabotUsageLimitsPage = () =>import(/* webpackChunkName: "metabot-usage-limits" */ "./pages/MetabotUsageLimitsPage"@@ -83,6 +88,7 @@ const metabotSystemPromptsUpsellPage = () =>*/const PATHS = {featureAccess: "usage-controls/ai-feature-access",+ mcpToolsAccess: "usage-controls/mcp-tools-access",usageLimits: "usage-controls/ai-usage-limits",customization: "customization",systemPrompts: "system-prompts",@@ -105,10 +111,8 @@ const adminAiPath = (path: string) => `${Urls.adminAiSettings()}/${path}`;* is registered once.*/export function registerAiControlsPagePrefetch(): void {- registerPagePrefetch(- adminAiPath(PATHS.featureAccess),- metabotFeatureAccessPage,- );+ registerPagePrefetch(adminAiPath(PATHS.featureAccess), aiFeatureAccessPage);+ registerPagePrefetch(adminAiPath(PATHS.mcpToolsAccess), mcpToolsAccessPage);registerPagePrefetch(adminAiPath(PATHS.usageLimits), metabotUsageLimitsPage);registerPagePrefetch(adminAiPath(PATHS.customization),@@ -124,7 +128,7 @@ export function registerAiControlsPagePrefetch(): void {export function registerAiControlsUpsellPagePrefetch(): void {registerPagePrefetch(adminAiPath(PATHS.featureAccess),- metabotFeatureAccessUpsellPage,+ aiFeatureAccessUpsellPage,);registerPagePrefetch(adminAiPath(PATHS.customization),@@ -142,7 +146,7 @@ export function getAiControlsRoutes() {<Routekey="ai-feature-access"path={PATHS.featureAccess}- lazy={metabotFeatureAccessPage}+ lazy={aiFeatureAccessPage}/><Routekey="ai-usage-limits"@@ -173,13 +177,25 @@ export function getAiControlsRoutes() {);}+export function getMcpToolsAccessRoutes() {+ return (+ <Route element={<RequireMcpEnabled />}>+ <Route+ key="mcp-tools-access"+ path={PATHS.mcpToolsAccess}+ lazy={mcpToolsAccessPage}+ />+ </Route>+ );+}+export function getAiControlsUpsellRoutes() {return (<><Routekey="ai-feature-access"path={PATHS.featureAccess}- lazy={metabotFeatureAccessUpsellPage}+ lazy={aiFeatureAccessUpsellPage}/><Routekey="customization"diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/types.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/types.tsnew file mode 100644index 00000000000..7a8f980479c--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/types.ts@@ -0,0 +1,8 @@+export type GroupTab = "user-groups" | "tenant-groups";++/**+ * Resolves to whether the mode changed. A failure has already been reported+ * to the user by the time this resolves, so the caller only decides what to+ * do on success.+ */+export type SwitchAdvancedMode = () => Promise<boolean>;diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/utils.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/utils.tsnew file mode 100644index 00000000000..3dc8e9dd366--- /dev/null+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/utils.ts@@ -0,0 +1,28 @@+import {+ isAdminGroup,+ isDefaultGroup,+ isDefaultTenantGroup,+} from "metabase/common/utils/groups";+import type { GroupInfo } from "metabase-types/api";++import type { GroupTab } from "./types";++export function getVisibleGroups(+ groups: GroupInfo[],+ advanced: boolean,+ activeTab: GroupTab,+): GroupInfo[] {+ if (advanced) {+ return groups.filter(+ (group) => !isDefaultGroup(group) && !isDefaultTenantGroup(group),+ );+ }++ if (activeTab === "tenant-groups") {+ return groups.filter(+ (group) => isAdminGroup(group) || isDefaultTenantGroup(group),+ );+ }++ return groups.filter((group) => isAdminGroup(group) || isDefaultGroup(group));+}diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-controls.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-controls.tsindex 03610e699fd..6abb4c609a2 100644--- a/enterprise/frontend/src/metabase-enterprise/api/ai-controls.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-controls.ts@@ -1,8 +1,10 @@import type {+ McpToolPermissionsResponse,MetabotGroupLimit,MetabotInstanceLimit,MetabotPermissionsResponse,MetabotTenantLimit,+ UpdateMcpToolPermissionsRequest,UpdateMetabotPermissionsRequest,} from "metabase-types/api";@@ -46,6 +48,58 @@ export const aiControlsApi = EnterpriseApi.injectEndpoints({}),invalidatesTags: [listTag("ai-controls-permissions")],}),+ getMcpToolPermissions: builder.query<McpToolPermissionsResponse, void>({+ query: () => ({+ method: "GET",+ url: "/api/ee/ai-controls/mcp-permissions",+ }),+ providesTags: () => [listTag("ai-controls-mcp-permissions")],+ }),+ updateMcpToolPermissions: builder.mutation<+ McpToolPermissionsResponse,+ UpdateMcpToolPermissionsRequest+ >({+ query: (body) => ({+ method: "PUT",+ url: "/api/ee/ai-controls/mcp-permissions",+ body,+ }),+ // The PUT answers with the GET body; a refetch would show the pre-save state first.+ onQueryStarted: async (_body, { dispatch, queryFulfilled }) => {+ try {+ const { data } = await queryFulfilled;+ dispatch(+ aiControlsApi.util.updateQueryData(+ "getMcpToolPermissions",+ undefined,+ () => data,+ ),+ );+ } catch {+ // the caller's unwrap() reports the failure+ }+ },+ }),+ enableAdvancedMcpToolPermissions: builder.mutation<+ McpToolPermissionsResponse,+ void+ >({+ query: () => ({+ method: "POST",+ url: "/api/ee/ai-controls/mcp-permissions/advanced",+ }),+ invalidatesTags: [listTag("ai-controls-mcp-permissions")],+ }),+ disableAdvancedMcpToolPermissions: builder.mutation<+ McpToolPermissionsResponse,+ void+ >({+ query: () => ({+ method: "DELETE",+ url: "/api/ee/ai-controls/mcp-permissions/advanced",+ }),+ invalidatesTags: [listTag("ai-controls-mcp-permissions")],+ }),getAIControlsInstanceLimit: builder.query<MetabotInstanceLimit, void>({query: () => ({method: "GET",@@ -111,6 +165,10 @@ export const {useUpdateAIControlsGroupPermissionsMutation,useEnableAdvancedAIControlsPermissionsMutation,useDisableAdvancedAIControlsPermissionsMutation,+ useGetMcpToolPermissionsQuery,+ useUpdateMcpToolPermissionsMutation,+ useEnableAdvancedMcpToolPermissionsMutation,+ useDisableAdvancedMcpToolPermissionsMutation,useGetAIControlsInstanceLimitQuery,useUpdateAIControlsInstanceLimitMutation,useGetAIControlsGroupLimitsQuery,diff --git a/enterprise/frontend/src/metabase-enterprise/api/tags.ts b/enterprise/frontend/src/metabase-enterprise/api/tags.tsindex baa31804a76..50a6850f93c 100644--- a/enterprise/frontend/src/metabase-enterprise/api/tags.ts+++ b/enterprise/frontend/src/metabase-enterprise/api/tags.ts@@ -47,6 +47,7 @@ export const ENTERPRISE_TAG_TYPES = ["support-access-grant-current","library-collection","ai-controls-permissions",+ "ai-controls-mcp-permissions","ai-controls-usage-instance-limit","ai-controls-usage-group-limits","ai-controls-usage-tenant-limits",diff --git a/enterprise/frontend/src/metabase-enterprise/lazy-plugin-routes.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/lazy-plugin-routes.unit.spec.tsxindex 72c40575c7c..91c98dd7229 100644--- a/enterprise/frontend/src/metabase-enterprise/lazy-plugin-routes.unit.spec.tsx+++ b/enterprise/frontend/src/metabase-enterprise/lazy-plugin-routes.unit.spec.tsx@@ -4,6 +4,7 @@ import { type RouteObject, toRouteObjects } from "metabase/router";import {getAiControlsRoutes,getAiControlsUpsellRoutes,+ getMcpToolsAccessRoutes,} from "metabase-enterprise/ai-controls/routes";import getApplicationPermissionsRoutes from "metabase-enterprise/application_permissions/routes";import { getRoutes as getDataAppRoutes } from "metabase-enterprise/data_apps/routes";@@ -42,6 +43,7 @@ function lazyLoaders(tree: ReactNode) {const FACTORIES: [string, ReactNode, number][] = [["ai-controls", getAiControlsRoutes(), 6],["ai-controls upsell", getAiControlsUpsellRoutes(), 3],+ ["mcp tools access", getMcpToolsAccessRoutes(), 1],["schema viewer", getDataStudioSchemaViewerRoutes(), 1],["transforms inspector", getInspectorRoutes(), 2],["transforms inspector upsell", getInspectorUpsellRoutes(), 2],diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.tsindex 4eb10a99378..a4ef69e90e5 100644--- a/frontend/src/metabase-types/api/metabot.ts+++ b/frontend/src/metabase-types/api/metabot.ts@@ -1,3 +1,4 @@+import type { GroupId } from "./group";import type { EnterpriseSettings } from "./settings";import type {@@ -421,6 +422,34 @@ export type UpdateMetabotPermissionsRequest = {permissions: MetabotGroupPermission[];};+/* MCP - Group Tool Permissions */++export type McpToolAccess = "yes" | "no";++export type McpTool = {+ name: string;+ scope: string;+ description: string;+ default_access: "allowed" | "denied";+};++export type McpGroupPermission = {+ group_id: GroupId;+ mcp_enabled: boolean;+ /** An absent tool takes its `default_access`. */+ tool_access: Record<string, McpToolAccess>;+};++export type McpToolPermissionsResponse = {+ advanced: boolean;+ tools: McpTool[];+ permissions: McpGroupPermission[];+};++export type UpdateMcpToolPermissionsRequest = {+ permissions: McpGroupPermission[];+};+export type UserMetabotPermissions = {metabot: "yes" | "no";"metabot-sql-generation": "yes" | "no";diff --git a/frontend/src/metabase-types/api/mocks/metabot.ts b/frontend/src/metabase-types/api/mocks/metabot.tsindex aa61a8f13e3..2e2bb182bbc 100644--- a/frontend/src/metabase-types/api/mocks/metabot.ts+++ b/frontend/src/metabase-types/api/mocks/metabot.ts@@ -4,6 +4,9 @@ import {AIToolKey,type McpAppsBootstrapResponse,type McpAppsBootstrapUser,+ type McpGroupPermission,+ type McpTool,+ type McpToolPermissionsResponse,type MetabotConversation,type MetabotGroupPermission,type MetabotInfo,@@ -83,6 +86,32 @@ export const createMockMetabotGroupPermissions = (}));};+export const createMockMcpTool = (opts?: Partial<McpTool>): McpTool => ({+ name: "search",+ scope: "agent:content:read",+ description: "Search for content.",+ default_access: "allowed",+ ...opts,+});++export const createMockMcpGroupPermission = (+ opts?: Partial<McpGroupPermission>,+): McpGroupPermission => ({+ group_id: 1,+ mcp_enabled: true,+ tool_access: {},+ ...opts,+});++export const createMockMcpToolPermissionsResponse = (+ opts?: Partial<McpToolPermissionsResponse>,+): McpToolPermissionsResponse => ({+ advanced: false,+ tools: [createMockMcpTool()],+ permissions: [createMockMcpGroupPermission()],+ ...opts,+});+/*** The setting keys `GET /api/embed-mcp/bootstrap` returns, out of those* {@link createMockSettings} defines: the `:public`, `:authenticated` anddiff --git a/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsx b/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsxindex 2b4e1df7382..22b0334461a 100644--- a/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsx+++ b/frontend/src/metabase/admin/ai/MetabotNavPane.unit.spec.tsx@@ -15,12 +15,14 @@ const setup = ({aiControlsEnabled = false,auditAppEnabled = false,isConfigured = true,+ mcpEnabled = true,initialRoute = "/admin/metabot",}: {aiFeaturesEnabled?: boolean;aiControlsEnabled?: boolean;auditAppEnabled?: boolean;isConfigured?: boolean;+ mcpEnabled?: boolean;initialRoute?: string;} = {}) => {mockSettings({@@ -42,12 +44,20 @@ const setup = ({settings: createMockSettingsState({"ai-features-enabled?": aiFeaturesEnabled,"llm-metabot-configured?": isConfigured,+ "mcp-enabled?": mcpEnabled,}),},},);};+function getUsageControlLinks() {+ return screen+ .getAllByRole("link")+ .map((link) => link.getAttribute("href"))+ .filter((href) => href?.startsWith("/admin/metabot/usage-controls/"));+}+describe("MetabotNavPane", () => {afterEach(() => {reinitialize();@@ -69,8 +79,8 @@ describe("MetabotNavPane", () => {expect(screen.queryByText("System prompts")).not.toBeInTheDocument();});- it("displays the ai controls in a disabled state when not configured", async () => {- setup({ aiControlsEnabled: true, isConfigured: false });+ it("displays the ai controls in a disabled state when neither Metabot nor MCP is on", async () => {+ setup({ aiControlsEnabled: true, isConfigured: false, mcpEnabled: false });expect(await screen.findByText("AI Settings")).toBeInTheDocument();expect(@@ -94,6 +104,75 @@ describe("MetabotNavPane", () => {).toBeInTheDocument();});+ it("keeps Usage controls open with only MCP tools access when Metabot is not configured but MCP is on", async () => {+ setup({+ aiControlsEnabled: true,+ isConfigured: false,+ mcpEnabled: true,+ initialRoute: "/admin/metabot/usage-controls/mcp-tools-access",+ });++ expect(await screen.findByText("AI Settings")).toBeInTheDocument();+ expect(+ screen.queryByText("Usage controls", {+ selector: '[data-disabled="true"] *',+ }),+ ).not.toBeInTheDocument();+ expect(getUsageControlLinks()).toEqual([+ "/admin/metabot/usage-controls/mcp-tools-access",+ ]);+ expect(+ screen.getByText("Customization", {+ selector: '[data-disabled="true"] *',+ }),+ ).toBeInTheDocument();+ });++ it("lists AI feature access, MCP tools access, and Limits under Usage controls when both features are on", async () => {+ setup({+ aiControlsEnabled: true,+ isConfigured: true,+ mcpEnabled: true,+ initialRoute: "/admin/metabot/usage-controls/ai-feature-access",+ });++ expect(await screen.findByText("AI Settings")).toBeInTheDocument();+ expect(+ screen.getByRole("link", { name: "AI feature access" }),+ ).toHaveAttribute(+ "href",+ "/admin/metabot/usage-controls/ai-feature-access",+ );+ expect(+ screen.getByRole("link", { name: "MCP tools access" }),+ ).toHaveAttribute("href", "/admin/metabot/usage-controls/mcp-tools-access");+ expect(screen.getByRole("link", { name: "Limits" })).toHaveAttribute(+ "href",+ "/admin/metabot/usage-controls/ai-usage-limits",+ );+ expect(getUsageControlLinks()).toEqual([+ "/admin/metabot/usage-controls/ai-feature-access",+ "/admin/metabot/usage-controls/mcp-tools-access",+ "/admin/metabot/usage-controls/ai-usage-limits",+ ]);+ expect(screen.queryByTestId("upsell-gem")).not.toBeInTheDocument();+ });++ it("lists AI feature access and Limits only when Metabot is configured and MCP is off", async () => {+ setup({+ aiControlsEnabled: true,+ isConfigured: true,+ mcpEnabled: false,+ initialRoute: "/admin/metabot/usage-controls/ai-feature-access",+ });++ expect(await screen.findByText("AI Settings")).toBeInTheDocument();+ expect(getUsageControlLinks()).toEqual([+ "/admin/metabot/usage-controls/ai-feature-access",+ "/admin/metabot/usage-controls/ai-usage-limits",+ ]);+ });+it("no longer exposes the Auditing folder or CLI analytics with audit_app", async () => {setup({ aiControlsEnabled: true, auditAppEnabled: true });@@ -131,4 +210,19 @@ describe("MetabotNavPane", () => {screen.getByRole("link", { name: "Authorizations" }),).toHaveAttribute("href", "/admin/metabot/mcp/authorizations");});++ it("keeps the MCP folder to Settings and Authorizations", async () => {+ setup({ aiControlsEnabled: true, initialRoute: "/admin/metabot/mcp" });++ const links = await screen.findAllByRole("link");+ const mcpLinks = links+ .filter((link) =>+ link.getAttribute("href")?.startsWith("/admin/metabot/mcp"),+ )+ .map((link) => link.getAttribute("href"));+ expect(mcpLinks).toEqual([+ "/admin/metabot/mcp",+ "/admin/metabot/mcp/authorizations",+ ]);+ });});diff --git a/frontend/src/metabase/admin/routes.tsx b/frontend/src/metabase/admin/routes.tsxindex 091f4359461..d7288929bdd 100644--- a/frontend/src/metabase/admin/routes.tsx+++ b/frontend/src/metabase/admin/routes.tsx@@ -126,7 +126,7 @@ const modelPersistence = () =>Component: ModelPersistenceConfiguration,}));-// `route.lazy` supplies a component and no props, so the three routes that+// `route.lazy` supplies a component and no props, so the four routes that// share this layout bind theirs here.const metabotLayout =(props: ComponentProps<typeof MetabotAdminLayout> = {}) =>@@ -387,6 +387,15 @@ export const getRoutes = (><Route path="mcp/authorizations" lazy={oauthAuthorizations} /></Route>+ <Route+ key="mcp-tools-access-layout"+ lazy={metabotLayout({+ fullWidth: true,+ innerContentProps: { fullWidth: true, fullHeight: true },+ })}+ >+ {PLUGIN_AI_CONTROLS.getMcpToolsAccessRoutes()}+ </Route><Routekey="layout"lazy={metabotLayout({diff --git a/frontend/src/metabase/plugins/oss/ai-controls.ts b/frontend/src/metabase/plugins/oss/ai-controls.tsindex 50e52107a93..304207d05c1 100644--- a/frontend/src/metabase/plugins/oss/ai-controls.ts+++ b/frontend/src/metabase/plugins/oss/ai-controls.ts@@ -5,12 +5,14 @@ import { definePluginSlot } from "../slot";export type AiControlsPlugin = {isEnabled: boolean;getAiControlsRoutes: () => ReactNode;+ getMcpToolsAccessRoutes: () => ReactNode;getAiControlsNavItems: () => ReactNode;};const getDefaultPluginAiControls = (): AiControlsPlugin => ({isEnabled: false,getAiControlsRoutes: () => null,+ getMcpToolsAccessRoutes: () => null,getAiControlsNavItems: () => null,});diff --git a/frontend/test/__support__/server-mocks/metabot.ts b/frontend/test/__support__/server-mocks/metabot.tsindex 53571a776a4..0c95e0c0f9d 100644--- a/frontend/test/__support__/server-mocks/metabot.ts+++ b/frontend/test/__support__/server-mocks/metabot.ts@@ -16,6 +16,7 @@ import type {LlmConnectionModels,LlmProviderConnection,LlmProviderType,+ McpToolPermissionsResponse,MetabotConversation,MetabotConversationTitleResponse,MetabotGroupLimit,@@ -508,6 +509,58 @@ export function setupUpdateMetabotGroupPermissionsEndpoint() {});}+const MCP_TOOL_PERMISSIONS_ROUTE_NAME = "mcp-tool-permissions";++export function setupMcpToolPermissionsEndpoint(+ response: McpToolPermissionsResponse,+) {+ fetchMock.removeRoute(MCP_TOOL_PERMISSIONS_ROUTE_NAME);+ fetchMock.get("path:/api/ee/ai-controls/mcp-permissions", response, {+ name: MCP_TOOL_PERMISSIONS_ROUTE_NAME,+ });+}++const UPDATE_MCP_TOOL_PERMISSIONS_ROUTE_NAME = "update-mcp-tool-permissions";++export function setupUpdateMcpToolPermissionsEndpoint(+ response: McpToolPermissionsResponse,+) {+ fetchMock.removeRoute(UPDATE_MCP_TOOL_PERMISSIONS_ROUTE_NAME);+ fetchMock.put("path:/api/ee/ai-controls/mcp-permissions", response, {+ name: UPDATE_MCP_TOOL_PERMISSIONS_ROUTE_NAME,+ });+}++const ENABLE_ADVANCED_MCP_TOOL_PERMISSIONS_ROUTE_NAME =+ "enable-advanced-mcp-tool-permissions";++export function setupEnableAdvancedMcpToolPermissionsEndpoint(+ response: McpToolPermissionsResponse,+) {+ fetchMock.removeRoute(ENABLE_ADVANCED_MCP_TOOL_PERMISSIONS_ROUTE_NAME);+ fetchMock.post(+ "path:/api/ee/ai-controls/mcp-permissions/advanced",+ response,+ {+ name: ENABLE_ADVANCED_MCP_TOOL_PERMISSIONS_ROUTE_NAME,+ },+ );+}++const DISABLE_ADVANCED_MCP_TOOL_PERMISSIONS_ROUTE_NAME =+ "disable-advanced-mcp-tool-permissions";++export function setupDisableAdvancedMcpToolPermissionsEndpoint(+ response: McpToolPermissionsResponse,+) {+ fetchMock.removeRoute(DISABLE_ADVANCED_MCP_TOOL_PERMISSIONS_ROUTE_NAME);+ fetchMock.delete(+ "path:/api/ee/ai-controls/mcp-permissions/advanced",+ response,+ { name: DISABLE_ADVANCED_MCP_TOOL_PERMISSIONS_ROUTE_NAME },+ );+}+const AI_CONTROLS_INSTANCE_LIMIT_ROUTE_NAME = "ai-controls-instance-limit";export function setupAIControlsInstanceLimitEndpoint(diff --git a/resources/migrations/065/20260916_mcp_group_permissions.yaml b/resources/migrations/065/20260916_mcp_group_permissions.yamlnew file mode 100644index 00000000000..38dfb6b3cfb--- /dev/null+++ b/resources/migrations/065/20260916_mcp_group_permissions.yaml@@ -0,0 +1,101 @@+## Per-group MCP tool access: one row per permissions group, whether its members may connect to the MCP server+## and which tools an admin has explicitly allowed or denied them.++databaseChangeLog:+ - changeSet:+ id: v65.2026-09-16T00:00:00+ author: alxnddr+ comment: Create mcp_group_permission table for per-group MCP tool access+ changes:+ - createTable:+ tableName: mcp_group_permission+ remarks: MCP access and per-tool overrides per permissions group+ columns:+ - column:+ name: id+ type: int+ autoIncrement: true+ constraints:+ primaryKey: true+ nullable: false+ - column:+ name: group_id+ type: int+ remarks: The ID of the associated permissions group+ constraints:+ nullable: false+ - column:+ name: mcp_enabled+ type: ${boolean.type}+ remarks: Whether members of the group may connect to the MCP server+ constraints:+ nullable: false+ - column:+ name: tool_access+ type: ${text.type}+ remarks: JSON object from MCP tool name to yes or no; an absent tool takes the author's default+ constraints:+ nullable: false+ - column:+ name: created_at+ type: ${timestamp_type}+ remarks: The timestamp this row was created+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false+ - column:+ name: updated_at+ type: ${timestamp_type}+ remarks: The timestamp this row was last updated+ defaultValueComputed: current_timestamp+ constraints:+ nullable: false++ ## The unique constraint doubles as the index behind the FK: MySQL/MariaDB reuse it, and Postgres has no+ ## auto-indexed FKs (fks-are-indexed-test checks).+ - changeSet:+ id: v65.2026-09-16T00:00:01+ author: alxnddr+ comment: Add unique constraint on mcp_group_permission.group_id+ changes:+ - addUniqueConstraint:+ tableName: mcp_group_permission+ columnNames: group_id+ constraintName: unique_mcp_group_permission_group_id++ - changeSet:+ id: v65.2026-09-16T00:00:02+ author: alxnddr+ comment: Add foreign key on mcp_group_permission.group_id referencing permissions_group+ changes:+ - addForeignKeyConstraint:+ baseTableName: mcp_group_permission+ baseColumnNames: group_id+ referencedTableName: permissions_group+ referencedColumnNames: id+ constraintName: fk_mcp_group_permission_ref_permissions_group+ onDelete: CASCADE++ - changeSet:+ id: v65.2026-09-16T00:00:03+ author: alxnddr+ comment: Enable MCP with no tool overrides for the groups simple mode shows+ changes:+ - sql:+ sql: >-+ INSERT INTO mcp_group_permission (group_id, mcp_enabled, tool_access)+ SELECT pg.id, TRUE, '{}'+ FROM permissions_group pg+ WHERE pg.magic_group_type IN ('admin', 'all-internal-users', 'all-external-users')+ AND NOT EXISTS (+ SELECT 1 FROM mcp_group_permission mgp+ WHERE mgp.group_id = pg.id+ )+ rollback:+ - sql:+ sql: >-+ DELETE FROM mcp_group_permission+ WHERE group_id IN (+ SELECT id FROM permissions_group+ WHERE magic_group_type IN ('admin', 'all-internal-users', 'all-external-users')+ )diff --git a/src/metabase/agent_api/query_guards.clj b/src/metabase/agent_api/query_guards.cljindex 381215e1417..13144f67cd2 100644--- a/src/metabase/agent_api/query_guards.clj+++ b/src/metabase/agent_api/query_guards.clj@@ -202,20 +202,24 @@The query endpoints declare no `:scope` of their own, so the endpoint scope middleware cannot tell a nativequery apart from any other one: [[metabase.mcp.ui-surface/request-surface]] charges the whole `/api/dataset`tree a single `agent:query:run`, and every credential minted for a client holding that scope satisfies it.- Raw SQL costs more, and that difference is spent here: it needs an SQL-execution scope- (`agent:sql:run`, or v1's concrete `agent:sql:execute`) off the credential's signed claim, and the- `mcp-execute-sql-enabled` kill switch.+ Raw SQL costs more, and that difference is spent here: it needs the user's groups to allow the `execute_sql`+ MCP tool, which `check-execute-sql-allowed!` (a no-arg fn that throws when they do not) decides, an+ SQL-execution scope (`agent:sql:run`, or v1's concrete `agent:sql:execute`) off the credential's signed claim,+ and the `mcp-execute-sql-enabled` kill switch.A credential whose claim is simply absent fails closed: a rolling deploy can hand this node one minted beforethe claim existed.Native is refused rather than banned because `execute_sql` handles legitimately hold raw SQL and are visualizableby design. Non-native queries, and requests authenticated any other way, pass straight through."- [request query]+ [check-execute-sql-allowed! request query];; Keyed on the credential, not on its scopes claim, so a credential carrying no claim is refused rather than;; waved through — a rolling deploy can hand this node one minted before the claim existed.(when-let [claims (:mcp-ui-credential request)](when (native-query? query)+ ;; Read per request rather than stamped on the credential, so an admin's denial applies to credentials+ ;; already minted.+ (check-execute-sql-allowed!);; Scope check first, kill switch second: a client that lacks the SQL-execution scope is refused;; the same way whether or not the instance has raw SQL enabled. Testing the kill switch first;; would leak that config bit — an unauthorized caller could tell `mcp-execute-sql-enabled`'s@@ -233,12 +237,13 @@{:status-code 403}))))))(defn +refuse-unscoped-native-sql- "Ring middleware applying [[check-mcp-ui-native-query!]] to a route tree, reading the query from the request- body.+ "Ring middleware applying [[check-mcp-ui-native-query!]], with `check-execute-sql-allowed!`, to a route tree,+ reading the query from the request body.It rides the route rather than the endpoints because the endpoints cannot reach it: `agent-api` already`:uses` `query-processor`, so a call from inside `metabase.query-processor.api` would close a module cycle.- `api-routes` is `:uses :any` and is where the two modules legitimately meet.+ `api-routes` is `:uses :any` and is where the two modules legitimately meet. The same holds for the group+ policy, which `mcp` owns and `mcp` already `:uses` `agent-api`, so `api-routes` passes it in.Applying it to the whole `/api/dataset` tree rather than to the two executing routes is deliberate: theguard is keyed on `:mcp-ui-credential`, which the session middleware attaches only for the routes on the@@ -248,10 +253,10 @@JSON-string `query` edge rather than assuming the already-decoded shape: `/api/dataset/:export-format`takes one, this middleware runs ahead of Malli's `:decode/api`, and that route is off the allowlist onlyfor now."- [handler]+ [check-execute-sql-allowed! handler](fn [request respond raise](try- (check-mcp-ui-native-query! request (:body request))+ (check-mcp-ui-native-query! check-execute-sql-allowed! request (:body request))(handler request respond raise)(catch Throwable e(raise e)))))diff --git a/src/metabase/api_routes/routes.clj b/src/metabase/api_routes/routes.cljindex e02135f5ffa..967c67ae280 100644--- a/src/metabase/api_routes/routes.clj+++ b/src/metabase/api_routes/routes.clj@@ -40,6 +40,7 @@[metabase.logger.api][metabase.login-history.api][metabase.mcp.callback-api]+ [metabase.mcp.core :as mcp][metabase.mcp.v2.api][metabase.measures.api][metabase.metabot.api]@@ -212,11 +213,13 @@;; endpoint scope middleware cannot hold the `agent:sql:run` line here. The credential carries the minting;; token's scopes as a signed claim (unrestricted only when minted from an unrestricted session: a cookie or;; API-key session, or an `mb:full` bearer token), and the guard- ;; spends that claim to stop a credential without `agent:sql:run` from POSTing raw SQL. The spec-generation+ ;; spends that claim to stop a credential without `agent:sql:run` from POSTing raw SQL, and MCP's group+ ;; policy to stop a user denied `execute_sql`. The spec-generation;; wrapper keeps the guard transparent to [[metabase.api.open-api/open-api-spec]] — a bare middleware fn here;; fails openapi.json generation for the whole /api tree."/dataset" (+auth ((routes.common/wrap-middleware-for-open-api-spec-generation- agent-api.query-guards/+refuse-unscoped-native-sql)+ (partial agent-api.query-guards/+refuse-unscoped-native-sql+ #'mcp/check-execute-sql-allowed!))(api.macros/ns-handler 'metabase.query-processor.api)))"/docs" (metabase.api.docs/make-routes #'routes)"/document" (+auth metabase.documents.api/routes)diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.cljindex abe371c9dcc..2510a8563db 100644--- a/src/metabase/cmd/copy.clj+++ b/src/metabase/cmd/copy.clj@@ -163,7 +163,8 @@:model/TransformJobRun:model/TransformRun:model/TransformRunCancelation- :model/TransformDagRun]+ :model/TransformDagRun+ :model/McpGroupPermission](when config/ee-available?[:model/MetabotGroupLimit:model/MetabotInstanceLimitdiff --git a/src/metabase/mcp/README.md b/src/metabase/mcp/README.mdindex 67c2078c95f..d37e8416252 100644--- a/src/metabase/mcp/README.md+++ b/src/metabase/mcp/README.md@@ -99,6 +99,10 @@ login, the model should name the failed tool or resource and the permission it rreconnecting and leaving the permission ticked on the consent screen. The instructions are one static string, the samefor every caller: there is no per-connection permission list.+### Per-group tool access++On Enterprise instances with the `ai_controls` feature, an admin can narrow the surface per permissions group on Admin > AI > Usage controls > MCP tools access (shown whenever the MCP server is on, with or without an LLM provider). Each group has a row in `mcp_group_permission` saying whether its members may connect at all and, per tool name, the admin's explicit `"yes"` or `"no"`; a tool with no entry takes the default its author declared, so every `deftool` carries a required `:default-access` of `:allowed` or `:denied` and a tool released later gets exactly that default in every group until an admin overrides it. Entries are keyed by tool name, so renaming a tool needs `:renamed-from` with its former names (a stored entry under a former name still applies and the admin API presents it under the current name), or the author accepts that every admin's choice for it is discarded; `metabase.mcp.v2.tool-names-test` pins the live names so neither happens by accident. A user's effective policy is the `tool_access` of each group of theirs whose row enables MCP: MCP is on when any such group exists, and a tool is allowed when any of those groups resolves it to yes. The rows alone decide it, and they also record the permission mode: simple mode (Administrators, All Users, and All tenant users) or group-level mode (every other group), which is the state in which All Users has no row. A switch deletes the rows of the groups the new mode hides and seeds the groups it enables on entry that have no row (Data Analysts on entering group-level mode, All Users and All tenant users on leaving it), and `PUT` refuses a group the current mode hides, so no request reads a cached mode. The policy is applied on top of OAuth scopes in `tools/list` and `tools/call` (`v2/registry.clj`), and a user whose groups grant no access is refused at `initialize` and at `resources/read` (for sessions opened before MCP was turned off) with an error naming the fix. App-only tools (`_meta {:ui {:visibility ["app"]}}`, i.e. `refresh_ui_credential`) are not on the admin page: they are allowed while the policy allows any MCP Apps tool. Superusers and internal callers are never narrowed; OSS allows everything. On Enterprise the stored rows are enforced even without the `ai_controls` feature (an expired or unverifiable token keeps the restrictions an admin configured); the feature only gates the admin page and API. The resolver is `permissions.clj` (`defenterprise`, EE implementation in `metabase-enterprise.mcp.permissions`) and the admin API is `/api/ee/ai-controls/mcp-permissions`.+## Available toolsGenerated from the v2 registry (`deftool`). The scope named here is what the registry checks before the tooldiff --git a/src/metabase/mcp/core.clj b/src/metabase/mcp/core.cljindex d8d2c9bb577..d0fcb3f7217 100644--- a/src/metabase/mcp/core.clj+++ b/src/metabase/mcp/core.clj@@ -8,7 +8,9 @@[metabase.mcp.session :as mcp.session][metabase.mcp.settings :as mcp.settings][metabase.mcp.ui-surface :as mcp.ui-surface]- [metabase.mcp.usage :as mcp.usage]))+ [metabase.mcp.usage :as mcp.usage]+ [metabase.mcp.v2.message :as message]+ [metabase.mcp.v2.registry :as registry]))(set! *warn-on-reflection* true)@@ -54,6 +56,14 @@[client-info-name](mcp.settings/inline-ui-enabled-for-client? (mcp.usage/detect-client client-info-name)))+(defn check-execute-sql-allowed!+ "Throw a 403 unless the current user's groups allow the `execute_sql` tool, for raw SQL reaching the REST API other+ than through that tool."+ []+ (when-let [denial (registry/tool-denial "execute_sql" (message/raw "Running a native (SQL) query"))]+ ;; Not a teaching error: the message record in its ex-data would turn this REST 403 into a stack trace.+ (throw (ex-info (message/render denial) {:status-code 403}))))+(defn vscode-webview-enabled?"Returns true if vscode/cursor is enabled in common MCP apps."[]diff --git a/src/metabase/mcp/db.clj b/src/metabase/mcp/db.cljindex 569ca30d54b..04b3c6d46d1 100644--- a/src/metabase/mcp/db.clj+++ b/src/metabase/mcp/db.clj@@ -261,6 +261,11 @@:subscriptions[:handlers :channel [:recipients :recipients-detail]]))+(defn group-permission-exists?+ "Whether some McpGroupPermission matches `where`, a HoneySQL condition such as `[:in :group_id ids]`."+ [where]+ (t2/exists? :model/McpGroupPermission {:where where}))+(defn user-id->tenant-id"Map of user id to `tenant_id` for `user-ids`, in one query. An empty collection asks nothing of thedatabase and answers `{}` — `[:in ()]` is not valid SQL.diff --git a/src/metabase/mcp/models/mcp_group_permission.clj b/src/metabase/mcp/models/mcp_group_permission.cljnew file mode 100644index 00000000000..8231541f959--- /dev/null+++ b/src/metabase/mcp/models/mcp_group_permission.clj@@ -0,0 +1,69 @@+(ns metabase.mcp.models.mcp-group-permission+ "Toucan 2 model registration for `:model/McpGroupPermission`: one row per permissions group holding whether its+ members may connect to the MCP server and, per tool name, the admin's explicit `\"yes\"` or `\"no\"`."+ (:require+ [metabase.api.common :as api]+ [metabase.mcp.db :as mcp.db]+ [metabase.mcp.permissions :as mcp.perms]+ [metabase.mcp.v2.registry :as registry]+ [metabase.metabot.usage-controls :as usage-controls]+ [metabase.models.interface :as mi]+ [metabase.permissions.core :as perms]+ [metabase.util :as u]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.malli.registry :as mr]+ [methodical.core :as methodical]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(methodical/defmethod t2/table-name :model/McpGroupPermission [_model] :mcp_group_permission)++(doto :model/McpGroupPermission+ (derive :metabase/model)+ (derive ::mi/read-policy.superuser)+ (derive ::mi/write-policy.superuser)+ (derive ::mi/create-policy.superuser)+ (derive :hook/timestamped?))++(t2/deftransforms :model/McpGroupPermission+ {:tool_access mi/transform-json-no-keywordization})++(defn- check-tool-access+ "Throw a 400 unless every value in `tool-access` is `\"yes\"` or `\"no\"` and every name is a registered tool, a+ former name of one, or in `stored`, the names the row held before, so an entry for a tool removed since it was saved+ never blocks a save."+ [tool-access stored]+ (api/check-400 (mr/validate ::mcp.perms/tool-access tool-access)+ (tru "Every MCP tool must be \"yes\" or \"no\""))+ (let [known (into (set (keys (registry/renamed-tool-names))) (map :name) (registry/tool-catalog))]+ (doseq [tool-name (keys tool-access)]+ (api/check-400 (or (known tool-name) (stored tool-name)) (tru "Unknown MCP tool: {0}" tool-name)))))++(defn- check-one-mode+ "Throw a 400 when a row for the group with `group-id` would sit beside rows of the other permission mode: All Users+ and All tenant users have rows only in simple mode, every group but them and Administrators only in group-level+ mode."+ [group-id]+ (when-not (= (u/the-id (perms/admin-group)) group-id)+ (let [advanced? (not-any? #{group-id} (usage-controls/simple-mode-group-ids))]+ (api/check-400 (not (mcp.db/group-permission-exists?+ [:not (usage-controls/visible-groups-clause :group_id advanced?)]))+ (if advanced?+ (tru "Group {0} can''t have an MCP policy while All Users has one" (str group-id))+ (tru "All Users can''t have an MCP policy while groups have their own"))))))++(t2/define-before-insert :model/McpGroupPermission+ [{:keys [group_id tool_access] :as row}]+ (check-tool-access tool_access #{})+ (check-one-mode group_id)+ row)++(t2/define-before-update :model/McpGroupPermission+ [row]+ (let [changes (t2/changes row)]+ (when (contains? changes :tool_access)+ (check-tool-access (:tool_access changes) (set (keys (:tool_access (t2/original row))))))+ (when (contains? changes :group_id)+ (check-one-mode (:group_id changes))))+ row)diff --git a/src/metabase/mcp/permissions.clj b/src/metabase/mcp/permissions.cljnew file mode 100644index 00000000000..5b0c8c73496--- /dev/null+++ b/src/metabase/mcp/permissions.clj@@ -0,0 +1,75 @@+(ns metabase.mcp.permissions+ "Per-group MCP tool access: each permissions group that enables MCP carries the admin's explicit `\"yes\"` or+ `\"no\"` per tool, a tool without an entry takes the default its author declared, and a user may use a tool when+ any of their groups allows it."+ (:require+ [metabase.api.common :as api]+ [metabase.premium-features.core :refer [defenterprise]]+ [metabase.util.malli :as mu]+ [metabase.util.malli.registry :as mr]+ [metabase.util.malli.schema :as ms]))++(set! *warn-on-reflection* true)++(def ^:private access-values+ "The two things an admin can say about a tool."+ #{"yes" "no"})++(mr/def ::tool-access+ "One group's overrides: MCP tool name to `\"yes\"` or `\"no\"`. An absent name means the tool's `:default-access`."+ [:and+ (ms/string-keyed-map :string)+ ;; Checked over the whole map: the API decoder strips a `:map-of` entry whose value fails, and a dropped entry+ ;; would fall back to the tool's default instead of refusing the request.+ [:fn {:error/message "every tool must be \"yes\" or \"no\""} #(every? access-values (vals %))]])++(mr/def ::policy+ "A user's effective MCP policy: `:unrestricted`, or the [[::tool-access]] of every group of theirs that enables+ MCP and that the current permission mode shows. Empty means no access."+ [:or [:= :unrestricted] [:sequential ::tool-access]])++(mr/def ::tool+ "A registry entry, of which [[tool-allowed?]] reads the name, the author's default, and the former names."+ [:map {::mr/deliberately-open true}+ [:name :string]+ [:default-access [:enum :allowed :denied]]+ [:renamed-from {:optional true} [:sequential :string]]])++(def unrestricted-policy+ "The policy of a caller nothing narrows: superusers, internal callers with no current user, and every OSS user."+ :unrestricted)++(defenterprise effective-policy+ "The [[::policy]] of the User with `user-id`, folded over the groups the current permission mode shows. OSS+ allows everything."+ metabase-enterprise.mcp.permissions+ [_user-id]+ unrestricted-policy)++(mu/defn policy-for-current-user :- ::policy+ "The [[::policy]] of `api/*current-user-id*`. Superusers and internal callers (no current user) are unrestricted."+ []+ (if (or (nil? api/*current-user-id*) api/*is-superuser?*)+ unrestricted-policy+ (effective-policy api/*current-user-id*)))++(mu/defn enabled? :- :boolean+ "Whether `policy` lets its user connect to the MCP server at all."+ [policy :- ::policy]+ (boolean (or (= unrestricted-policy policy) (seq policy))))++(mu/defn- group-allows? :- :boolean+ "Whether one group's `tool-access` lets its members use `tool`: its entry under the tool's name, else under the+ first `:renamed-from` name it holds, else the tool's `:default-access`."+ [tool-access :- ::tool-access+ {tool-name :name :keys [default-access renamed-from]} :- ::tool]+ (if-let [access (some tool-access (cons tool-name renamed-from))]+ (= "yes" access)+ (= :allowed default-access)))++(mu/defn tool-allowed? :- :boolean+ "Whether `policy` lets its user see and call the registry entry `tool`: unrestricted, or some group allows it."+ [policy :- ::policy+ tool :- ::tool]+ (boolean (or (= unrestricted-policy policy)+ (some #(group-allows? % tool) policy))))diff --git a/src/metabase/mcp/transport.clj b/src/metabase/mcp/transport.cljindex 8f73c24ea2f..5c0ef04bc0d 100644--- a/src/metabase/mcp/transport.clj+++ b/src/metabase/mcp/transport.clj@@ -15,6 +15,7 @@[metabase.api.macros.scope :as scope][metabase.api.open-api :as open-api][metabase.mcp.core :as mcp]+ [metabase.mcp.permissions :as mcp.perms][metabase.mcp.session :as mcp.session][metabase.mcp.usage :as mcp.usage][metabase.mcp.v2.common :as v2.common]@@ -74,6 +75,12 @@:serverInfo server-info}instructions (assoc :instructions instructions))))+(def mcp-access-disabled-message+ "The refusal for a user whose groups grant no MCP access, at `initialize` and on requests of a session opened+ before an admin turned MCP off."+ (message/msg [(str "MCP access is not enabled for your account. "+ "Ask an administrator to enable it under Admin > AI > Usage controls > MCP tools access.")]))+(defn- mcp-app-ui-capability?"Return true if initialize params advertise support for MCP Apps HTML resources."[params]@@ -368,6 +375,10 @@(and batch? (some #(and (valid-message? %) (= "initialize" (:method %))) body))(json-response 400 (jsonrpc-error nil -32600 (message/msg ["initialize must not be batched"])))+ (and (not batch?) (valid-message? body) (= "initialize" (:method body))+ (not (mcp.perms/enabled? (mcp.perms/policy-for-current-user))))+ (json-response 403 (jsonrpc-error (:id body) v2.common/error-code-invalid-request mcp-access-disabled-message))+;; Initialize: create session and return response with session header(and (not batch?) (valid-message? body) (= "initialize" (:method body)))(let [params (:params body)@@ -464,23 +475,40 @@;; threads have no such ceiling and cost nothing while parked.(Executors/newThreadPerTaskExecutor (.. (Thread/ofVirtual) (name "mcp-keepalive-" 0) factory)))+(defn- read-tools-hash+ "`[hash failed?]`: `(tools-hash-fn)` and false, or `fallback` and true when it throws. The hash reads the user's+ group policy from the app database, and a failed read must not end a stream that is otherwise healthy.+ `failing?` says the previous read failed too, so a sustained failure warns once rather than every tick."+ [tools-hash-fn fallback failing?]+ (try+ [(tools-hash-fn) false]+ (catch Exception e+ (if failing?+ (log/debug e "Still could not hash the MCP tool list for the keepalive stream; keeping the previous hash")+ (log/warn e "Could not hash the MCP tool list for the keepalive stream; keeping the previous hash"))+ [fallback true])))+(defn- keepalive-loop!"Emit SSE keepalive comments on `writer` every `interval-ms` until `canceled-chan` reports the client is gone.Re-reads the tool manifest hash on each tick and emits `notifications/tools/list_changed` when it differs from the- previous tick, so the client knows to refetch `tools/list`. Returns nil once canceled."+ previous tick, so the client knows to refetch `tools/list`; a tick whose hash fails keeps the previous one. Returns+ nil once canceled."[^Writer writer tools-hash-fn canceled-chan interval-ms]- (loop [last-hash (tools-hash-fn)]+ (loop [[last-hash failing?] (read-tools-hash tools-hash-fn nil false)](.write writer ": keepalive\n\n")(.flush writer);; Park on the cancellation channel instead of sleeping through the interval: the cancel loop notices a;; disconnected client within a second, and waiting on it releases this thread then rather than at the next tick.- (let [[_ port] (a/alts!! [canceled-chan (a/timeout interval-ms)])]+ ;; `:priority` so a cancellation already delivered wins over a timeout that is ready too.+ (let [[_ port] (a/alts!! [canceled-chan (a/timeout interval-ms)] :priority true)](when-not (= port canceled-chan)- (let [current-hash (tools-hash-fn)]- (when (not= current-hash last-hash)+ (let [[current-hash :as read] (read-tools-hash tools-hash-fn last-hash failing?)]+ ;; A nil `last-hash` means no read has succeeded yet, so the first that does seeds it rather than+ ;; announcing a change.+ (when (and last-hash (not= current-hash last-hash))(.write writer ^String (sse-body [tools-list-changed-notification]))(.flush writer))- (recur current-hash))))))+ (recur read))))))(def ^:private max-concurrent-keepalive-streams"How many GET keepalive streams one user may hold open at once.diff --git a/src/metabase/mcp/v2/api.clj b/src/metabase/mcp/v2/api.cljindex 18437fcf850..fcf7a8379ff 100644--- a/src/metabase/mcp/v2/api.clj+++ b/src/metabase/mcp/v2/api.clj@@ -8,6 +8,7 @@[clojure.string :as str][metabase.api.common :as api][metabase.mcp.paths :as mcp.paths]+ [metabase.mcp.permissions :as mcp.perms][metabase.mcp.scope :as mcp.scope][metabase.mcp.session :as mcp.session][metabase.mcp.transport :as transport]@@ -108,8 +109,16 @@(defn- handle-resources-read [id params session-id token-scopes](let [uri (:uri params)]- (if (or (not (string? uri)) (str/blank? uri))+ (cond+ ;; `initialize` checks this too, but a session opened before an admin turned MCP off for the user's groups+ ;; would otherwise keep reading.+ (not (mcp.perms/enabled? (mcp.perms/policy-for-current-user)))+ (transport/jsonrpc-error id common/error-code-invalid-request transport/mcp-access-disabled-message)++ (or (not (string? uri)) (str/blank? uri))(transport/jsonrpc-error id -32602 (message/msg ["Missing required parameter: uri"]))++ :else;; The scoped credential the iframe authenticates with. Since #81041 the browser receives it;; through the `refresh_ui_credential` tool; the shell's render-fn still forces this delay for;; templates that embed it (the test fallback), and the production template discards it.@@ -151,6 +160,18 @@(transport/jsonrpc-error id -32601 (message/msg ["Method not found: %s"] method))nil)))+;;; ---------------------------------------------------- Catalog ---------------------------------------------------++(defn tool-catalog+ "Every tool on this surface as `{:name :scope :description :default_access}`, sorted by scope then name."+ []+ (registry/tool-catalog))++(defn renamed-tool-names+ "Every former name a tool on this surface declares, as `{former-name current-name}`."+ []+ (registry/renamed-tool-names))+;;; ---------------------------------------------------- Handler ---------------------------------------------------(def +mcp-enabled@@ -160,15 +181,13 @@(def ^:private server-instructions"The `initialize` result's `instructions` — the only channel that reaches the model before any tool call. It pointsat the `learn` skills and the `glossary` once, settles the routing choices a model makes before reading any tool- description closely- (structured queries are the default, raw SQL the escape hatch, `visualize_query` for charts when listed), and- explains the scope-denial failures that clients rewrite before the model sees them."- (str "This server ships task-shaped docs as skills. learn() lists the topics; learn(topic) returns one.\n"+ description closely (structured queries are the default, raw SQL the escape hatch, `visualize_query` for charts),+ and explains the scope-denial failures that clients rewrite before the model sees them."+ (str "learn() lists task-shaped docs (skills) by topic; learn(topic) returns one.\n""Before your first complex write — native template_tags, dashboard parameter wiring, a multi-stage or joined ""query, visualization settings — read the matching skill unless it is already in context.\n"- "This instance's glossary defines business terms that matter for answering questions about its data. Fetch "- "them with glossary() before you answer — an instance's own definition of a term overrides your reading of "- "it.\n"+ "This instance's glossary defines business terms used in its data. Fetch them with glossary() before you "+ "answer — an instance's own definition of a term overrides your reading of it.\n""Answer questions from data with execute_query (structured MBQL) by default; execute_sql is the escape hatch ""for what MBQL cannot express or an explicit request for SQL.\n""When visualize_query is available, use it for any request to show, chart, plot, or visualize data (pass a "@@ -180,8 +199,8 @@;; for. The unfiltered tool list needs saying because a scope-filtered list is the conventional design and the;; protocol has no field to signal ours: asked what this connection could do, a model read the roster as a;; grant and answered with scopes it did not hold.- "Every tool is listed whatever this connection holds, so the list says nothing about its permissions; only a "- "failed call reveals a missing one.\n"+ "Tools are listed whatever this connection holds, so the list says nothing about its permissions; only a "+ "failed call reveals a missing one. An unlisted tool is off for this user: ignore advice here about it.\n""An auth error (\"re-authorization\", \"expired token\", \"insufficient scope\", \"Unauthorized\", \"tool ""execution failed\") usually means a missing permission, not an expired login. When a tool call or resource ""read needs a permission this connection lacks, tell the user which tool or resource failed, which permission "@@ -194,7 +213,7 @@(def ^:private default-ask-scopes"The `scope` of the 401 challenge, which an uninstructed client requests on first connect. Every scope here must beinside the OAuth server's default grant ceiling."- ;; Every tool is listed whatever the token holds. A call needing a scope the token lacks is answered with a 403+ ;; Tools are listed whatever scopes the token holds. A call needing a scope the token lacks is answered with a 403;; `insufficient_scope` naming the union of held and required scopes, so a client steps up to the rest of the surface;; rather than being granted it up front. Each tool also declares its scope in `securitySchemes`, which is draft;; SEP-1488 (modelcontextprotocol issue 1488) and supported by ChatGPT; it is not in MCP 2025-03-26, the version thisdiff --git a/src/metabase/mcp/v2/registry.clj b/src/metabase/mcp/v2/registry.cljindex 0884d8bb371..2af7a385b18 100644--- a/src/metabase/mcp/v2/registry.clj+++ b/src/metabase/mcp/v2/registry.clj@@ -23,6 +23,7 @@[metabase.api-scope.core :as api-scope][metabase.api.common :as api][metabase.api.macros.defendpoint.tools-manifest :as tools-manifest]+ [metabase.mcp.permissions :as mcp.perms][metabase.mcp.scope :as mcp.scope][metabase.mcp.ui-resource :as mcp.ui-resource][metabase.mcp.usage :as mcp.usage]@@ -44,11 +45,15 @@(defonce ^:private manifest-cache(atom nil))+(def ^:private default-accesses+ "What a tool's `:default-access` may be: whether a group without an entry for the tool may use it."+ #{:allowed :denied})+(defn register-tool!"Register a v2 tool definition.Does basic validation of arguments and throws when invalid."- [{tool-name :name :keys [scope description args handler] :as tool}]+ [{tool-name :name :keys [scope description args handler default-access renamed-from] :as tool}](when (str/blank? tool-name)(throw (ex-info "v2 MCP tool registered without a :name" {:tool tool})))(doseq [[k v] {:scope scope :description description}]@@ -64,10 +69,18 @@;; Dispatch gates on :required-extensions, so a misspelled key (:require-extensions,;; :requires-extension) would silently disable the gate — reject unknown keys loudly instead.(when-let [unknown (seq (remove #{:name :scope :description :args :handler :annotations- :output-schema :required-extensions :title :_meta}+ :output-schema :required-extensions :title :_meta+ :default-access :renamed-from}(keys tool)))](throw (ex-info (format "v2 MCP tool %s registered with unknown option(s) %s" tool-name (vec unknown)){:tool-name tool-name :unknown-keys (vec unknown)})))+ (when-not (default-accesses default-access)+ (throw (ex-info (format "v2 MCP tool %s registered without a :default-access of :allowed or :denied" tool-name)+ {:tool-name tool-name :default-access default-access})))+ (when (contains? tool :renamed-from)+ (when-not (and (vector? renamed-from) (seq renamed-from) (not-any? str/blank? renamed-from))+ (throw (ex-info (format "v2 MCP tool %s :renamed-from must be a non-empty vector of former names" tool-name)+ {:tool-name tool-name :renamed-from renamed-from}))));; Only the extensions a client can actually advertise are gateable: an unknown keyword is never in;; `ui-resource/supported-extensions`'s output, so the tool would be hidden from and refused to every;; client forever, with no error to say why.@@ -101,10 +114,11 @@(deftool echo\"Echo the message back.\"- {:name \"echo\"- :scope metabot.scope/agent-content-read- :annotations {:readOnlyHint true}- :args [:map …]}+ {:name \"echo\"+ :scope metabot.scope/agent-content-read+ :default-access :allowed+ :annotations {:readOnlyHint true}+ :args [:map …]}[arguments context]…)@@ -121,6 +135,12 @@`opts` is a map of:- `:name` - the mcp public-facing name of the tool- `:scope` - the required scope for the tool, published as `securitySchemes`+ - `:default-access` - `:allowed` or `:denied`: whether a permissions group whose admin has not said+ yes or no to this tool may use it. Group rows are keyed by tool name, so a new tool gets exactly+ this until an admin overrides it+ - `:renamed-from` - _optional_ - vector of the tool's former names. A group's stored yes or no under+ a former name still applies to the tool, and the admin API presents it under the current name;+ without it a rename silently discards every admin's choice for the tool- `:annotations` - _optional_ - overrides for the default annotations- `:args` - malli schema for the arguments, published as `inputSchema`- `:output-schema` - _optional_ - malli schema for the structured output, published as `outputSchema`@@ -154,6 +174,52 @@(map :scope)(vals @tools*)))+(defn- first-sentence+ "The opening sentence of a tool `description`, ending in a period."+ [description]+ (let [flat (str/replace description #"\s+" " ")+ sentence (first (str/split flat #"(?<!\be\.g|\bi\.e)\.\s+" 2))]+ (cond-> sentence+ (not (str/ends-with? sentence ".")) (str "."))))++(defn- app-only?+ "Whether `tool` is called only by an MCP App iframe, never by the model, like `refresh_ui_credential`."+ [tool]+ (= ["app"] (get-in tool [:_meta :ui :visibility])))++(defn- tool-allowed?+ "Whether `policy` lets its user use `tool`. An app-only tool has no row on the admin's grid: it is allowed while+ the policy allows any MCP Apps tool, since those are what call it."+ [policy tool]+ (if (app-only? tool)+ (boolean (some #(and (seq (:required-extensions %))+ (not (app-only? %))+ (mcp.perms/tool-allowed? policy %))+ (vals @tools*)))+ (mcp.perms/tool-allowed? policy tool)))++(defn tool-catalog+ "Every registered tool an admin can allow or deny, as `{:name :scope :description :default_access}`, sorted by+ scope then name; `:description` is the first sentence of the tool's own and `:default_access` is `\"allowed\"` or+ `\"denied\"`. App-only tools are left out, since [[tool-allowed?]] derives their access."+ []+ (->> (vals @tools*)+ (remove app-only?)+ (map (fn [{:keys [default-access] :as tool}]+ (-> (select-keys tool [:name :scope :description])+ (update :description first-sentence)+ (assoc :default_access (name default-access)))))+ (sort-by (juxt :scope :name))+ vec))++(defn renamed-tool-names+ "Every former name a registered tool declares in `:renamed-from`, as `{former-name current-name}`."+ []+ (into {}+ (for [{tool-name :name :keys [renamed-from]} (vals @tools*)+ former renamed-from]+ [former tool-name])))+;;; ------------------------------------------------ Manifest ------------------------------------------------------(def ^:private default-annotations@@ -214,28 +280,32 @@(reset! manifest-cache (generate-manifest))))(defn list-tools- "Return the tool definitions for the v2 MCP `tools/list` response, filtered by the client- extensions `options` advertises (`:supports-mcp-ui?` — MCP Apps tools are hidden from clients- that can't render an iframe rather than failing at call time). Token scopes don't filter the- list; [[call-tool]] enforces them. The 0-arity assumes full extension support."+ "Return the tool definitions for the v2 MCP `tools/list` response, filtered by the current user's+ per-group policy ([[metabase.mcp.permissions/policy-for-current-user]]) and by the client extensions+ `options` advertises (`:supports-mcp-ui?` — MCP Apps tools are hidden from clients that can't render+ an iframe rather than failing at call time). Token scopes don't filter the list; [[call-tool]]+ enforces them. The 0-arity assumes full extension support."([];; Full support because [[tools-hash]] has no session, so the hash must not depend on per-session capabilities.(list-tools {:supports-mcp-ui? true}))([options]- (let [supported (mcp.ui-resource/supported-extensions options)]+ (let [supported (mcp.ui-resource/supported-extensions options)+ policy (mcp.perms/policy-for-current-user)](into [](comp;; has all required extensions(filter #(empty? (mcp.ui-resource/missing-required-extensions % supported)))+ ;; the user's groups allow it+ (filter #(tool-allowed? policy %))(map #(select-keys % [:name :title :description :inputSchema :outputSchema :annotations:securitySchemes :_meta])))(manifest)))))(defn tools-hash- "Stable 8-character hex hash of the listed tools; polled by the GET/SSE keepalive to emit- `notifications/tools/list_changed` when the set changes (feature flips). Hashes the JSON- encoding of the wire-visible schema, so the result never depends on Clojure's `hash` of- non-data leaves."+ "Stable 8-character hex hash of the tools listed for the current user; polled by the GET/SSE+ keepalive to emit `notifications/tools/list_changed` when the set changes (feature flips, an admin+ editing the user's group policy). Hashes the JSON encoding of the wire-visible schema, so the result+ never depends on Clojure's `hash` of non-data leaves."[](format "%08x"(hash (->> (list-tools)@@ -281,6 +351,34 @@(when-let [label (english-scope-label required-scope)](str " (" label ")")))})+(def ^:private enable-tool-hint+ "The sentence closing every refusal of a tool the user's groups deny, naming who can enable it and where."+ (message/msg ["Ask an administrator to enable it under Admin > AI > Usage controls > MCP tools access."]))++(defn- group-policy-denial-message+ "The `tools/call` error for a tool `tool-name` the user's groups deny."+ [tool-name]+ (message/msg ["Tool %s is not enabled for your groups. %s"] tool-name enable-tool-hint))++(defn tool-denial+ "The refusal of `subject`, an action that is another tool's capability, such as storing raw SQL that `execute_sql`+ would run, when the current user's groups deny the tool registered as `tool-name`; nil when they allow it. An+ unregistered `tool-name` is denied to every caller but an unrestricted one."+ [tool-name subject]+ (let [policy (mcp.perms/policy-for-current-user)]+ (when-not (if-let [tool (get @tools* tool-name)]+ (tool-allowed? policy tool)+ (= mcp.perms/unrestricted-policy policy))+ (message/msg ["%s needs the %s tool, which is not enabled for your groups. %s"]+ subject tool-name enable-tool-hint))))++(defn check-tool-allowed!+ "Throw a 403 teaching error with the [[tool-denial]] of `subject` when the current user's groups deny the tool+ registered as `tool-name`."+ [tool-name subject]+ (when-let [denial (tool-denial tool-name subject)]+ (common/throw-teaching-error denial {:status-code 403})))+(defn- dispatch-tool-call[token-scopes session-id tool-name arguments options](let [tool (get @tools* tool-name)@@ -297,6 +395,11 @@{:error {:code common/error-code-invalid-params:message (message/msg ["Invalid arguments: expected a JSON object."])}}+ ;; Before the scope check, so a user their groups deny isn't sent to re-authorize for nothing.+ (not (tool-allowed? (mcp.perms/policy-for-current-user) tool))+ {:error {:code common/error-code-invalid-request+ :message (group-policy-denial-message tool-name)}}+(not (mcp.scope/matches? token-scopes (:scope tool))){:error {:code common/error-code-invalid-request:message (insufficient-scope-message (message/msg ["call tool: %s"] tool-name)diff --git a/src/metabase/mcp/v2/tools/alert.clj b/src/metabase/mcp/v2/tools/alert.cljindex 9abd303e686..99d728e4802 100644--- a/src/metabase/mcp/v2/tools/alert.clj+++ b/src/metabase/mcp/v2/tools/alert.clj@@ -478,10 +478,11 @@archived state, and this tool cannot delete one. An alert's question is fixed at creation. Creating an alert, changingits delivery or its schedule, resuming a paused one, or clearing send_once additionally requires the agent:query:runscope — the alert runs the question and delivers its results. Pausing one never does. Alerts are for saved questions; use subscription_write to schedule a whole dashboard."- {:name "alert_write"- :scope metabot.scope/agent-delivery-write- :annotations {:readOnlyHint false :destructiveHint false}- :args alert-write-args-schema}+ {:name "alert_write"+ :default-access :allowed+ :scope metabot.scope/agent-delivery-write+ :annotations {:readOnlyHint false :destructiveHint false}+ :args alert-write-args-schema}[args {:keys [token-scopes]}](let [[op a b] (v2.write/dispatch-write {:create-required [:card_id :schedule]} args)](common/success-contentdiff --git a/src/metabase/mcp/v2/tools/bookmark.clj b/src/metabase/mcp/v2/tools/bookmark.cljindex fc7dea6e19e..1fbf3f3e966 100644--- a/src/metabase/mcp/v2/tools/bookmark.clj+++ b/src/metabase/mcp/v2/tools/bookmark.clj@@ -77,10 +77,11 @@(registry/deftool bookmark-content"Add or remove a bookmark on content for the calling user — the same starred/favorites list the Metabase sidebar shows. Pass type (question, model, metric, dashboard, collection, or document), id (numeric or 21-char entity_id), and bookmarked: true to bookmark or false to un-bookmark. Both directions are idempotent: bookmarking something already bookmarked, or un-bookmarking something that isn't, succeeds and reports the resulting state. Bookmarks are per-user and grant no access — the item must already be readable by the caller. The item's name comes back only when your token also holds agent:content:read; without it the response is a minimal acknowledgement. This response is the only place bookmark state is reported: no tool reads a bookmark back, search and get_content carry no bookmarked field, and there is no bookmark listing — so keep this result if you need it later rather than spending calls looking for a read path."- {:name "bookmark_content"- :scope metabot.scope/agent-content-write- :annotations {:readOnlyHint false :destructiveHint false :idempotentHint true}- :args bookmark-content-args-schema}+ {:name "bookmark_content"+ :default-access :allowed+ :scope metabot.scope/agent-content-write+ :annotations {:readOnlyHint false :destructiveHint false :idempotentHint true}+ :args bookmark-content-args-schema}[{:keys [type id bookmarked]} {:keys [token-scopes]}](let [row (fetch-item type id)bookmark-model (get-in type->spec [type :bookmark-model])diff --git a/src/metabase/mcp/v2/tools/browse.clj b/src/metabase/mcp/v2/tools/browse.cljindex 2d25087a843..b19c7517d68 100644--- a/src/metabase/mcp/v2/tools/browse.clj+++ b/src/metabase/mcp/v2/tools/browse.clj@@ -545,10 +545,11 @@(registry/deftool browse-data"Browse the data hierarchy: databases → schemas → tables → fields. Actions: list_databases — databases you can see; list_schemas — schema names in a database; list_tables — tables in a database, scoped to `schema` (omit it for databases without schemas) and optionally narrowed with `search`; list_models — models built on a database; get_fields — field metadata for up to 20 tables in one call, each table carrying its measures, segments, metrics, and related tables (FK targets with column names) for query construction. list_* actions return the {data, returned, total} envelope paged with limit/offset. get_fields returns whole tables within a response byte budget and names any tables it had to omit; a single table too large for the budget comes back as a position-ordered field slice with a continuation offset."- {:name "browse_data"- :scope metabot.scope/agent-content-read- :annotations {:readOnlyHint true :idempotentHint true}- :args browse-args-schema}+ {:name "browse_data"+ :default-access :allowed+ :scope metabot.scope/agent-content-read+ :annotations {:readOnlyHint true :idempotentHint true}+ :args browse-args-schema}[{:keys [action] :as args} _context](validate-args-for-action! args)(case action@@ -864,10 +865,11 @@(registry/deftool browse-collection"Browse collections structurally — one uniform id over every partition: a numeric id, a 21-char entity_id, \"root\" (re-rooted per namespace), or \"trash\" (archived content, items mode only). items mode (default) lists one collection's contents with type/created_by/pinned_state/sort_column/sort_direction and limit/offset paging in the {data, returned, total} envelope; browsing the trash or an archived collection returns archived children. tree mode returns the nested subcollection structure (collections only, no items, no pagination) down to depth (default 2) under a per-node child cap and total node budget; trimmed or deeper nodes carry a marker naming the expansion call, e.g. … 14 more under \"Finance\" — browse_collection(id: 45, mode: \"tree\"); archived subtrees and the trash never appear in trees. For content search or recents use the search tool."- {:name "browse_collection"- :scope metabot.scope/agent-content-read- :annotations {:readOnlyHint true :idempotentHint true}- :args browse-collection-args-schema}+ {:name "browse_collection"+ :default-access :allowed+ :scope metabot.scope/agent-content-read+ :annotations {:readOnlyHint true :idempotentHint true}+ :args browse-collection-args-schema}[{:keys [mode] :as args} _context](validate-browse-collection-args! args)(let [target (resolve-browse-target args)]diff --git a/src/metabase/mcp/v2/tools/collection.clj b/src/metabase/mcp/v2/tools/collection.cljindex 5aac0a2087f..2bae92724e4 100644--- a/src/metabase/mcp/v2/tools/collection.clj+++ b/src/metabase/mcp/v2/tools/collection.clj@@ -167,12 +167,13 @@not work, because unset properties are stripped before the tool sees them. Personal collectionsthemselves cannot be created or moved, but you can nest collections inside one by passing its id as parent_id.Returns the resulting collection, including authority_level and namespace, so no follow-up read is needed."- {:name "collection_write"- :scope metabot.scope/agent-content-write+ {:name "collection_write"+ :default-access :allowed+ :scope metabot.scope/agent-content-write;; `archived: true` trashes the collection and everything under it, so this is not the;; additive-only update `destructiveHint false` would assert.- :annotations {:readOnlyHint false :destructiveHint true}- :args collection-write-args-schema}+ :annotations {:readOnlyHint false :destructiveHint true}+ :args collection-write-args-schema}[args {:keys [token-scopes]}](let [[op a b] (v2.write/dispatch-write collection-write-entry args)payload (v2.write/readback token-scopes [metabot.scope/agent-content-read]diff --git a/src/metabase/mcp/v2/tools/content.clj b/src/metabase/mcp/v2/tools/content.cljindex 74c0b58a881..27d017f1e80 100644--- a/src/metabase/mcp/v2/tools/content.clj+++ b/src/metabase/mcp/v2/tools/content.clj@@ -612,10 +612,11 @@(registry/deftool get-content"Fetch content by {type, id} — the typed read for anything found via search or browse_collection. Batch up to 10 items of mixed types; each is permission-checked independently and a bad item returns {type, id, error} without failing the batch. Types: question, model, metric, measure, dashboard, document, collection, snippet, segment, alert, subscription. Ids: numeric or 21-char entity_id. Concise shapes are task-focused: a question carries its source (database id and name, table, source card), display, a one-line query summary — for a native question the head of its query text rather than a placeholder — raw template_tags (in the stored shape question_write accepts back verbatim), and materialized parameters (the same tags viewed as parameters); a dashboard returns the editing skeleton (tabs, parameters with wired dashcard ids, one summary row per dashcard with position/size/series/inline parameters), never the raw REST dashcards; a document returns its body text as content_markdown — the same field name document_write takes and returns, so a read-modify-write needs no renaming (a body holding a block with no Markdown form returns content_markdown_unavailable in its place instead: that document cannot be edited or rewritten as Markdown); alerts and subscriptions return condition, schedule, channels, recipients (redacted for non-admins). include adds sections on demand — definition returns the stored query (numeric ids) in the shape execute_query and question_write accept; visualization_settings returns a question's or model's stored chart settings, the same property question_write takes back, so a chart can be read back and patched; comments returns a document's threads, each anchored to the exact character range of its block in the returned markdown."- {:name "get_content"- :scope metabot.scope/agent-content-read- :annotations {:readOnlyHint true :idempotentHint true}- :args get-content-args-schema}+ {:name "get_content"+ :default-access :allowed+ :scope metabot.scope/agent-content-read+ :annotations {:readOnlyHint true :idempotentHint true}+ :args get-content-args-schema}[{:keys [items include] :as args} _](when (> (count items) max-items)(common/throw-teaching-errordiff --git a/src/metabase/mcp/v2/tools/dashboard.clj b/src/metabase/mcp/v2/tools/dashboard.cljindex b2c6a10b46a..26d6f8a56a0 100644--- a/src/metabase/mcp/v2/tools/dashboard.clj+++ b/src/metabase/mcp/v2/tools/dashboard.clj@@ -462,13 +462,14 @@produce without writing — but per-field parameter-mapping permission checks run only on the real save, so aclean dry run can still be rejected. Returns the resulting dashboard, so no follow-up read is needed.Requires write permission on the dashboard and read permission on every referenced card."- {:name "dashboard_write"- :scope metabot.scope/agent-content-write+ {:name "dashboard_write"+ :default-access :allowed+ :scope metabot.scope/agent-content-write;; `archived: true` trashes the dashboard, and `remove`/`remove_tab`/`remove_parameter` drop;; cards, tabs, and subscriptions — not the additive-only update `destructiveHint false`;; would assert.- :annotations {:readOnlyHint false :destructiveHint true}- :args dashboard-write-args-schema}+ :annotations {:readOnlyHint false :destructiveHint true}+ :args dashboard-write-args-schema}[args {:keys [token-scopes]}](let [dispatched (v2.write/dispatch-write dashboard-write-entry args)](common/success-contentdiff --git a/src/metabase/mcp/v2/tools/definitions.clj b/src/metabase/mcp/v2/tools/definitions.cljindex aa85b344f10..31fbe98e272 100644--- a/src/metabase/mcp/v2/tools/definitions.clj+++ b/src/metabase/mcp/v2/tools/definitions.clj@@ -334,12 +334,13 @@single-stage query. For a full query table_id must name the definition's own source table; a mismatch isa teaching error. Not admin-only: writing requires superuser OR a data analyst with unrestricted view-data on thetable, and the table must not live in a read-only remote-synced collection."- {:name "segment_write"- :scope metabot.scope/agent-content-write+ {:name "segment_write"+ :default-access :allowed+ :scope metabot.scope/agent-content-write;; `archived: true` trashes the segment, so this is not the additive-only update;; `destructiveHint false` would assert.- :annotations {:readOnlyHint false :destructiveHint true}- :args segment-write-args-schema}+ :annotations {:readOnlyHint false :destructiveHint true}+ :args segment-write-args-schema}[args {:keys [token-scopes]}](let [dispatched (v2.write/dispatch-write segment-write-entry args)](case (first dispatched)@@ -402,12 +403,13 @@full query table_id must name the definition's own source table; a mismatch is a teaching error. Not admin-only:writing requires superuser OR a data analyst with unrestricted view-data on the table, and the table must not livein a read-only remote-synced collection."- {:name "measure_write"- :scope metabot.scope/agent-content-write+ {:name "measure_write"+ :default-access :allowed+ :scope metabot.scope/agent-content-write;; `archived: true` trashes the measure, so this is not the additive-only update;; `destructiveHint false` would assert.- :annotations {:readOnlyHint false :destructiveHint true}- :args measure-write-args-schema}+ :annotations {:readOnlyHint false :destructiveHint true}+ :args measure-write-args-schema}[args {:keys [token-scopes]}](let [dispatched (v2.write/dispatch-write measure-write-entry args)](case (first dispatched)diff --git a/src/metabase/mcp/v2/tools/document.clj b/src/metabase/mcp/v2/tools/document.cljindex 89de449d64c..d685f7d537d 100644--- a/src/metabase/mcp/v2/tools/document.clj+++ b/src/metabase/mcp/v2/tools/document.clj@@ -533,10 +533,11 @@(registry/deftool document-write-tool"Create or update a document. method: \"create\" | \"update\". Documents are Metabase-flavored Markdown: CommonMark plus {% card id=118 name=\"…\" %} block embeds of saved questions you can read (build with question_write first; an unresolvable id fails the write), {% entity id=\"42\" model=\"dashboard\" %} inline links (models: card, dataset, metric, dashboard, collection, table, database, document), and ::: layout containers (flex, supporting, resize). No Markdown tables - embed a table-display question instead. Before authoring layout containers, call learn(\"documents\") — the grammar, nesting rules, and a worked example. A card not already owned by the document is cloned into it on write and its id rewritten, so always take the returned content_markdown as the current text. Create: name + content_markdown; optional collection_id (omit for your personal collection; \"root\" for the root collection) and collection_position. Update: id + exactly one of edits: [{old_str, new_str, replace_all?}] (each old_str must match the current server-side Markdown exactly once — extend the snippet or set replace_all; new_str is parsed as Markdown; edited blocks keep their ids and comment anchors) or content_markdown (a full-body rewrite that orphans every comment thread on the body); edits: [] changes only name/collection_id/collection_position/archived (archived: true trashes, false restores). To unset a property, name it in clear: [\"collection_position\"] — a null does not clear. The response lists changed_blocks and orphaned_comment_threads. It carries content_markdown_unavailable in place of content_markdown when the body holds a block with no Markdown form: the write happened, but that body cannot be edited or rewritten as Markdown without discarding the block. Writes are last-write-wins; a stale old_str failing to match is the only staleness signal."- {:name "document_write"- :scope metabot.scope/agent-content-write- :annotations {:readOnlyHint false :destructiveHint false}- :args document-write-args-schema}+ {:name "document_write"+ :default-access :allowed+ :scope metabot.scope/agent-content-write+ :annotations {:readOnlyHint false :destructiveHint false}+ :args document-write-args-schema}[args {:keys [token-scopes]}](let [[op a b] (v2.write/dispatch-write{:create-required [:name :content_markdown]diff --git a/src/metabase/mcp/v2/tools/duplicate.clj b/src/metabase/mcp/v2/tools/duplicate.cljindex 86fe7eadbb7..018febfa953 100644--- a/src/metabase/mcp/v2/tools/duplicate.clj+++ b/src/metabase/mcp/v2/tools/duplicate.clj@@ -146,10 +146,11 @@(registry/deftool duplicate-content"Copy a question, dashboard, or document into a collection — cheaper and safer than reading the original and re-creating it, and it preserves everything the read projections leave out. Pass type, id (numeric or 21-char entity_id), and optionally collection_id (omit to copy into your personal collection; \"root\" for the root collection) and new_name (defaults to \"Copy of <source name>\"). is_deep_copy is dashboards-only: false (the default) makes the copy point at the original's questions, true duplicates those questions into the destination collection as well — a dashboard that holds questions saved inside it can only be copied with is_deep_copy: true. Any copy of a dashboard, shallow or deep, reports cards it had to leave behind as `uncopied` — cards you can't read (reported as an id alone) or that are in the trash; the copy simply omits them, so check this field on every dashboard copy. A question saved inside a document can't be duplicated on its own — duplicate the document instead. Duplicating is creating: you need curate permission on the destination collection. The copy's name and collection come back only when your token also holds agent:content:read; without it the response is a minimal acknowledgement carrying the id, the type, and a count of any uncopied cards."- {:name "duplicate_content"- :scope metabot.scope/agent-content-write- :annotations {:readOnlyHint false :destructiveHint false}- :args duplicate-content-args-schema}+ {:name "duplicate_content"+ :default-access :allowed+ :scope metabot.scope/agent-content-write+ :annotations {:readOnlyHint false :destructiveHint false}+ :args duplicate-content-args-schema}[{:keys [type id new_name is_deep_copy] :as args} {:keys [token-scopes]}](let [{:keys [fetch copy!]} (type->spec type)];; `true?`, not `some?`: `false` is the documented default and means exactly what a question ordiff --git a/src/metabase/mcp/v2/tools/glossary.clj b/src/metabase/mcp/v2/tools/glossary.cljindex 199183bb844..69672fc04b6 100644--- a/src/metabase/mcp/v2/tools/glossary.clj+++ b/src/metabase/mcp/v2/tools/glossary.clj@@ -43,23 +43,24 @@(registry/deftool glossary"Look up a business term as this Metabase instance defines it, as its own data analysts wrote it down. glossary() lists terms with their definitions, paged with limit (default 50, max 500) and offset; glossary(term) returns matching terms (case insensitive). Call glossary() before answering any question about this instance's data: these definitions override your own reading of a word, and the question itself will not tell you which words are defined here."- {:name "glossary"- :scope metabot.scope/agent-content-read- :annotations {:readOnlyHint true :idempotentHint true}- :args [:map {:closed true}- [:term {:optional true}- [:maybe [:string {:min 1- :description (str "The term to define, matched case-insensitively. "- "Omit to list terms with their definitions.")}]]]- [:limit {:optional true}- [:maybe [:int {:min 1 :max max-limit- :description (str "Maximum entries to return (default 50, max 500). "- "Ignored with \"term\", which is a lookup, not a "- "page.")}]]]- [:offset {:optional true}- [:maybe [:int {:min 0- :description (str "Number of entries to skip, for paging (default 0). "- "Ignored with \"term\".")}]]]]}+ {:name "glossary"+ :default-access :allowed+ :scope metabot.scope/agent-content-read+ :annotations {:readOnlyHint true :idempotentHint true}+ :args [:map {:closed true}+ [:term {:optional true}+ [:maybe [:string {:min 1+ :description (str "The term to define, matched case-insensitively. "+ "Omit to list terms with their definitions.")}]]]+ [:limit {:optional true}+ [:maybe [:int {:min 1 :max max-limit+ :description (str "Maximum entries to return (default 50, max 500). "+ "Ignored with \"term\", which is a lookup, not a "+ "page.")}]]]+ [:offset {:optional true}+ [:maybe [:int {:min 0+ :description (str "Number of entries to skip, for paging (default 0). "+ "Ignored with \"term\".")}]]]]}[{:keys [term limit offset]} _context](let [entries (glossary/entries)](if termdiff --git a/src/metabase/mcp/v2/tools/learn.clj b/src/metabase/mcp/v2/tools/learn.cljindex df845e8d8f8..408466d4387 100644--- a/src/metabase/mcp/v2/tools/learn.clj+++ b/src/metabase/mcp/v2/tools/learn.clj@@ -28,14 +28,15 @@(registry/deftool learn"Read this server's task docs (skills) for the write dialects the schemas can't fully describe. learn() lists topics; learn(topic) returns that skill whole; learn(topic, reference) one of its reference files. Topics: query-dialect (the query language for execute_query and question_write's query; reference \"operators\" = operator catalog), native-parameters (template tags and field filters for native SQL), dashboard-filters (dashboard parameters and the wire_parameter target grammar), dashboard-layout (24-column grid, sizes, tabs), documents (document_write's Markdown grammar), visualization-settings (display choice and settings; reference \"settings\" = per-chart key catalog). Read the matching topic before your first complex write of that kind; skip when already in context."- {:name "learn"- :scope metabot.scope/agent-content-read- :annotations {:readOnlyHint true :idempotentHint true}- :args [:map {:closed true}- [:topic {:optional true}- [:maybe [:string {:min 1 :description "A topic from the catalog. Omit to list all topics."}]]]- [:reference {:optional true}- [:maybe [:string {:min 1 :description "A reference file of `topic`, by the name the skill (or the catalog) lists."}]]]]}+ {:name "learn"+ :default-access :allowed+ :scope metabot.scope/agent-content-read+ :annotations {:readOnlyHint true :idempotentHint true}+ :args [:map {:closed true}+ [:topic {:optional true}+ [:maybe [:string {:min 1 :description "A topic from the catalog. Omit to list all topics."}]]]+ [:reference {:optional true}+ [:maybe [:string {:min 1 :description "A reference file of `topic`, by the name the skill (or the catalog) lists."}]]]]}[{:keys [topic reference]} _context](common/success-content(conddiff --git a/src/metabase/mcp/v2/tools/metric.clj b/src/metabase/mcp/v2/tools/metric.cljindex 61b01029f10..ff067cef2d8 100644--- a/src/metabase/mcp/v2/tools/metric.clj+++ b/src/metabase/mcp/v2/tools/metric.clj@@ -275,12 +275,13 @@to your personal collection; pass \"root\" for the root collection), collection_position to pin. Updating a card that is aquestion or a model is refused rather than retyping it. Requires write permission on the metric and curatepermission on the target collection."- {:name "metric_write"- :scope metabot.scope/agent-content-write+ {:name "metric_write"+ :default-access :allowed+ :scope metabot.scope/agent-content-write;; `archived: true` trashes the metric, so this is not the additive-only update;; `destructiveHint false` would assert (matches collection_write).- :annotations {:readOnlyHint false :destructiveHint true}- :args metric-write-args-schema}+ :annotations {:readOnlyHint false :destructiveHint true}+ :args metric-write-args-schema}[args {:keys [token-scopes session-id]}](let [dispatched (v2.write/dispatch-write metric-write-entry args)payload (v2.write/readback token-scopes [metabot.scope/agent-content-read]diff --git a/src/metabase/mcp/v2/tools/parameters.clj b/src/metabase/mcp/v2/tools/parameters.cljindex 667cfce321c..b8feb5af050 100644--- a/src/metabase/mcp/v2/tools/parameters.clj+++ b/src/metabase/mcp/v2/tools/parameters.clj@@ -426,10 +426,11 @@(registry/deftool get-parameter-values"Fetch the valid values for one filter on a dashboard or saved question, so you filter with real values instead of guessing. Pass target (\"dashboard\" or \"question\" — the latter accepts any card id: question, model, or metric), id (numeric or 21-char entity_id), and parameter_id from get_content's `parameters` (each lists id, name, type). Values come back as [value] pairs, or [value, display_label] when the column is remapped — filter with the first element, show the second. query searches a large list rather than paging it; constraints (dashboards only) chain-filters — pass the other filters' current selections keyed by parameter id to get only the values still valid alongside them. Paged with limit (default 100, max 1000) and offset. A parameter with nothing behind it (e.g. a free-text template tag) returns no values. A column-backed date parameter answers with its range instead of a value list — {kind: \"date\", min, max, distinct_dates, accepts} — where accepts is the grammar to write a value in (\"YYYY-MM-DD\", \"YYYY-MM-DD~YYYY-MM-DD\", \"past30days\", \"thisyear\") and min/max are the column's real first and last dates to write between. constraints narrow the range as they narrow a list; query, limit and offset don't apply to it. Pair with run_saved_question, which takes these values as its `parameters`."- {:name "get_parameter_values"- :scope metabot.scope/agent-content-read- :annotations {:readOnlyHint true :idempotentHint true}- :args get-parameter-values-args-schema}+ {:name "get_parameter_values"+ :default-access :allowed+ :scope metabot.scope/agent-content-read+ :annotations {:readOnlyHint true :idempotentHint true}+ :args get-parameter-values-args-schema}[{:keys [target id parameter_id query constraints limit offset]} _context](when (and query (str/blank? query))(common/throw-teaching-errordiff --git a/src/metabase/mcp/v2/tools/query.clj b/src/metabase/mcp/v2/tools/query.cljindex 54234ca8486..3d1373177a4 100644--- a/src/metabase/mcp/v2/tools/query.clj+++ b/src/metabase/mcp/v2/tools/query.clj@@ -249,10 +249,11 @@"The default way to answer a question from data: validate and execute a structured (MBQL) query, returning rows plus a query_handle. Use it first for any count, sum, group-by, filter, sort, or join, even \"how many X\"; execute_sql is only for window functions, CTEs, set operations, engine-specific functions, an explicit request for SQL, or a rejection you cannot fix. Only this route validates ids, pages with a cursor, and mints handles that save as cards taking dashboard filters as-is. Native SQL is rejected at any depth. Pass exactly one of: query (a fresh query, dialect below), query_handle (re-run a stored query), or cursor (next page). The query_handle holds the whole query, not the page, so save or visualize from any page. On next_cursor, call again with cursor until truncated is false. row_limit is only the page size: the first N rows is a stage limit: N with an order-by, never pages counted by hand.Dialect (JSON): tables and columns go by NUMERIC ID (from browse_data list_tables / get_fields or search) — never guessed, base64, or schema-qualified. Only the FIRST stage has source-table or source-card (an id); later stages read the previous stage's output. Every clause is [\"op\", {}, ...args], options map mandatory at position 1. Field refs: [\"field\", {}, <field id>], or [\"field\", {}, \"<column name>\"] against a previous stage. Stage keys: filters, aggregation, breakout, expressions, fields, joins, order-by, limit. Example, row count by month (placeholder ids; drop breakout for a plain count): {\"lib/type\": \"mbql/query\", \"stages\": [{\"lib/type\": \"mbql.stage/mbql\", \"source-table\": <TABLE_ID>, \"aggregation\": [[\"count\", {}]], \"breakout\": [[\"field\", {\"temporal-unit\": \"month\"}, <FIELD_ID>]]}]}. get_content's definition include returns this same shape. Call learn(\"query-dialect\") before joins, expressions, multi-stage queries, or limits; learn(\"query-dialect\", \"operators\") lists every operator."- {:name "execute_query"- :scope metabot.scope/agent-query-run- :annotations {:readOnlyHint true}- :args execute-query-args-schema}+ {:name "execute_query"+ :default-access :allowed+ :scope metabot.scope/agent-query-run+ :annotations {:readOnlyHint true}+ :args execute-query-args-schema}[{:keys [validate_only row_limit] :as args} {:keys [session-id]}](let [input (query-input args){resolved :query prompt :prompt} (resolve-input input args session-id)@@ -449,13 +450,14 @@ Dialect (JSON): tables and columns go by NUMERIC ID (from browse_data list_table(registry/deftool execute-sql"Escape hatch for execute_query, the default for every question MBQL can express (see its description): execute a raw SQL string against a database, returning rows plus a query_handle. Use only for what MBQL cannot express (window functions, CTEs, set operations, engine-specific functions), an explicit request for SQL, or a structured attempt rejected for a reason you cannot fix. Raw SQL is checked only by the warehouse (no metadata validation, no teaching errors naming what is wrong), and a card saved from it cannot be filtered on a dashboard until rewritten with template tags. Requires native-query permission on the database and the instance-level mcp-execute-sql-enabled setting — both enforced even with validate_only: true. The sql runs verbatim against the warehouse, so it is the injection surface — never splice caller- or user-supplied values into it; put values behind {{tag}} placeholders bound via template_tag_values, driver-level prepared-statement parameters that are injection-safe for the values. {{snippet: …}} and {{#123}} card-reference tags splice server-side SQL text and can never be populated through template_tag_values. validate_only: true mints a query_handle without executing (tags and permissions checked; the SQL text itself is not) — stage SQL for saving or visualizing without pulling rows into context. The query_handle is accepted by question_write; execute_query is MBQL-only and rejects it. Results are cols + rows with returned/truncated counts. No cursor pagination: the server cannot know whether arbitrary SQL has a total order, so page it yourself — ORDER BY a unique key plus WHERE <key> > <last value returned>, which is exact where an offset would silently repeat or skip rows. Otherwise narrow the SQL (filters/aggregation) or raise row_limit (max 2000)."- {:name "execute_sql"- :scope metabot.scope/agent-sql-run+ {:name "execute_sql"+ :default-access :allowed+ :scope metabot.scope/agent-sql-run;; Unlike execute_query, arbitrary SQL can write. These match MCP's defaults for an unannotated;; tool, stated explicitly so the tool is covered by the mutating-tool invariants in;; `metabase.mcp.v2.registry-test`, which enumerate on `:readOnlyHint`.- :annotations {:readOnlyHint false :destructiveHint true}- :args execute-sql-args-schema}+ :annotations {:readOnlyHint false :destructiveHint true}+ :args execute-sql-args-schema}[{:keys [database_id sql template_tag_values prompt validate_only row_limit]} {:keys [session-id]}](check-execute-sql-gates! database_id)(let [mp (lib-be/application-database-metadata-provider database_id)@@ -610,10 +612,11 @@ Dialect (JSON): tables and columns go by NUMERIC ID (from browse_data list_table(registry/deftool run-saved-question"Run a saved question (card) by numeric id or entity_id, returning rows inline. Pass each parameter as {id, value} where id is the parameter's id or slug — the stored target and type always apply and client-supplied ones are ignored, so you can set a filter's value but never repoint it at another field. Both native template-tag parameters ({{variable}} and field-filter tags) and declared filter-widget parameters can be set; value types are checked per parameter. Discover them with get_content (a question's concise shape carries its template tags and materialized parameters). Results are cols + rows with returned/truncated counts, capped by row_limit. No query_handle and no cursor: on truncation, narrow through the card's parameters or raise row_limit (max 2000)."- {:name "run_saved_question"- :scope metabot.scope/agent-query-run- :annotations {:readOnlyHint true}- :args run-saved-question-args-schema}+ {:name "run_saved_question"+ :default-access :allowed+ :scope metabot.scope/agent-query-run+ :annotations {:readOnlyHint true}+ :args run-saved-question-args-schema}[{:keys [id parameters row_limit]} _context](let [row-limit (or row_limit default-row-limit)card (v2.resolve/resolve-and-read :model/Card id)diff --git a/src/metabase/mcp/v2/tools/question.clj b/src/metabase/mcp/v2/tools/question.cljindex e244a36c768..7d4432df349 100644--- a/src/metabase/mcp/v2/tools/question.clj+++ b/src/metabase/mcp/v2/tools/question.clj@@ -130,16 +130,17 @@stages)))))(defn- check-native-source-gates!- "The gates an inline `native` source passes: the `agent:sql:run` scope and the- `mcp-execute-sql-enabled` kill switch — `execute_sql`'s own two, because the stored card is raw- SQL a later `run_saved_question` executes, so accepting one under the content write scope alone- would rebuild `execute_sql` without its scope or its kill switch. Every source that can resolve- to native passes these, `query_handle` included — holding a handle is not proof the gates were- spent (`construct_native_query` mints under `agent:sql:construct` and never consults the kill- switch, and a handle resolves on `core_session.user_id`, so any credential of that user can spend- one minted by another). No-op on the scope half for unscoped callers (cookie sessions bind the- unrestricted sentinel, which matches everything)."+ "Throw unless the current user and `token-scopes` may store a native question: the user's groups must allow+ `execute_sql`, the scopes must match `agent:sql:run`, and the `mcp-execute-sql-enabled` kill switch must be on."[token-scopes]+ ;; `execute_sql`'s own three gates. A stored native card is raw SQL a later `run_saved_question` executes, so+ ;; accepting one under `question_write`'s policy and the content write scope alone would rebuild `execute_sql` for+ ;; a user an admin denied it, or without its scope or its kill switch. Every source that can resolve to native+ ;; passes these, `query_handle` included: holding a handle is not proof the gates were spent+ ;; (`construct_native_query` mints under `agent:sql:construct` and never consults the kill switch, and a handle+ ;; resolves on `core_session.user_id`, so any credential of that user can spend one minted by another). Unscoped+ ;; callers bind the unrestricted sentinel, which matches every scope.+ (registry/check-tool-allowed! "execute_sql" (message/raw "Saving a native (SQL) query"))(when-not (mcp.scope/matches? token-scopes metabot.scope/agent-sql-run)(common/throw-insufficient-scope!(message/msg [(str "Saving a native (SQL) query requires the %s scope — "@@ -505,7 +506,8 @@"(learn(\"query-dialect\")). Prefer `query_handle`.")}]]][:native {:optional true}[:maybe [:map {:description (str "A native SQL query to save: {database_id, sql, template_tags?}. Requires "- "the agent:sql:run scope and the mcp-execute-sql-enabled setting. Call "+ "the agent:sql:run scope, the mcp-execute-sql-enabled setting, and the "+ "execute_sql tool enabled for your groups. Call ""learn(\"native-parameters\") before first passing template_tags.")}[:database_id [:or :int :string]][:sql [:string {:min 1}]]@@ -581,13 +583,14 @@visibility-type-strs)]]]]]]])(registry/deftool question-write-tool- "Create, update, or archive a saved question or model. method: \"create\" | \"update\". On create, pass a name and exactly one query source: query_handle (from an execute tool — MBQL or native SQL), query (an inline query — numeric ids and a top-level database id, learn(\"query-dialect\"); prefer query_handle, which saves exactly the query execute_query validated), or native ({database_id, sql, template_tags?} — the template_tags shape is MCP-specific and not guessable: before first passing it, call learn(\"native-parameters\") unless already read; on create or update, native additionally requires the agent:sql:run scope and the instance-level mcp-execute-sql-enabled setting, since the saved card is raw SQL). Optional: card_type (\"question\" default, or \"model\"), description, collection_id (omit = your personal collection; \"root\" = the root collection) or dashboard_id (saves the question inside that dashboard, whose collection it inherits — passing both is an error), display, visualization_settings (learn(\"visualization-settings\") covers display choice and settings keys), cache_ttl, column_metadata (list of {name, display_name?, description?, semantic_type?, visibility_type?} — sets result_metadata; typically used with card_type \"model\"). On update, pass id and the fields to change; archived: true trashes, false restores; dashboard_id moves the card into that dashboard (collection follows; a question saved in another dashboard can't move to a different one; moving a card OUT of a dashboard isn't supported yet). Updating a card that is a metric is refused rather than retyping it — use metric_write."- {:name "question_write"- :scope metabot.scope/agent-content-write+ "Create, update, or archive a saved question or model. method: \"create\" | \"update\". On create, pass a name and exactly one query source: query_handle (from an execute tool — MBQL or native SQL), query (an inline query — numeric ids and a top-level database id, learn(\"query-dialect\"); prefer query_handle, which saves exactly the query execute_query validated), or native ({database_id, sql, template_tags?} — the template_tags shape is MCP-specific and not guessable: before first passing it, call learn(\"native-parameters\") unless already read; on create or update, native additionally requires the agent:sql:run scope, the instance-level mcp-execute-sql-enabled setting, and the execute_sql tool enabled for your groups, since the saved card is raw SQL). Optional: card_type (\"question\" default, or \"model\"), description, collection_id (omit = your personal collection; \"root\" = the root collection) or dashboard_id (saves the question inside that dashboard, whose collection it inherits — passing both is an error), display, visualization_settings (learn(\"visualization-settings\") covers display choice and settings keys), cache_ttl, column_metadata (list of {name, display_name?, description?, semantic_type?, visibility_type?} — sets result_metadata; typically used with card_type \"model\"). On update, pass id and the fields to change; archived: true trashes, false restores; dashboard_id moves the card into that dashboard (collection follows; a question saved in another dashboard can't move to a different one; moving a card OUT of a dashboard isn't supported yet). Updating a card that is a metric is refused rather than retyping it — use metric_write."+ {:name "question_write"+ :default-access :allowed+ :scope metabot.scope/agent-content-write;; `archived: true` trashes the card, so this is not the additive-only update;; `destructiveHint false` would assert.- :annotations {:readOnlyHint false :destructiveHint true}- :args question-write-args-schema}+ :annotations {:readOnlyHint false :destructiveHint true}+ :args question-write-args-schema}[args {:keys [token-scopes session-id]}](let [[op a b] (v2.write/dispatch-write{:create-required [:name]diff --git a/src/metabase/mcp/v2/tools/search.clj b/src/metabase/mcp/v2/tools/search.cljindex f9e35310874..bda0289ed7e 100644--- a/src/metabase/mcp/v2/tools/search.clj+++ b/src/metabase/mcp/v2/tools/search.clj@@ -514,9 +514,10 @@limit — so a large total is a floor (the response says \"at least N\"). An empty {data: [], total: 0} means nomatch against the search index, which on a freshly started instance can still be building — if content you canreach with browse_collection or browse_data does not turn up here, prefer those over concluding it is absent." {:name "search"- :scope metabot.scope/agent-content-read- :annotations {:readOnlyHint true :idempotentHint true}- :args search-args-schema}+ :default-access :allowed+ :scope metabot.scope/agent-content-read+ :annotations {:readOnlyHint true :idempotentHint true}+ :args search-args-schema}[{:keys [term_queries semantic_queries recent type collection_id archived] :as args} _](let [queries? (boolean (or (seq term_queries) (seq semantic_queries)))filters? (boolean (or (seq type)diff --git a/src/metabase/mcp/v2/tools/subscription.clj b/src/metabase/mcp/v2/tools/subscription.cljindex 386cb64fe11..9ecfdd13636 100644--- a/src/metabase/mcp/v2/tools/subscription.clj+++ b/src/metabase/mcp/v2/tools/subscription.clj@@ -491,10 +491,11 @@never does. This is for dashboards on a schedule — use alert_write for aquestion that fires on a condition. Requires read permission on the dashboard; only its creator (or an admin) canupdate it."- {:name "subscription_write"- :scope metabot.scope/agent-delivery-write- :annotations {:readOnlyHint false :destructiveHint false}- :args subscription-write-args-schema}+ {:name "subscription_write"+ :default-access :allowed+ :scope metabot.scope/agent-delivery-write+ :annotations {:readOnlyHint false :destructiveHint false}+ :args subscription-write-args-schema}[args {:keys [token-scopes]}](let [[op a b] (v2.write/dispatch-write subscription-write-entry args)id (case opdiff --git a/src/metabase/mcp/v2/tools/ui_credential.clj b/src/metabase/mcp/v2/tools/ui_credential.cljindex 4f7dbaea0c7..7bf79a34371 100644--- a/src/metabase/mcp/v2/tools/ui_credential.clj+++ b/src/metabase/mcp/v2/tools/ui_credential.clj@@ -21,6 +21,7 @@(registry/deftool refresh-ui-credential"Refresh the scoped credential used by a Metabase MCP App. Called by the app itself, not by the model."{:name "refresh_ui_credential"+ :default-access :allowed;; The same scope as the UI tools the iframe renders. Any token can read the shells, so this scope, not the;; shell read, is what keeps a credential from a token that could not call those tools.:scope metabot.scope/agent-query-rundiff --git a/src/metabase/mcp/v2/tools/visualize.clj b/src/metabase/mcp/v2/tools/visualize.cljindex 8a9005cea37..ecfeabfdec0 100644--- a/src/metabase/mcp/v2/tools/visualize.clj+++ b/src/metabase/mcp/v2/tools/visualize.clj@@ -108,6 +108,7 @@Use this for any request to show, display, visualize, plot, chart, or present results — for example `Show me customers`, `Show me orders by month`, `Display revenue by region`, `Visualize active users over time`. Rendering the visualization IS the final answer: do not call execute_query or execute_sql afterwards to restate the numbers, and do not tell the user to change display types or open the Metabase query builder, a panel, or a sidebar — this is a lightweight inline visualization, not the full Metabase UI."{:name "visualize_query"+ :default-access :allowed:scope (v2.resources/resource-scope v2.resources/visualize-query-uri);; Not idempotent: the fresh-`query` path mints a new handle row on every call.:annotations {:readOnlyHint true}@@ -133,6 +134,7 @@ Use this for any request to show, display, visualize, plot, chart, or present re(registry/deftool render-drill-through"Render the drill-through visualization the user just navigated into. Use this — not an execute tool — when the user asks to show a result and their message carries a handle UUID; it is the exact follow-up for the phrase `Show me the result`. Pass that UUID through as query_handle without running the query yourself. Like visualize_query, this renders a lightweight inline visualization and is the final answer: do not restate the numbers with an execute tool, and do not tell the user to change display types or open a Metabase panel or sidebar."{:name "render_drill_through"+ :default-access :allowed:scope (v2.resources/resource-scope v2.resources/render-drill-through-uri):annotations {:readOnlyHint true :idempotentHint true}:required-extensions #{:mcp-app-ui}diff --git a/src/metabase/metabot/usage_controls.clj b/src/metabase/metabot/usage_controls.cljnew file mode 100644index 00000000000..da3b16dfbd7--- /dev/null+++ b/src/metabase/metabot/usage_controls.clj@@ -0,0 +1,23 @@+(ns metabase.metabot.usage-controls+ "The groups each mode of an AI usage controls page (Admin > AI > Usage controls) governs: simple mode sets one policy+ for All Users and All tenant users, group-level mode one per group."+ (:require+ [metabase.permissions.core :as perms]+ [metabase.util :as u]))++(set! *warn-on-reflection* true)++(defn simple-mode-group-ids+ "The IDs of the groups an AI usage controls page governs in simple mode and hides in group-level mode: All Users and+ All tenant users."+ []+ [(u/the-id (perms/all-users-group)) (u/the-id (perms/all-external-users-group))])++(defn visible-groups-clause+ "A HoneySQL condition matching, on `column`, the groups an AI usage controls page shows in the mode selected by+ `advanced?`: Administrators and the simple-mode groups in simple mode, every group but the simple-mode groups in+ group-level mode."+ [column advanced?]+ (if advanced?+ [:not-in column (simple-mode-group-ids)]+ [:in column (conj (simple-mode-group-ids) (u/the-id (perms/admin-group)))]))diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.cljindex 67bc917b9f5..f6fb01fa9ce 100644--- a/src/metabase/models/resolution.clj+++ b/src/metabase/models/resolution.clj@@ -70,6 +70,7 @@:model/ImplicitAction metabase.actions.models:model/LoginHistory metabase.login-history.models.login-history:model/McpFeedback metabase.mcp.models.mcp-feedback+ :model/McpGroupPermission metabase.mcp.models.mcp-group-permission:model/McpQueryHandle metabase.mcp.models.mcp-query-handle:model/McpSessionLog metabase.mcp.models.mcp-session-log:model/McpToolCallLog metabase.mcp.models.mcp-tool-call-logdiff --git a/test/metabase/agent_api/query_guards_test.clj b/test/metabase/agent_api/query_guards_test.cljindex fa899391eb7..7de10197089 100644--- a/test/metabase/agent_api/query_guards_test.clj+++ b/test/metabase/agent_api/query_guards_test.clj@@ -225,6 +225,15 @@[token-scopes]{:mcp-ui-credential {:uid 1 :sid "session" :token-scopes token-scopes}})+(def ^:private sql-allowed+ "A `check-execute-sql-allowed!` for a user whose groups allow `execute_sql`."+ (constantly nil))++(defn- sql-denied+ "A `check-execute-sql-allowed!` for a user whose groups deny `execute_sql`."+ []+ (throw (ex-info "execute_sql is not enabled for your groups" {:status-code 403})))+(def ^:private legacy-native {:database 1 :type "native" :native {:query "SELECT 1"}})(def ^:private mbql-5-native {:lib/type "mbql/query" :database 1:stages [{:lib/type "mbql.stage/native" :native "SELECT 1"}]})@@ -236,40 +245,54 @@agent:sql:run — a hand-rolled payload would most naturally use the legacy shape, while execute_sqlmints MBQL 5"(are [query] (= 403 (thrown-status #(query-guards/check-mcp-ui-native-query!- (ui-request #{"agent:content:read" "agent:query:run"})+ sql-allowed (ui-request #{"agent:content:read" "agent:query:run"})query)))legacy-nativembql-5-native))(testing "the refusal names the scope the client would need"(is (re-find #"agent:sql:run"(try (query-guards/check-mcp-ui-native-query!- (ui-request #{"agent:query:run"}) legacy-native)+ sql-allowed (ui-request #{"agent:query:run"}) legacy-native)""(catch clojure.lang.ExceptionInfo e (ex-message e))))))(testing "grants that cover agent:sql:run pass"(are [scopes] (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query!- (ui-request scopes) legacy-native)))+ sql-allowed (ui-request scopes) legacy-native)))#{"agent:sql:run"}#{"agent:sql:execute"} ; v1's concrete scope keeps working#{"agent:sql:*"} ; metabot permissions grant wildcards#{:metabase.api.macros.scope/unrestricted})) ; browser-session MCP clients(testing "non-native queries are never gated, whatever the grant"- (is (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query! (ui-request #{}) mbql-query)))))+ (is (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query!+ sql-allowed (ui-request #{}) mbql-query)))))(testing "requests not authenticated by a UI credential pass through untouched"- (is (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query! {} legacy-native)))))+ (is (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query! sql-allowed {} legacy-native)))))(testing "a credential carrying no scopes claim fails closed — a rolling deploy can mint one"(is (= 403 (thrown-status #(query-guards/check-mcp-ui-native-query!- {:mcp-ui-credential {:uid 1 :sid "session"}} legacy-native)))))+ sql-allowed {:mcp-ui-credential {:uid 1 :sid "session"}} legacy-native)))))(testing "the kill switch outranks the grant"(mt/with-temporary-setting-values [mcp-execute-sql-enabled false](is (= 403 (thrown-status #(query-guards/check-mcp-ui-native-query!- (ui-request #{"agent:sql:run"}) legacy-native))))))+ sql-allowed (ui-request #{"agent:sql:run"}) legacy-native))))))+ (testing "a user whose groups deny execute_sql is refused native queries, whatever the grant"+ (are [query] (= "execute_sql is not enabled for your groups"+ (try (query-guards/check-mcp-ui-native-query!+ sql-denied (ui-request #{:metabase.api.macros.scope/unrestricted}) query)+ ""+ (catch clojure.lang.ExceptionInfo e (ex-message e))))+ legacy-native+ mbql-5-native))+ (testing "the group policy is consulted only for a native query on a UI credential"+ (is (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query!+ sql-denied (ui-request #{"agent:query:run"}) mbql-query))))+ (is (= ::no-throw (thrown-status #(query-guards/check-mcp-ui-native-query! sql-denied {} legacy-native)))))(testing "M2: the scope check runs before the kill switch, so an unauthorized caller cannot tell themcp-execute-sql-enabled state apart from the 403 it gets — the message names the missing scope,not the kill switch, whether the switch is on or off"(doseq [enabled? [true false]](mt/with-temporary-setting-values [mcp-execute-sql-enabled enabled?]- (let [msg (try (query-guards/check-mcp-ui-native-query! (ui-request #{"agent:query:run"}) legacy-native)+ (let [msg (try (query-guards/check-mcp-ui-native-query!+ sql-allowed (ui-request #{"agent:query:run"}) legacy-native)""(catch clojure.lang.ExceptionInfo e (ex-message e)))](is (re-find #"agent:sql:run" msg))diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.cljindex 9b4f61f2e15..3a25a7d0e67 100644--- a/test/metabase/cmd/copy_test.clj+++ b/test/metabase/cmd/copy_test.clj@@ -95,6 +95,7 @@:model/Dependency:model/DependencyStatus:model/ExplorationQueryResult+ :model/McpGroupPermission:model/McpQueryHandle:model/McpSessionLog:model/McpToolCallLogdiff --git a/test/metabase/mcp/permissions_test.clj b/test/metabase/mcp/permissions_test.cljnew file mode 100644index 00000000000..faf45fde7c6--- /dev/null+++ b/test/metabase/mcp/permissions_test.clj@@ -0,0 +1,167 @@+(ns metabase.mcp.permissions-test+ "Per-group MCP tool access as the resolver, the v2 registry and the transport's `initialize` enforce it. The+ policy is stubbed here; how it is collected from group rows is `metabase-enterprise.mcp.permissions-test`."+ (:require+ [clojure.set :as set]+ [clojure.string :as str]+ [clojure.test :refer :all]+ [metabase.api.common :as api]+ [metabase.mcp.permissions :as mcp.perms]+ [metabase.mcp.v2.api :as v2.api]+ [metabase.mcp.v2.common :as common]+ [metabase.mcp.v2.message :as message]+ [metabase.mcp.v2.registry :as registry]+ [metabase.mcp.v2.resources :as v2.resources]+ [metabase.mcp.v2.test-util]+ [metabase.test :as mt]))++(set! *warn-on-reflection* true)++(def ^:private no-access-policy+ [])++(def ^:private allowed-by-default+ {:name "hummingbird" :default-access :allowed})++(def ^:private denied-by-default+ {:name "shrike" :default-access :denied})++(def ^:private renamed-tool+ {:name "kestrel" :default-access :denied :renamed-from ["sparrowhawk"]})++(defn- listed-tool-names+ "The names `tools/list` returns for the current user."+ []+ (into #{} (map :name) (registry/list-tools)))++(deftest ^:parallel default-access-applies-without-an-entry-test+ (testing "default allowed with no entry"+ (is (true? (mcp.perms/tool-allowed? [{}] allowed-by-default))))+ (testing "default denied with no entry"+ (is (false? (mcp.perms/tool-allowed? [{}] denied-by-default)))))++(deftest ^:parallel explicit-entry-beats-default-test+ (testing "explicit no beats default allowed"+ (is (false? (mcp.perms/tool-allowed? [{"hummingbird" "no"}] allowed-by-default))))+ (testing "explicit yes beats default denied"+ (is (true? (mcp.perms/tool-allowed? [{"shrike" "yes"}] denied-by-default)))))++(deftest ^:parallel any-group-allowing-wins-test+ (testing "yes in one group beats no in another"+ (is (true? (mcp.perms/tool-allowed? [{"hummingbird" "no"} {"hummingbird" "yes"}] allowed-by-default))))+ (testing "an untouched group's default allowed beats another group's explicit no"+ (is (true? (mcp.perms/tool-allowed? [{"hummingbird" "no"} {}] allowed-by-default))))+ (testing "every group saying no denies"+ (is (false? (mcp.perms/tool-allowed? [{"hummingbird" "no"} {"hummingbird" "no"}] allowed-by-default)))))++(deftest ^:parallel stale-and-renamed-entries-test+ (testing "a stale name is inert"+ (is (true? (mcp.perms/tool-allowed? [{"dodo" "no"}] allowed-by-default)))+ (is (false? (mcp.perms/tool-allowed? [{"dodo" "yes"}] denied-by-default))))+ (testing "a :renamed-from name carries the entry"+ (is (true? (mcp.perms/tool-allowed? [{"sparrowhawk" "yes"}] renamed-tool))))+ (testing "the current name's own entry wins over a former name's"+ (is (false? (mcp.perms/tool-allowed? [{"kestrel" "no" "sparrowhawk" "yes"}] renamed-tool)))))++(deftest ^:parallel unrestricted-and-no-access-policies-test+ (is (true? (mcp.perms/tool-allowed? mcp.perms/unrestricted-policy denied-by-default)))+ (is (true? (mcp.perms/enabled? mcp.perms/unrestricted-policy)))+ (testing "no enabled group allows nothing, whatever the defaults"+ (is (false? (mcp.perms/tool-allowed? no-access-policy allowed-by-default)))+ (is (false? (mcp.perms/enabled? no-access-policy))))+ (testing "an enabled group with no overrides enables the connection"+ (is (true? (mcp.perms/enabled? [{}])))))++(deftest ^:parallel superuser-and-internal-callers-bypass-test+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly no-access-policy)]+ (testing "a superuser is never narrowed by group policy"+ (mt/with-current-user (mt/user->id :crowberto)+ (is (= mcp.perms/unrestricted-policy (mcp.perms/policy-for-current-user)))))+ (testing "an internal caller with no current user is unrestricted"+ (binding [api/*current-user-id* nil]+ (is (= mcp.perms/unrestricted-policy (mcp.perms/policy-for-current-user)))))+ (testing "an ordinary user gets the resolved policy"+ (mt/with-current-user (mt/user->id :rasta)+ (is (= no-access-policy (mcp.perms/policy-for-current-user)))))))++(deftest ^:parallel denied-tool-is-hidden-and-refused-test+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly [{"test_echo" "no"}])]+ (mt/with-current-user (mt/user->id :rasta)+ (testing "tools/list hides the explicitly denied tool and the tool denied by default, and only those"+ (is (= #{"test_echo" "test_off_by_default"}+ (set/difference (binding [api/*current-user-id* nil] (listed-tool-names))+ (listed-tool-names)))))+ (testing "the keepalive hash sees the narrower list, so an open stream learns of the change"+ (is (not= (registry/tools-hash)+ (binding [api/*current-user-id* nil] (registry/tools-hash)))))+ (testing "tools/call refuses the denied tool and names the fix"+ (let [{:keys [error]} (registry/call-tool nil nil "test_echo" {})]+ (is (= common/error-code-invalid-request (:code error)))+ (is (= (str "Tool \"test_echo\" is not enabled for your groups. "+ "Ask an administrator to enable it under Admin > AI > Usage controls > MCP tools access.")+ (message/render (:message error))))))+ (testing "a token without the tool's scope still gets the group refusal, not a step-up challenge"+ (let [{:keys [error]} (registry/call-tool #{"agent:metadata:read"} nil "test_echo" {})]+ (is (nil? (:insufficient-scope error)))+ (is (str/starts-with? (message/render (:message error))+ "Tool \"test_echo\" is not enabled for your groups."))))+ (testing "tools/call refuses the tool denied by default"+ (is (= common/error-code-invalid-request+ (get-in (registry/call-tool nil nil "test_off_by_default" {}) [:error :code])))))))++(deftest ^:parallel allowed-tool-dispatches-test+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly [{"test_off_by_default" "yes"}])]+ (mt/with-current-user (mt/user->id :rasta)+ (testing "a tool at its default allowed dispatches"+ (is (= {:ok true :message "pong"}+ (get-in (registry/call-tool nil nil "test_echo" {}) [:result :structuredContent]))))+ (testing "an explicit yes lists and dispatches a tool denied by default"+ (is (contains? (listed-tool-names) "test_off_by_default"))+ (is (= {:ok true}+ (get-in (registry/call-tool nil nil "test_off_by_default" {}) [:result :structuredContent])))))))++(deftest ^:parallel disabled-policy-hides-every-tool-test+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly no-access-policy)]+ (mt/with-current-user (mt/user->id :rasta)+ (is (empty? (listed-tool-names)))+ (is (= common/error-code-invalid-request+ (get-in (registry/call-tool nil nil "test_echo" {}) [:error :code]))))))++(deftest ^:parallel initialize-is-refused-when-mcp-is-disabled-test+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly no-access-policy)]+ (let [initialize {:jsonrpc "2.0" :method "initialize" :params {} :id 1}]+ (testing "the handshake names the fix instead of handing out an empty tool list"+ (is (= {:jsonrpc "2.0"+ :id 1+ :error {:code common/error-code-invalid-request+ :message (str "MCP access is not enabled for your account. "+ "Ask an administrator to enable it under Admin > AI > Usage controls > MCP tools access.")}}+ (mt/user-http-request :rasta :post 403 "metabase-mcp" initialize))))+ (testing "a superuser still connects"+ (is (=? {:result {:protocolVersion string?}}+ (mt/user-http-request :crowberto :post 200 "metabase-mcp" initialize)))))))++(deftest ^:parallel app-only-tool-follows-the-ui-tools-test+ (mt/with-current-user (mt/user->id :rasta)+ (testing "refresh_ui_credential is not on the admin's grid, so an entry stored for it is ignored while a UI tool+ is allowed"+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly [{"refresh_ui_credential" "no"}])]+ (is (contains? (listed-tool-names) "refresh_ui_credential"))))+ (testing "it is hidden and refused once every UI tool is denied"+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly [{"visualize_query" "no"+ "render_drill_through" "no"}])]+ (is (not (contains? (listed-tool-names) "refresh_ui_credential")))+ (is (= common/error-code-invalid-request+ (get-in (registry/call-tool nil nil "refresh_ui_credential" {}) [:error :code])))))))++(deftest ^:parallel resources-read-is-refused-when-mcp-is-disabled-test+ (let [read-fields #(#'v2.api/handle-resources-read 1 {:uri v2.resources/fields-catalog-uri} nil nil)]+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly no-access-policy)]+ (testing "a session opened before an admin turned MCP off reads nothing"+ (mt/with-current-user (mt/user->id :rasta)+ (is (=? {:error {:code common/error-code-invalid-request}}+ (read-fields)))))+ (testing "a superuser still reads"+ (mt/with-current-user (mt/user->id :crowberto)+ (is (=? {:result {:contents seq}}+ (read-fields))))))))diff --git a/test/metabase/mcp/transport_test.clj b/test/metabase/mcp/transport_test.cljindex 8497b6ad907..fc8ad73e043 100644--- a/test/metabase/mcp/transport_test.clj+++ b/test/metabase/mcp/transport_test.clj@@ -88,21 +88,53 @@(testing "the keepalive written before the cancellation still reached the client"(is (= ": keepalive\n\n" (str sink)))))))+(defn- scripted-hash-fn!+ "A tools hash fn whose `n`th read returns the `n`th of `reads`, throwing for `::fail`, and offering a cancellation on+ `canceled` from the third read so the loop ends after a known number of ticks."+ [canceled reads]+ (let [calls (atom 0)]+ (fn []+ (let [call (swap! calls inc)+ read (nth reads (dec call))]+ (when (>= call 3)+ (a/offer! canceled ::request-canceled))+ (if (= ::fail read)+ (throw (ex-info "app database unavailable" {}))+ read)))))++(defn- run-scripted-keepalive-loop!+ "Run the keepalive loop over [[scripted-hash-fn!]] `reads`, returning what it wrote, after checking it returned+ after three ticks."+ [reads]+ (let [canceled (a/promise-chan)+ sink (StringWriter.)]+ (is (= :returned (run-keepalive-loop! sink (scripted-hash-fn! canceled reads) canceled 1)))+ (is (= 3 (count (re-seq #": keepalive" (str sink)))))+ (str sink)))++(defn- list-changed-count+ [output]+ (count (re-seq #"notifications/tools/list_changed" output)))+(deftest keepalive-loop-emits-tools-list-changed-on-hash-change-test(testing "a change in the visible tool set between ticks emits notifications/tools/list_changed exactly once"- (let [canceled (a/promise-chan)- sink (StringWriter.)- calls (atom 0)- hash-fn (fn []- (let [n (swap! calls inc)]- ;; cancel on the third read so the loop terminates after a known number of ticks- (when (>= n 3)- (a/offer! canceled ::request-canceled))- (if (= n 1) "hash-1" "hash-2")))]- (is (= :returned (run-keepalive-loop! sink hash-fn canceled 1)))- (let [output (str sink)]- (is (= 3 (count (re-seq #": keepalive" output))))- (is (= 1 (count (re-seq #"notifications/tools/list_changed" output))))))))+ (is (= 1 (list-changed-count (run-scripted-keepalive-loop! ["hash-1" "hash-2" "hash-2"]))))))++(deftest keepalive-loop-survives-a-failing-tools-hash-test+ (testing "a tick whose tools hash throws keeps the previous hash, so the stream stays open and nothing is announced"+ (is (zero? (list-changed-count (run-scripted-keepalive-loop! ["hash-1" ::fail "hash-1"])))))+ (testing "a failing first read doesn't end the stream, and the first hash read after it seeds the hash rather than+ announcing a change"+ (is (zero? (list-changed-count (run-scripted-keepalive-loop! [::fail "hash-1" "hash-1"])))))+ (testing "a change after that seeding read is still announced"+ (is (= 1 (list-changed-count (run-scripted-keepalive-loop! [::fail "hash-1" "hash-2"]))))))++(deftest keepalive-loop-warns-once-for-a-sustained-tools-hash-failure-test+ (testing "a tools hash that keeps failing warns on the first failure and logs the rest at debug"+ (mt/with-log-messages-for-level [messages [metabase.mcp.transport :debug]]+ (run-scripted-keepalive-loop! [::fail ::fail ::fail])+ (is (= [:warn :debug :debug]+ (map :level (filter #(re-find #"hash the MCP tool list" (str (:message %))) (messages))))))))(defn- keepalive-counts []@@#'mcp.transport/keepalive-stream-counts)diff --git a/test/metabase/mcp/v2/api_test.clj b/test/metabase/mcp/v2/api_test.cljindex e0dffad5719..f9749530a5a 100644--- a/test/metabase/mcp/v2/api_test.clj+++ b/test/metabase/mcp/v2/api_test.clj@@ -7,6 +7,7 @@[metabase.mcp.db :as mcp.db][metabase.mcp.http-handler :as mcp.http-handler][metabase.mcp.paths :as mcp.paths]+ [metabase.mcp.permissions :as mcp.perms][metabase.mcp.session :as mcp.session][metabase.mcp.settings :as mcp.settings][metabase.mcp.ui-resource :as mcp.ui-resource]@@ -276,12 +277,14 @@(testing "the cause is a missing permission, not an expired login"(is (re-find #"(?i)missing permission" instructions))(is (re-find #"(?i)not an expired login" instructions)))- (testing "GHY-4555: the roster is not a grant. Every tool is listed whatever the token holds, but a scope-filtered+ (testing "GHY-4555: the roster is not a grant. Tools are listed whatever the token holds, but a scope-filteredlist is the conventional design and nothing on the wire signals ours, so a model asked what theconnection could do read the roster as a grant and named scopes it did not hold"- (is (re-find #"(?i)every tool is listed whatever this connection holds" instructions))+ (is (re-find #"(?i)tools are listed whatever this connection holds" instructions))(is (re-find #"(?i)says nothing about its permissions" instructions))- (is (re-find #"(?i)only a failed call reveals a missing one" instructions)))+ (is (re-find #"(?i)only a failed call reveals a missing one" instructions))+ (testing "while an admin's group policy does hide tools, so the model drops advice about one it cannot see"+ (is (re-find #"(?i)an unlisted tool is off for this user" instructions))))(testing "a resource read is refused the same way as a tool call, so the guidance covers both"(is (re-find #"(?i)tool call or resource read" instructions)))(testing "the model names the tool and the permission, as the consent screen names it"@@ -832,38 +835,25 @@(is (not (:isError result)))(is (= {:ok true :message "pong"} (:structuredContent result))))))))))-(defn- do-with-temp-tool!- "Register a throwaway tool for the body, then restore the registry. Lets a test assert scope filtering against a- tool whose scope differs from the token's without depending on a not-yet-landed real tool."- [tool thunk]- (let [tools-atom @#'registry/tools*- snapshot @tools-atom]- (try- (registry/register-tool! tool)- (thunk)- (finally- (reset! tools-atom snapshot)- ;; register-tool! flushes the manifest cache; do the same on the way out so a later test doesn't see- ;; a manifest that still lists the throwaway tool.- (reset! @#'registry/manifest-cache nil)))))-(defn- do-with-bearer-token!- "Issue an OAuth access token carrying `scopes` for crowberto and call `f` with the auth headers."- [scopes f]- (mt/with-temporary-setting-values [site-url "http://localhost:3000"]- (oauth-server.tu/with-oauth-client [client-id]- (mt/with-model-cleanup [:model/OAuthAccessToken]- (let [token (str (random-uuid))]- ;; `:token` is stored hashed — the resolver hashes the presented string before looking it- ;; up, so the row has to be written the same way a real issued token would be — including a- ;; live `oauth_client` row, since the resolver fails closed on a token whose client is gone.- (t2/insert! :model/OAuthAccessToken- {:token (oidc.util/hash-token token)- :user_id (mt/user->id :crowberto)- :client_id client-id- :scope (vec scopes)- :expiry (+ (System/currentTimeMillis) 3600000)})- (f {"authorization" (str "Bearer " token)}))))))+ "Issue an OAuth access token carrying `scopes` for `user` (default crowberto) and call `f` with the auth headers."+ ([scopes f]+ (do-with-bearer-token! :crowberto scopes f))+ ([user scopes f]+ (mt/with-temporary-setting-values [site-url "http://localhost:3000"]+ (oauth-server.tu/with-oauth-client [client-id]+ (mt/with-model-cleanup [:model/OAuthAccessToken]+ (let [token (str (random-uuid))]+ ;; `:token` is stored hashed — the resolver hashes the presented string before looking it+ ;; up, so the row has to be written the same way a real issued token would be — including a+ ;; live `oauth_client` row, since the resolver fails closed on a token whose client is gone.+ (t2/insert! :model/OAuthAccessToken+ {:token (oidc.util/hash-token token)+ :user_id (mt/user->id user)+ :client_id client-id+ :scope (vec scopes)+ :expiry (+ (System/currentTimeMillis) 3600000)})+ (f {"authorization" (str "Bearer " token)})))))))(defn- embedded-credential"The UI credential the fallback template embedded in shell `html`, or nil when it embedded none."@@ -932,6 +922,34 @@{:request-options {:headers {"x-metabase-mcp-ui-auth" credential}}}native-query))))))))))))+(deftest ui-credential-native-query-honors-the-execute-sql-group-policy-test+ (testing "a user whose groups deny execute_sql must not run raw SQL through the iframe credential either, or+ refresh_ui_credential plus POST /api/dataset rebuilds the tool an admin denied. The policy is read per+ request, so a credential minted while execute_sql was allowed stops working once it is denied"+ (mcp.ui-resource/with-fallback-template+ (let [native-query {:database (mt/id) :type "native" :native {:query "SELECT 1"}}+ mbql-query {:database (mt/id) :type "query" :query {:source-table (mt/id :venues) :limit 1}}]+ (do-with-bearer-token!+ :rasta #{"agent:query:run" "agent:sql:run"}+ (fn [headers]+ (let [credential (ui-credential-for headers)+ post (fn [status query]+ (client/client-full-response+ :post status "dataset"+ {:request-options {:headers {"x-metabase-mcp-ui-auth" credential}}}+ query))]+ (is (string? credential)+ "the shell must render a credential — otherwise this test passes vacuously")+ (testing "denied: the native query is refused with the execute_sql denial"+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly [{"execute_sql" "no"}])]+ (is (re-find #"needs the \"execute_sql\" tool, which is not enabled for your groups"+ (str (:body (post 403 native-query)))))+ (testing "while its MBQL queries are untouched"+ (is (= 202 (:status (post 202 mbql-query)))))))+ (testing "allowed: the same credential runs the native query"+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly [{"execute_sql" "yes"}])]+ (is (= 202 (:status (post 202 native-query)))))))))))))+(deftest bearer-token-dispatches-with-its-own-scopes-test(testing "GHY-4287: the session middleware resolves an OAuth bearer token itself, so a bearer request reaches thetransport on the same authenticated branch a cookie session does. It must still dispatch with the@@ -940,13 +958,14 @@;; Register a throwaway tool on a DIFFERENT scope (`agent:content:write`, which the token below does not carry);; so the negative half of the scope contract has teeth independent of which real write tools are registered:;; this test fails if the bearer request dispatches unrestricted.- (do-with-temp-tool!- {:name "scope_probe_write"- :scope metabot.scope/agent-content-write- :description "test-only tool gated on a write scope the narrow token lacks"- :annotations {:readOnlyHint false}- :args [:map]- :handler (fn [_ _] nil)}+ (v2.tu/do-with-temp-tool!+ {:name "scope_probe_write"+ :scope metabot.scope/agent-content-write+ :default-access :allowed+ :description "test-only tool gated on a write scope the narrow token lacks"+ :annotations {:readOnlyHint false}+ :args [:map]+ :handler (fn [_ _] nil)}(fn [](mt/with-temporary-setting-values [site-url "http://localhost:3000"](oauth-server.tu/with-oauth-client [client-id]@@ -1347,13 +1366,14 @@(deftest unscoped-callers-never-get-an-insufficient-scope-challenge-test(testing "GHY-4543: a cookie session is stamped unrestricted, so a tool gated on any scope is served over 200"- (do-with-temp-tool!- {:name "scope_probe_sql"- :scope metabot.scope/agent-sql-run- :description "test-only tool gated on agent:sql:run"- :annotations {:readOnlyHint true}- :args [:map]- :handler (fn [_ _] {:content [{:type "text" :text "served"}]})}+ (v2.tu/do-with-temp-tool!+ {:name "scope_probe_sql"+ :scope metabot.scope/agent-sql-run+ :default-access :allowed+ :description "test-only tool gated on agent:sql:run"+ :annotations {:readOnlyHint true}+ :args [:map]+ :handler (fn [_ _] {:content [{:type "text" :text "served"}]})}(fn [](let [[session-id] (initialize!)response (mcp-request (jsonrpc-request "tools/call" {:name "scope_probe_sql" :arguments {}})diff --git a/test/metabase/mcp/v2/registry_test.clj b/test/metabase/mcp/v2/registry_test.cljindex 7aa17a25e1e..cdeed2f1797 100644--- a/test/metabase/mcp/v2/registry_test.clj+++ b/test/metabase/mcp/v2/registry_test.clj@@ -28,11 +28,12 @@would honor a set, because `registered-scopes` would otherwise collect the set itself rather thanits members"(is (thrown-with-msg? Exception #"registered without a :scope string"- (registry/register-tool! {:name "set_scope_probe"- :scope #{"agent:content:read" "agent:query:run"}- :description "probe: never registers"- :args [:map]- :handler (fn [_ _] nil)})))))+ (registry/register-tool! {:name "set_scope_probe"+ :scope #{"agent:content:read" "agent:query:run"}+ :default-access :allowed+ :description "probe: never registers"+ :args [:map]+ :handler (fn [_ _] nil)})))))(deftest ^:parallel call-tool-scope-check-test(testing "tools/call re-checks scope even for a tool that exists"@@ -233,6 +234,7 @@(is (thrown-with-msg? Exception #"unknown option"(registry/register-tool! {:name "typo_key":scope "agent:content:read"+ :default-access :allowed:description "x":args [:map]:handler (fn [_ _] nil)@@ -241,6 +243,7 @@(is (thrown-with-msg? Exception #"set of keywords"(registry/register-tool! {:name "bad_extensions":scope "agent:content:read"+ :default-access :allowed:description "x":args [:map]:handler (fn [_ _] nil)@@ -249,6 +252,7 @@(is (thrown-with-msg? Exception #"unknown client extension"(registry/register-tool! {:name "unknown_extension":scope "agent:content:read"+ :default-access :allowed:description "x":args [:map]:handler (fn [_ _] nil)@@ -268,37 +272,42 @@(deftest registration-validates-required-fields-test(testing "a blank :name fails loudly"(is (thrown-with-msg? Exception #":name"- (registry/register-tool! {:name ""- :scope "agent:content:read"- :description "x"- :args [:map]- :handler (fn [_ _] nil)}))))+ (registry/register-tool! {:name ""+ :scope "agent:content:read"+ :default-access :allowed+ :description "x"+ :args [:map]+ :handler (fn [_ _] nil)}))))(testing "a missing :description fails loudly"(is (thrown-with-msg? Exception #"without a :description"- (registry/register-tool! {:name "no_desc"- :scope "agent:content:read"- :args [:map]- :handler (fn [_ _] nil)}))))+ (registry/register-tool! {:name "no_desc"+ :scope "agent:content:read"+ :default-access :allowed+ :args [:map]+ :handler (fn [_ _] nil)}))))(testing "a missing :args schema fails loudly"(is (thrown-with-msg? Exception #":args Malli schema"- (registry/register-tool! {:name "no_args"- :scope "agent:content:read"- :description "x"- :handler (fn [_ _] nil)}))))+ (registry/register-tool! {:name "no_args"+ :scope "agent:content:read"+ :default-access :allowed+ :description "x"+ :handler (fn [_ _] nil)}))))(testing "a non-fn :handler fails loudly"(is (thrown-with-msg? Exception #":handler fn"- (registry/register-tool! {:name "bad_handler"- :scope "agent:content:read"- :description "x"- :args [:map]- :handler "not-a-fn"}))))+ (registry/register-tool! {:name "bad_handler"+ :scope "agent:content:read"+ :default-access :allowed+ :description "x"+ :args [:map]+ :handler "not-a-fn"}))))(testing "an optional non-nullable field fails the strict-tool nullability check"(is (thrown-with-msg? Exception #"optional non-nullable field"- (registry/register-tool! {:name "bad_schema"- :scope "agent:content:read"- :description "x"- :args [:map [:x {:optional true} :string]]- :handler (fn [_ _] nil)})))))+ (registry/register-tool! {:name "bad_schema"+ :scope "agent:content:read"+ :default-access :allowed+ :description "x"+ :args [:map [:x {:optional true} :string]]+ :handler (fn [_ _] nil)})))));;; ------------------------------------- Write-tool scope invariants ----------------------------------------@@ -312,18 +321,6 @@granting writes, so it keeps its own scope rather than folding into `content:write`."#{"agent:content:write" "agent:delivery:write" "agent:sql:run"})-(defn- do-with-temp-tool!- "Register a throwaway tool for the body, then restore the registry and flush the manifest cache."- [tool thunk]- (let [tools-atom @#'registry/tools*- snapshot @tools-atom]- (try- (registry/register-tool! tool)- (thunk)- (finally- (reset! tools-atom snapshot)- (reset! @#'registry/manifest-cache nil)))))-;; not ^:parallel: registers a tool in the shared registry(deftest tools-hash-test(testing "tools-hash is a stable 8-char hex string"@@ -331,12 +328,13 @@(is (= (registry/tools-hash) (registry/tools-hash))))(testing "it changes when the listed tool set does"(let [before (registry/tools-hash)]- (do-with-temp-tool!- {:name "hash_probe"- :scope "agent:content:read"- :description "test-only tool that only exists to move the hash"- :args [:map]- :handler (fn [_ _] nil)}+ (v2.tu/do-with-temp-tool!+ {:name "hash_probe"+ :scope "agent:content:read"+ :default-access :allowed+ :description "test-only tool that only exists to move the hash"+ :args [:map]+ :handler (fn [_ _] nil)}(fn [](is (not= before (registry/tools-hash))))))))@@ -360,12 +358,13 @@no `:annotations` is published to clients as mutating while its raw registry entry carries no`:readOnlyHint` at all — and enumerating from the raw entry would skip exactly the tool theseinvariants exist to catch: one that mutates, says nothing about it, and rides a read scope."- (do-with-temp-tool!- {:name "annotation_free_mutator"- :scope "agent:content:read"- :description "test-only tool that declares no annotations at all"- :args [:map]- :handler (fn [_ _] nil)}+ (v2.tu/do-with-temp-tool!+ {:name "annotation_free_mutator"+ :scope "agent:content:read"+ :default-access :allowed+ :description "test-only tool that declares no annotations at all"+ :args [:map]+ :handler (fn [_ _] nil)}(fn [](testing "clients are told it mutates"(is (false? (->> (registry/list-tools)@@ -386,12 +385,13 @@(doseq [scope (sort write-scopes):let [tool-name (str "scope_probe_" (str/replace scope #"\W" "_"))]](testing scope- (do-with-temp-tool!- {:name tool-name- :scope scope- :description "test-only tool gated on a scope the token lacks"- :args [:map]- :handler (fn [_ _] nil)}+ (v2.tu/do-with-temp-tool!+ {:name tool-name+ :scope scope+ :default-access :allowed+ :description "test-only tool gated on a scope the token lacks"+ :args [:map]+ :handler (fn [_ _] nil)}(fn [](is (contains? (set (map :name (registry/list-tools))) tool-name))(is (str/starts-with? (message/render (-> (registry/call-tool #{"agent:content:read"} nil tool-name {})@@ -399,9 +399,10 @@(str "Insufficient scope to call tool: \"" tool-name "\"."))))))))(testing "GHY-4543: the extension filter still hides tools"(testing "a tool needing a client extension the caller lacks"- (do-with-temp-tool!+ (v2.tu/do-with-temp-tool!{:name "ui_probe":scope "agent:content:read"+ :default-access :allowed:description "test-only tool that needs MCP Apps UI":args [:map]:handler (fn [_ _] nil)@@ -510,16 +511,41 @@;; not ^:parallel: registers a throwaway tool(deftest description-permission-text-without-registered-scope-description-test(testing "GHY-4543: a scope with no consent-screen label is named by its scope string alone"- (do-with-temp-tool!- {:name "unlabelled_scope_probe"- :scope "agent:unlabelled:probe"- :description "Probe."- :args [:map]- :handler (fn [_ _] nil)}+ (v2.tu/do-with-temp-tool!+ {:name "unlabelled_scope_probe"+ :scope "agent:unlabelled:probe"+ :default-access :allowed+ :description "Probe."+ :args [:map]+ :handler (fn [_ _] nil)}(fn [](is (= "Requires the agent:unlabelled:probe permission.\n\nProbe."(get (published-descriptions) "unlabelled_scope_probe")))))))+;;; ------------------------------------------ Tool catalog ---------------------------------------------------------++(deftest ^:parallel first-sentence-test+ (let [first-sentence #'registry/first-sentence]+ (testing "the first sentence of a multi-sentence description"+ (is (= "Echo the message back." (first-sentence "Echo the message back. Or pong."))))+ (testing "a one-sentence description keeps its single period"+ (is (= "Echo the message back." (first-sentence "Echo the message back."))))+ (testing "a description without a period gets one"+ (is (= "Echo the message back." (first-sentence "Echo the message back"))))+ (testing "e.g. and i.e. do not end the sentence, and line breaks collapse"+ (is (= "Find terms, e.g. revenue, i.e. the definitions." (first-sentence "Find terms, e.g.\nrevenue, i.e. the definitions. Not this."))))))++(deftest ^:parallel tool-catalog-test+ (let [catalog (registry/tool-catalog)+ echo (some #(when (= "test_echo" (:name %)) %) catalog)]+ (testing "one entry per tool with the author's default as a string and the first sentence as the description"+ (is (= {:name "test_echo" :scope "agent:content:read" :description "Test-only tool." :default_access "allowed"}+ echo)))+ (testing "sorted by scope then name"+ (is (= (sort-by (juxt :scope :name) catalog) catalog)))+ (testing "app-only tools are left out, since their access follows the tools that use them"+ (is (not-any? #(= "refresh_ui_credential" (:name %)) catalog)))))+;;; ------------------------------------------ Security schemes -----------------------------------------------------(defn- published-security-schemesdiff --git a/test/metabase/mcp/v2/test_util.clj b/test/metabase/mcp/v2/test_util.cljindex 20c0376fd00..aa74bd21a45 100644--- a/test/metabase/mcp/v2/test_util.clj+++ b/test/metabase/mcp/v2/test_util.clj@@ -1,5 +1,5 @@(ns metabase.mcp.v2.test-util- "Test-only v2 MCP tools. Never loaded by the production surface."+ "Test-only v2 MCP tools and registry helpers. Never loaded by the production surface."(:require[clojure.string :as str][metabase.mcp.v2.common :as common]@@ -26,11 +26,35 @@(registry/deftool test-echo"Test-only tool. Echoes `message` back, or `pong` when none is given."- {:name "test_echo"- :scope metabot.scope/agent-content-read- :annotations {:readOnlyHint true :idempotentHint true}- :args [:map {:closed true}- [:message {:optional true} [:maybe :string]]]}+ {:name "test_echo"+ :scope metabot.scope/agent-content-read+ :default-access :allowed+ :annotations {:readOnlyHint true :idempotentHint true}+ :args [:map {:closed true}+ [:message {:optional true} [:maybe :string]]]}[{:keys [message]} _context](let [payload {:ok true :message (or message "pong")}](common/success-content payload payload)))++(registry/deftool test-off-by-default+ "Test-only tool denied by default. A group uses it only after an admin says yes."+ {:name "test_off_by_default"+ :scope metabot.scope/agent-content-read+ :default-access :denied+ :annotations {:readOnlyHint true :idempotentHint true}+ :args [:map {:closed true}]}+ [_arguments _context]+ (common/success-content {:ok true} {:ok true}))++(defn do-with-temp-tool!+ "Register `tool` for the duration of `thunk`, then restore the registry and flush the manifest cache. `tool` may+ redefine a registered tool under the same handler."+ [tool thunk]+ (let [tools-atom @#'registry/tools*+ snapshot @tools-atom]+ (try+ (registry/register-tool! tool)+ (thunk)+ (finally+ (reset! tools-atom snapshot)+ (reset! @#'registry/manifest-cache nil)))))diff --git a/test/metabase/mcp/v2/tool_names_test.clj b/test/metabase/mcp/v2/tool_names_test.cljnew file mode 100644index 00000000000..984b9cbe7c6--- /dev/null+++ b/test/metabase/mcp/v2/tool_names_test.clj@@ -0,0 +1,47 @@+(ns metabase.mcp.v2.tool-names-test+ "Pins the names of the live MCP tools. Every admin's explicit yes or no in `mcp_group_permission` is keyed by tool+ name, so a rename drops them all unless the tool declares `:renamed-from`."+ (:require+ [clojure.string :as str]+ [clojure.test :refer [deftest is]]+ [metabase.mcp.v2.api]+ [metabase.mcp.v2.registry :as registry]))++(set! *warn-on-reflection* true)++(def ^:private live-tool-names+ #{"alert_write"+ "bookmark_content"+ "browse_collection"+ "browse_data"+ "collection_write"+ "dashboard_write"+ "document_write"+ "duplicate_content"+ "execute_query"+ "execute_sql"+ "get_content"+ "get_parameter_values"+ "glossary"+ "learn"+ "measure_write"+ "metric_write"+ "question_write"+ "refresh_ui_credential"+ "render_drill_through"+ "run_saved_question"+ "search"+ "segment_write"+ "subscription_write"+ "visualize_query"})++(defn- live-tool?+ "Whether `tool` is registered by a namespace under `metabase.mcp.v2.tools`, as opposed to a test-only tool."+ [{:keys [handler]}]+ (str/starts-with? (str (some-> handler meta :ns ns-name)) "metabase.mcp.v2.tools."))++(deftest ^:parallel live-tool-names-are-pinned-test+ (is (= live-tool-names+ (into #{} (comp (filter live-tool?) (map :name)) (vals @@#'registry/tools*)))+ (str "A live MCP tool was added, removed or renamed. Update this set. A rename also needs `:renamed-from` on "+ "the tool so stored group entries follow it, or a chosen `:default-access` for the new name.")))diff --git a/test/metabase/mcp/v2/tools/question_test.clj b/test/metabase/mcp/v2/tools/question_test.cljindex 41ae611e085..dee5ea372fd 100644--- a/test/metabase/mcp/v2/tools/question_test.clj+++ b/test/metabase/mcp/v2/tools/question_test.clj@@ -8,10 +8,13 @@[metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]+ [metabase.mcp.permissions :as mcp.perms][metabase.mcp.v2.message :as message][metabase.mcp.v2.queries :as v2.queries][metabase.mcp.v2.registry :as registry][metabase.mcp.v2.test-util :as v2.tu]+ ;; Registers execute_sql, whose policy entry the native source gates read.+ [metabase.mcp.v2.tools.query][metabase.mcp.v2.tools.question :as v2.question][metabase.permissions.core :as perms][metabase.permissions.models.permissions-group :as perms-group]@@ -1088,6 +1091,54 @@(is (str/includes? (-> result :content first :text) "mcp-execute-sql-enabled"))(is (zero? (t2/count :model/Card :name "Killed Native Q")))))))))+(defn- native-source-args!+ "The `question_write` args creating a question named `card-name` from `source`, one of the sources that resolve to+ native SQL. A `:query_handle` is minted for the current user in session `sid`."+ [source sid card-name]+ (assoc (case source+ :native {:native {:database_id (mt/id) :sql "SELECT 1"}}+ :query {:query {:database (mt/id) :stages [{:native "SELECT 1"}]}}+ :query_handle {:query_handle (v2.queries/mint-query-handle!+ sid api/*current-user-id*+ (v2.queries/encode-serialized-query+ (lib/prepare-for-serialization+ (lib/native-query (mt/metadata-provider) "SELECT 1"))))})+ :method "create"+ :name card-name))++;; not ^:parallel: mt/with-model-cleanup on the shared query-handle table+(deftest native-source-honors-the-execute-sql-group-policy-test+ (testing "a user whose groups deny execute_sql must not store raw SQL through question_write either, or+ question_write plus run_saved_question rebuilds the tool an admin denied"+ (mt/with-model-cleanup [:model/Card :model/McpQueryHandle]+ (mt/with-current-user (mt/user->id :rasta)+ (let [scopes #{"agent:content:write" "agent:sql:run"}]+ (doseq [source [:native :query :query_handle]]+ (testing (name source)+ (testing "is refused, naming the denied tool, and nothing is written"+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly [{"execute_sql" "no"}])]+ (let [sid (str (random-uuid))+ result (call-tool scopes sid "question_write"+ (native-source-args! source sid "Denied Native Q"))]+ (is (:isError result))+ (is (re-find #"^Saving a native \(SQL\) query needs the \"execute_sql\" tool, which is not enabled"+ (-> result :content first :text)))+ (is (zero? (t2/count :model/Card :name "Denied Native Q"))))))+ (testing "goes through once the groups allow execute_sql"+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly [{"execute_sql" "yes"}])]+ (let [sid (str (random-uuid))+ result (call-tool scopes sid "question_write"+ (native-source-args! source sid "Allowed Native Q"))]+ (is (not (:isError result)) (-> result :content first :text))+ (is (=? {:stages [{:lib/type :mbql.stage/native :native "SELECT 1"}]}+ (t2/select-one-fn :dataset_query :model/Card :id (:id (payload result))))))))))+ (testing "an MBQL question is unaffected by the execute_sql denial"+ (mt/with-dynamic-fn-redefs [mcp.perms/effective-policy (constantly [{"execute_sql" "no"}])]+ (let [result (call-tool scopes (str (random-uuid)) "question_write"+ {:method "create" :name "Plain MBQL Q"+ :query {:database (mt/id) :stages [{:source-table (mt/id :orders)}]}})]+ (is (not (:isError result)) (-> result :content first :text))))))))))+(deftest write-response-respects-read-scope-test(testing "GHY-4217: without agent:resource:read the response is a minimal ack — the write scopemust not double as a read scope"