Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Metabot AI Controls (#71387)

Anderson672bd07e35ed
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.edn
index 01b4e0ec7f4..5161d27a9db 100644
--- a/.clj-kondo/config.edn
+++ b/.clj-kondo/config.edn
@@ -479,6 +479,7 @@
metabase.query-processor.setup/with-qp-setup clojure.core/let
metabase.search.api-test/do-test-users clojure.core/let
metabase.settings.core/define-multi-setting clojure.core/def
+ metabase.api-scope.core/defscope clj-kondo.lint-as/def-catch-all
metabase.settings.core/defsetting clj-kondo.lint-as/def-catch-all
metabase.settings.models.setting.multi-setting/define-multi-setting clojure.core/def
metabase.settings.models.setting/defsetting clj-kondo.lint-as/def-catch-all
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 63c8b80850e..3b678332446 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -241,7 +241,8 @@
metabase.api.settings
metabase.api.util
metabase.api.util.handlers}
- :uses #{config
+ :uses #{api-scope
+ config
events
models
settings
@@ -289,6 +290,11 @@
metabase.api-routes.core}
:uses :any}
+ api-scope
+ {:team "Metabot"
+ :api #{metabase.api-scope.core
+ metabase.api-scope.init}}
+
app-db
{:team "UX West"
:api #{metabase.app-db.cluster-lock ; TODO FIXME
@@ -1144,6 +1150,7 @@
metabase.mcp.init}
:uses #{agent-api
api
+ api-scope
config
oauth-server
request
@@ -1179,6 +1186,7 @@
:uses #{activity-feed
analytics
api
+ api-scope
app-db
audit-app
channel
@@ -2951,7 +2959,7 @@
enterprise/metabot
{:team "Metabot"
- :api #{}
+ :api #{metabase-enterprise.metabot.api.routes}
:friends #{enterprise/agent-api
slackbot
mcp
@@ -2964,7 +2972,10 @@
util
enterprise/dependencies
enterprise/transforms-python}
- :model-imports #{:model/Card :model/Transform}}
+ :model-imports #{:model/Card
+ :model/PermissionsGroup
+ :model/PermissionsGroupMembership
+ :model/Transform}}
enterprise/permission-debug
{:team "UX West"
@@ -3292,6 +3303,7 @@
:model-exports #{:model/Workspace :model/WorkspaceMergeTransform}
:friends #{enterprise/agent-api}
:uses #{api
+ api-scope
app-db
config
database-routing
diff --git a/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts b/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts
new file mode 100644
index 00000000000..57112e2b5a1
--- /dev/null
+++ b/e2e/test/scenarios/metabot/ai-controls.cy.spec.ts
@@ -0,0 +1,298 @@
+import { ALL_USERS_GROUP_ID } from "e2e/support/cypress_sample_instance_data";
+
+const { H } = cy;
+
+// A tiny valid PNG (1×1 transparent pixel) as a data URI, used for icon upload tests
+const TINY_PNG_DATA_URI =
+ "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
+
+describe("AI Controls > Metabot access and customization", () => {
+ beforeEach(() => {
+ H.restore();
+ cy.signInAsAdmin();
+ H.activateToken("bleeding-edge");
+ H.updateSetting("llm-anthropic-api-key", "sk-ant-test-key");
+ });
+
+ describe("Feature Access page", () => {
+ it("should display the AI feature access table with groups and save a permission change", () => {
+ cy.intercept("GET", "/api/ee/ai-controls/permissions").as(
+ "getPermissions",
+ );
+ cy.intercept("PUT", "/api/ee/ai-controls/permissions").as(
+ "updatePermissions",
+ );
+
+ cy.visit("/admin/metabot/1/usage-controls/ai-feature-access");
+
+ cy.wait("@getPermissions");
+
+ cy.findByTestId("ai-feature-access-table").should("be.visible");
+
+ // Verify column headers
+ cy.findByTestId("ai-feature-access-table").within(() => {
+ cy.findByText("AI features").should("be.visible");
+ cy.findByText("Chat and NLQ").should("be.visible");
+ cy.findByText("SQL generation").should("be.visible");
+ cy.findByText("Other tools").should("be.visible");
+ });
+
+ // Admins row should be locked/checked
+ cy.findByRole("row", { name: /Administrators permissions/ }).within(
+ () => {
+ cy.findByRole("switch").should("be.checked").and("be.disabled");
+ },
+ );
+
+ // All Users row should have the metabot switch checked (default is yes)
+ cy.findByRole("row", { name: /All Users permissions/ }).within(() => {
+ // Toggle the metabot AI features switch off
+ cy.findByRole("switch").should("be.checked").click({ force: true });
+ });
+
+ // Wait for the debounced PUT request to complete
+ cy.wait("@updatePermissions")
+ .its("response.statusCode")
+ .should("eq", 200);
+
+ // Verify sub-permission checkboxes are now disabled after disabling metabot
+ cy.findByRole("row", { name: /All Users permissions/ }).within(() => {
+ cy.findByRole("switch").should("not.be.checked");
+ cy.findAllByRole("checkbox").each(($checkbox) => {
+ cy.wrap($checkbox).should("be.disabled");
+ });
+ });
+ });
+ });
+
+ describe("Group access controls", () => {
+ it("should not show the Metabot chat icon for users in a group without Metabot access", () => {
+ // First, get the current permissions so we can update only the All Users group
+ cy.request("GET", "/api/ee/ai-controls/permissions").then((response) => {
+ const currentPermissions: Array<{
+ group_id: number;
+ perm_type: string;
+ perm_value: string;
+ }> = response.body.permissions;
+
+ // Set All Users group's metabot permission to "no"
+ const updatedPermissions = currentPermissions.map((p) => {
+ if (
+ p.group_id === ALL_USERS_GROUP_ID &&
+ p.perm_type === "permission/metabot"
+ ) {
+ return { ...p, perm_value: "no" };
+ }
+ return p;
+ });
+
+ cy.request("PUT", "/api/ee/ai-controls/permissions", {
+ permissions: updatedPermissions,
+ });
+ });
+
+ // Sign in as a normal user (who is only in the All Users group)
+ cy.signInAsNormalUser();
+ cy.visit("/");
+
+ // Wait for the navigation bar to be present
+ cy.findByLabelText("Navigation bar").should("be.visible");
+
+ // The Metabot chat icon should not be present
+ H.appBar().find('[aria-label*="Chat with"]').should("not.exist");
+ });
+ });
+
+ describe("Customization", () => {
+ it("should save a custom Metabot name", () => {
+ cy.intercept("PUT", "/api/setting/metabot-name").as("saveName");
+
+ cy.visit("/admin/metabot/1/customization");
+
+ cy.findByRole("heading", { name: "Customization", level: 1 }).should(
+ "be.visible",
+ );
+ cy.findByLabelText("Metabot's name")
+ .should("be.visible")
+ .clear()
+ .type("HAL 9000");
+
+ // Wait for debounced save
+ cy.wait("@saveName").its("response.statusCode").should("eq", 204);
+
+ // Reload and verify persistence
+ cy.reload();
+ cy.findByLabelText("Metabot's name").should("have.value", "HAL 9000");
+ });
+
+ it("should upload a custom Metabot icon and show the illustrations section", () => {
+ cy.intercept("PUT", "/api/setting/metabot-icon").as("saveIcon");
+
+ cy.visit("/admin/metabot/1/customization");
+
+ H.main().findByText("Metabot's icon").should("be.visible");
+ cy.findByRole("button", { name: "Upload a custom icon" }).should(
+ "be.visible",
+ );
+
+ // The illustrations section is hidden until a custom icon is set
+ H.main().findByText("Metabot illustrations").should("not.exist");
+
+ // Upload a tiny PNG via the hidden file input
+ cy.get('input[type="file"]').selectFile(
+ {
+ contents: Cypress.Buffer.from(
+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
+ "base64",
+ ),
+ fileName: "metabot-icon.png",
+ mimeType: "image/png",
+ },
+ { force: true },
+ );
+
+ cy.wait("@saveIcon").its("response.statusCode").should("eq", 204);
+
+ // The illustrations section should now appear
+ H.main().findByText("Metabot illustrations").should("be.visible");
+ cy.findByRole("switch", { name: /Show Metabot illustrations/ })
+ .parent()
+ .should("be.visible");
+
+ // The "Remove custom icon" button should be visible
+ cy.findByLabelText("Remove custom icon").should("be.visible");
+ });
+
+ it("should hide Metabot illustrations when the toggle is switched off", () => {
+ // Set a custom icon via API so the illustrations toggle is visible
+ H.updateEnterpriseSettings({
+ "metabot-icon": TINY_PNG_DATA_URI,
+ "metabot-show-illustrations": true,
+ });
+ H.updateSetting("metabot-enabled?", true);
+
+ cy.intercept("PUT", "/api/setting/metabot-show-illustrations").as(
+ "saveIllustrations",
+ );
+
+ cy.visit("/admin/metabot/1/customization");
+
+ H.main().findByText("Metabot illustrations").should("be.visible");
+
+ // The switch should be ON
+ cy.findByRole("switch", { name: "Show Metabot illustrations" }).should(
+ "have.attr",
+ "data-checked",
+ "true",
+ );
+
+ // Toggle illustrations off
+ cy.findByRole("switch", {
+ name: "Show Metabot illustrations",
+ }).click({ force: true });
+
+ cy.wait("@saveIllustrations")
+ .its("response.statusCode")
+ .should("eq", 204);
+
+ // Navigate to the home page and open Metabot chat to verify illustrations are hidden
+ cy.visit("/");
+ // Can't use H.openMetabotViaSearchButton() because custom icon replaces .Icon-metabot
+ H.appBar()
+ .findByRole("button", { name: /Chat with/ })
+ .click();
+
+ cy.findByTestId("metabot-empty-chat-info").should("be.visible");
+ // The SVG illustration should NOT be rendered when showIllustrations=false
+ cy.findByTestId("metabot-empty-chat-info")
+ .find("svg")
+ .should("not.exist");
+ // But the hint text should still be visible
+ cy.findByTestId("metabot-empty-chat-info")
+ .findByText(/I can help you/)
+ .should("be.visible");
+ });
+
+ it("should show the custom Metabot name in the app bar button tooltip", () => {
+ H.updateSetting("metabot-name", "Aria");
+
+ cy.visit("/");
+ cy.findByLabelText("Navigation bar").should("be.visible");
+
+ // The app bar button tooltip/aria-label should reflect the custom name
+ H.appBar()
+ .findByRole("button", { name: /Chat with Aria/ })
+ .should("be.visible");
+ });
+
+ it("should show a custom Metabot icon in the app bar when metabot-icon is set", () => {
+ H.updateEnterpriseSettings({ "metabot-icon": TINY_PNG_DATA_URI });
+
+ cy.visit("/");
+ cy.findByLabelText("Navigation bar").should("be.visible");
+
+ // The custom icon img should be rendered (alt = metabot name)
+ H.appBar()
+ .findByRole("button", { name: /Chat with/ })
+ .within(() => {
+ // When a custom icon is set, MetabotIcon renders an <img> with alt = metabotName
+ cy.get("img").should("be.visible");
+ });
+ });
+ });
+
+ describe("System Prompts pages", () => {
+ it("should save a custom Metabot chat system prompt", () => {
+ cy.intercept("PUT", "/api/setting/metabot-chat-system-prompt").as(
+ "savePrompt",
+ );
+
+ cy.visit("/admin/metabot/1/system-prompts/metabot-chat");
+
+ cy.findByRole("heading", {
+ name: "Metabot chat prompt instructions",
+ level: 1,
+ }).should("be.visible");
+
+ cy.findByRole("textbox", { name: /Metabot chat prompt instructions/ })
+ .should("be.visible")
+ .click()
+ .type("Be concise and helpful.");
+
+ cy.wait("@savePrompt").its("response.statusCode").should("eq", 204);
+
+ // Reload and verify persistence
+ cy.reload();
+ cy.findByRole("textbox", {
+ name: /Metabot chat prompt instructions/,
+ }).should("contain.value", "Be concise and helpful.");
+ });
+
+ it("should save a custom SQL generation system prompt", () => {
+ cy.intercept("PUT", "/api/setting/metabot-sql-system-prompt").as(
+ "saveSqlPrompt",
+ );
+
+ cy.visit("/admin/metabot/1/system-prompts/sql-generation");
+
+ cy.findByRole("heading", {
+ name: "SQL generation prompt instructions",
+ level: 1,
+ }).should("be.visible");
+
+ cy.findByRole("textbox", {
+ name: /SQL generation prompt instructions/,
+ })
+ .should("be.visible")
+ .click()
+ .type("Always use uppercase SQL keywords.");
+
+ cy.wait("@saveSqlPrompt").its("response.statusCode").should("eq", 204);
+
+ cy.reload();
+ cy.findByRole("textbox", {
+ name: /SQL generation prompt instructions/,
+ }).should("contain.value", "Always use uppercase SQL keywords.");
+ });
+ });
+});
diff --git a/enterprise/backend/src/metabase_enterprise/agent_api/workspace.clj b/enterprise/backend/src/metabase_enterprise/agent_api/workspace.clj
index 8c830967861..9f43deebe6a 100644
--- a/enterprise/backend/src/metabase_enterprise/agent_api/workspace.clj
+++ b/enterprise/backend/src/metabase_enterprise/agent_api/workspace.clj
@@ -3,6 +3,7 @@
Provides workspace access with JWT-based agent authentication."
(:require
[metabase-enterprise.workspaces.api.common :as ws.api.common]
+ [metabase-enterprise.workspaces.core :as ws.core]
[metabase-enterprise.workspaces.types :as ws.t]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
@@ -130,7 +131,7 @@
(api.macros/defendpoint :get "/:ws-id" :- Workspace
"Get a single workspace by ID."
- {:scope "agent:workspace:read"}
+ {:scope ws.core/agent-workspace-read}
[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]
_query-params]
(ws.api.common/get-workspace ws-id))
@@ -140,7 +141,7 @@
[:inputs [:sequential InputTable]]
[:outputs [:sequential OutputTable]]]
"Get workspace input and output tables."
- {:scope "agent:workspace:read"}
+ {:scope ws.core/agent-workspace-read}
[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]
_query-params]
(ws.api.common/get-workspace-tables ws-id))
@@ -161,28 +162,28 @@
[:status [:maybe :keyword]]
[:message [:maybe :string]]]]]]
"Get workspace creation status and recent log entries."
- {:scope "agent:workspace:read"}
+ {:scope ws.core/agent-workspace-read}
[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]
_query-params]
(ws.api.common/get-workspace-log ws-id))
(api.macros/defendpoint :get "/:ws-id/graph" :- GraphResult
"Get the dependency graph for a workspace."
- {:scope "agent:workspace:read"}
+ {:scope ws.core/agent-workspace-read}
[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]
_query-params]
(ws.api.common/get-workspace-graph ws-id))
(api.macros/defendpoint :get "/:ws-id/problem" :- [:sequential ::ws.t/problem]
"Detect problems in the workspace."
- {:scope "agent:workspace:read"}
+ {:scope ws.core/agent-workspace-read}
[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]
_query-params]
(ws.api.common/get-workspace-problems ws-id))
(api.macros/defendpoint :get "/:ws-id/external/transform" :- [:map [:transforms [:sequential ExternalTransform]]]
"List external transforms not checked out into this workspace."
- {:scope "agent:workspace:read"}
+ {:scope ws.core/agent-workspace-read}
[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]
{:keys [database-id]} :- [:map [:database-id {:optional true} ::ws.t/appdb-id]]]
(ws.api.common/get-external-transforms ws-id database-id))
@@ -190,7 +191,7 @@
(api.macros/defendpoint :get "/:ws-id/input/pending"
:- [:map [:inputs [:sequential PendingInput]]]
"List pending input grants."
- {:scope "agent:workspace:read"}
+ {:scope ws.core/agent-workspace-read}
[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]]
(ws.api.common/get-pending-inputs ws-id))
@@ -198,19 +199,19 @@
(api.macros/defendpoint :get "/:ws-id/transform" :- [:map [:transforms [:sequential WorkspaceTransformListing]]]
"List all transforms in a workspace."
- {:scope "agent:workspace:read"}
+ {:scope ws.core/agent-workspace-read}
[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]]
(ws.api.common/list-transforms ws-id))
(api.macros/defendpoint :get "/:ws-id/transform/:tx-id" :- WorkspaceTransform
"Get a specific transform in a workspace."
- {:scope "agent:workspace:read"}
+ {:scope ws.core/agent-workspace-read}
[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]
(ws.api.common/fetch-ws-transform ws-id tx-id))
(api.macros/defendpoint :post "/:ws-id/archive" :- Workspace
"Archive a workspace."
- {:scope "agent:workspace:write"}
+ {:scope ws.core/agent-workspace-write}
[{:keys [ws-id]} :- [:map [:ws-id ms/PositiveInt]]
_query-params
_body-params]
@@ -219,7 +220,7 @@
(api.macros/defendpoint :post "/:ws-id/transform"
:- WorkspaceTransform
"Create a new transform in the workspace."
- {:scope "agent:workspace:write"}
+ {:scope ws.core/agent-workspace-write}
[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]
_query-params
body :- [:map #_{:closed true}
@@ -231,20 +232,20 @@
(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/archive" :- :nil
"Mark a transform for archival."
- {:scope "agent:workspace:write"}
+ {:scope ws.core/agent-workspace-write}
[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]
(ws.api.common/archive-transform! ws-id tx-id))
(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/unarchive" :- :nil
"Unmark a transform for archival."
- {:scope "agent:workspace:write"}
+ {:scope ws.core/agent-workspace-write}
[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]
(ws.api.common/unarchive-transform! ws-id tx-id))
(api.macros/defendpoint :post "/:ws-id/transform/validate/target"
:- [:map [:status :int] [:body [:or :string i18n/LocalizedString]]]
"Validate the target table for a workspace transform."
- {:scope "agent:workspace:write"}
+ {:scope ws.core/agent-workspace-write}
[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]
{:keys [transform-id]} :- [:map [:transform-id {:optional true} ::ws.t/ref-id]]
{:keys [db_id target]} :- [:map
@@ -264,7 +265,7 @@
[:failed [:sequential ::ws.t/ref-id]]
[:not_run [:sequential ::ws.t/ref-id]]]
"Execute all transforms in the workspace in dependency order."
- {:scope "agent:workspace:execute"}
+ {:scope ws.core/agent-workspace-execute}
[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]
_query-params
{:keys [stale_only]} :- [:map [:stale_only {:optional true} ::ws.t/flag]]]
@@ -273,7 +274,7 @@
(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/run"
:- ::ws.t/execution-result
"Run a single transform in a workspace."
- {:scope "agent:workspace:execute"}
+ {:scope ws.core/agent-workspace-execute}
[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]
_query-params
{:keys [run_stale_ancestors]} :- [:map [:run_stale_ancestors {:optional true} ::ws.t/flag]]]
@@ -282,7 +283,7 @@
(api.macros/defendpoint :post "/:ws-id/transform/:tx-id/dry-run"
:- ::ws.t/query-result
"Dry-run a transform without persisting to the target table."
- {:scope "agent:workspace:execute"}
+ {:scope ws.core/agent-workspace-execute}
[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]
_query-params
{:keys [run_stale_ancestors]} :- [:map [:run_stale_ancestors {:optional true} ::ws.t/flag]]]
@@ -291,7 +292,7 @@
(api.macros/defendpoint :post "/:ws-id/query"
:- ::ws.t/query-result
"Execute a SQL query in the workspace's isolated database context."
- {:scope "agent:workspace:execute"}
+ {:scope ws.core/agent-workspace-execute}
[{:keys [ws-id]} :- [:map [:ws-id ::ws.t/appdb-id]]
_query-params
{:keys [sql]} :- [:map [:sql [:string {:min 1}]]]]
@@ -301,7 +302,7 @@
(api.macros/defendpoint :put "/:ws-id/transform/:tx-id" :- WorkspaceTransform
"Update or create a transform in a workspace."
- {:scope "agent:workspace:write"}
+ {:scope ws.core/agent-workspace-write}
[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]
_query-params
body :- [:map
@@ -313,7 +314,7 @@
(api.macros/defendpoint :delete "/:ws-id/transform/:tx-id" :- :nil
"Delete a transform from the workspace."
- {:scope "agent:workspace:write"}
+ {:scope ws.core/agent-workspace-write}
[{:keys [ws-id tx-id]} :- [:map [:ws-id ::ws.t/appdb-id] [:tx-id ::ws.t/ref-id]]]
(ws.api.common/delete-transform! ws-id tx-id))
diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
index cb172f55607..2f5f897ad12 100644
--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
@@ -24,6 +24,7 @@
[metabase-enterprise.embedding-hub.api]
[metabase-enterprise.gsheets.api :as gsheets.api]
[metabase-enterprise.library.api]
+ [metabase-enterprise.metabot.api.routes]
[metabase-enterprise.permission-debug.api]
[metabase-enterprise.remote-sync.api]
[metabase-enterprise.replacement.api]
@@ -47,6 +48,7 @@
(def ^:private required-feature->message
{:advanced-permissions (deferred-tru "Advanced Permissions")
+ :ai-controls (deferred-tru "AI Controls")
:attached-dwh (deferred-tru "Attached DWH")
:audit-app (deferred-tru "Audit app")
:collection-cleanup (deferred-tru "Collection Cleanup")
@@ -91,6 +93,7 @@
;; 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)
"/audit-app" (premium-handler metabase-enterprise.audit-app.api.routes/routes :audit-app)
"/billing" metabase-enterprise.billing.api.routes/routes
"/content-translation" (premium-handler metabase-enterprise.content-translation.routes/routes :content-translation)
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/api/permissions.clj b/enterprise/backend/src/metabase_enterprise/metabot/api/permissions.clj
new file mode 100644
index 00000000000..d6e4997bb16
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/api/permissions.clj
@@ -0,0 +1,78 @@
+(ns metabase-enterprise.metabot.api.permissions
+ "`/api/ee/ai-controls/permissions` routes for managing metabot permissions per group."
+ (:require
+ [metabase-enterprise.metabot.models.metabot-permissions :as metabot-perms]
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]
+ [metabase.metabot.scope :as scope]
+ [toucan2.core :as t2]))
+
+(def ^:private perm-type-enum
+ "Malli enum of valid perm_type keywords."
+ (into [:enum] scope/perm-types))
+
+(def ^:private perm-value-enum
+ "Malli enum of valid perm_value keywords."
+ (into [:enum] (distinct (mapcat (comp :values val) scope/metabot-permissions))))
+
+(def ^:private permissions-response-schema
+ [:map [:permissions [:sequential [:map
+ [:group_id pos-int?]
+ [:perm_type perm-type-enum]
+ [:perm_value perm-value-enum]]]]])
+
+(api.macros/defendpoint :get "/" :- permissions-response-schema
+ "List all metabot permissions for all groups, filling in defaults for missing entries."
+ []
+ (api/check-superuser)
+ (metabot-perms/all-permissions))
+
+(def ^:private valid-perm-types
+ "Set of valid perm_type strings for the PUT request body."
+ (into #{} (map (comp str symbol)) scope/perm-types))
+
+(def ^:private valid-perm-values-by-type
+ "Map of perm_type string → set of valid perm_value strings for that type."
+ (into {} (map (fn [[perm-type {:keys [values]}]]
+ [(-> perm-type symbol str) (into #{} (map name) values)]))
+ scope/metabot-permissions))
+
+(defn- valid-perm-value?
+ "Returns true if `perm_value` is valid for the given `perm_type`."
+ [{:keys [perm_type perm_value]}]
+ (contains? (get valid-perm-values-by-type perm_type) perm_value))
+
+(def ^:private all-valid-perm-values
+ "Flat set of all valid perm_value strings (for schema-level validation)."
+ (into #{} (mapcat val) valid-perm-values-by-type))
+
+(api.macros/defendpoint :put "/" :- permissions-response-schema
+ "Update metabot permissions for all groups. Upserts each permission entry and returns the full
+ permissions list with defaults filled in."
+ [_route-params
+ _query-params
+ {:keys [permissions]} :- [:map
+ [:permissions [:sequential [:map
+ [:group_id pos-int?]
+ [:perm_type (into [:enum] valid-perm-types)]
+ [:perm_value (into [:enum] all-valid-perm-values)]]]]]]
+ (api/check-superuser)
+ (doseq [perm permissions]
+ (when-not (valid-perm-value? perm)
+ (throw (ex-info (format "Invalid perm_value %s for perm_type %s" (:perm_value perm) (:perm_type perm))
+ {:status-code 400}))))
+ (t2/with-transaction [_conn]
+ (doseq [{:keys [group_id perm_type perm_value]} permissions]
+ (let [perm-type-kw (keyword perm_type)
+ perm-value-kw (keyword perm_value)]
+ (if (t2/exists? :model/MetabotPermissions :group_id group_id :perm_type perm-type-kw)
+ (t2/update! :model/MetabotPermissions {:group_id group_id :perm_type perm-type-kw} {:perm_value perm-value-kw})
+ (t2/insert! :model/MetabotPermissions {:group_id group_id
+ :perm_type perm-type-kw
+ :perm_value perm-value-kw})))))
+ (metabot-perms/all-permissions))
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/ai-controls/permissions` routes."
+ (api.macros/ns-handler *ns* +auth))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/api/routes.clj b/enterprise/backend/src/metabase_enterprise/metabot/api/routes.clj
new file mode 100644
index 00000000000..50c232f6f82
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/api/routes.clj
@@ -0,0 +1,10 @@
+(ns metabase-enterprise.metabot.api.routes
+ "Routes for enterprise metabot API endpoints."
+ (:require
+ [metabase-enterprise.metabot.api.permissions]
+ [metabase.api.util.handlers :as handlers]))
+
+(def ^{:arglists '([request respond raise])} routes
+ "Ring routes for enterprise metabot API endpoints."
+ (handlers/route-map-handler
+ {"/permissions" metabase-enterprise.metabot.api.permissions/routes}))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_permissions.clj b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_permissions.clj
new file mode 100644
index 00000000000..1e22635126e
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/models/metabot_permissions.clj
@@ -0,0 +1,37 @@
+(ns metabase-enterprise.metabot.models.metabot-permissions
+ "Toucan2 model registration and DB helpers for `:model/MetabotPermissions`."
+ (:require
+ [metabase.metabot.scope :as scope]
+ [metabase.models.interface :as mi]
+ [methodical.core :as methodical]
+ [toucan2.core :as t2]))
+
+(methodical/defmethod t2/table-name :model/MetabotPermissions [_model] :metabot_permissions)
+
+(doto :model/MetabotPermissions
+ (derive :metabase/model)
+ (derive ::mi/write-policy.superuser))
+
+(t2/deftransforms :model/MetabotPermissions
+ {:perm_type mi/transform-keyword
+ :perm_value mi/transform-keyword})
+
+(defn permissions-for-group
+ "Returns the full set of permissions for a group, filling in defaults for any missing perm types."
+ [group-id stored-perms]
+ (let [stored-by-type (into {} (map (juxt :perm_type identity)) stored-perms)]
+ (for [[perm-type default-value] (sort-by key scope/perm-type-defaults)]
+ (or (get stored-by-type perm-type)
+ {:group_id group-id
+ :perm_type perm-type
+ :perm_value default-value}))))
+
+(defn all-permissions
+ "Returns all metabot permissions for all groups, filling in defaults for missing entries."
+ []
+ (let [groups (t2/select :model/PermissionsGroup {:order-by [[:id :asc]]})
+ stored (t2/select :model/MetabotPermissions {:order-by [[:group_id :asc] [:perm_type :asc]]})
+ by-group (group-by :group_id stored)]
+ {:permissions (vec (mapcat (fn [{:keys [id]}]
+ (permissions-for-group id (get by-group id [])))
+ groups))}))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj b/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj
new file mode 100644
index 00000000000..016b89bca88
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot/permissions.clj
@@ -0,0 +1,32 @@
+(ns metabase-enterprise.metabot.permissions
+ "Enterprise implementation of metabot permission resolution.
+ Resolves per-group permissions from the database, taking the most permissive
+ value across all of a user's groups."
+ (:require
+ [metabase.metabot.scope :as scope]
+ [metabase.premium-features.core :refer [defenterprise]]
+ [toucan2.core :as t2]))
+
+(defenterprise resolve-user-permissions
+ "Resolve the effective metabot permissions for a user by taking the most
+ permissive value across all their groups. Returns a map of perm-type → value,
+ with defaults filled in for any unset permission types."
+ :feature :ai-controls
+ [user-id]
+ (if-not user-id
+ scope/all-yes-permissions
+ (let [stored (t2/select :model/MetabotPermissions
+ {:where [:in :group_id
+ {:select [:group_id]
+ :from [(t2/table-name :model/PermissionsGroupMembership)]
+ :where [:= :user_id user-id]}]})
+ by-type (group-by :perm_type stored)]
+ (reduce-kv
+ (fn [acc perm-type default-value]
+ (let [values (map :perm_value (get by-type perm-type))]
+ (assoc acc perm-type
+ (if (seq values)
+ (scope/most-permissive-value perm-type values)
+ default-value))))
+ {}
+ scope/perm-type-defaults))))
diff --git a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
index b2a2b0facd7..0871f061492 100644
--- a/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
+++ b/enterprise/backend/src/metabase_enterprise/serialization/v2/models.clj
@@ -84,6 +84,7 @@
"LoginHistory"
"MetabotConversation"
"MetabotMessage"
+ "MetabotPermissions"
"ModelIndex"
"ModelIndexValue"
"ModerationReview"
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/core.clj b/enterprise/backend/src/metabase_enterprise/workspaces/core.clj
index 9346331b947..3e3ddfb5b6f 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/core.clj
@@ -1,2 +1,11 @@
-;; For now, we do not anticipate any non-API usage of this module.
-(ns metabase-enterprise.workspaces.core)
+(ns metabase-enterprise.workspaces.core
+ "API namespace for the `enterprise/workspaces` module."
+ (:require
+ [metabase-enterprise.workspaces.scope]
+ [potemkin :as p]))
+
+(p/import-vars
+ [metabase-enterprise.workspaces.scope
+ agent-workspace-execute
+ agent-workspace-read
+ agent-workspace-write])
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/init.clj b/enterprise/backend/src/metabase_enterprise/workspaces/init.clj
index 04f7482afd3..8df0afcb37b 100644
--- a/enterprise/backend/src/metabase_enterprise/workspaces/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/init.clj
@@ -6,4 +6,5 @@
[metabase-enterprise.workspaces.models.workspace]
[metabase-enterprise.workspaces.models.workspace-graph]
[metabase-enterprise.workspaces.models.workspace-transform]
+ [metabase-enterprise.workspaces.scope]
[metabase-enterprise.workspaces.settings]))
diff --git a/enterprise/backend/src/metabase_enterprise/workspaces/scope.clj b/enterprise/backend/src/metabase_enterprise/workspaces/scope.clj
new file mode 100644
index 00000000000..5db6bf96dfa
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/workspaces/scope.clj
@@ -0,0 +1,14 @@
+(ns metabase-enterprise.workspaces.scope
+ "Scope declarations for the workspaces module."
+ (:require
+ [metabase.api-scope.core :as api-scope]
+ [metabase.util.i18n :refer [deferred-tru]]))
+
+(api-scope/defscope agent-workspace-read "agent:workspace:read"
+ (deferred-tru "Read workspace data"))
+
+(api-scope/defscope agent-workspace-write "agent:workspace:write"
+ (deferred-tru "Write workspace data"))
+
+(api-scope/defscope agent-workspace-execute "agent:workspace:execute"
+ (deferred-tru "Execute workspace queries"))
diff --git a/enterprise/backend/test/metabase_enterprise/agent_api/api_test.clj b/enterprise/backend/test/metabase_enterprise/agent_api/api_test.clj
index eb984a879e0..829fe704dab 100644
--- a/enterprise/backend/test/metabase_enterprise/agent_api/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/agent_api/api_test.clj
@@ -179,7 +179,7 @@
(let [headers {"authorization" (str "Bearer " (sign-jwt {:email "[email protected]"
:scope "agent:search"}))}]
(is (= {:error "unsupported_scope"
- :message "Token does not have required scope: agent:table:read"}
+ :message "Insufficient scope for this operation."}
(client/client :get 403 (str "agent/v1/table/" table-id)
{:request-options {:headers headers}})))))
@@ -194,7 +194,7 @@
(let [headers {"authorization" (str "Bearer " (sign-jwt {:email "[email protected]"
:scope ""}))}]
(is (= {:error "unsupported_scope"
- :message "Token does not have required scope: agent:table:read"}
+ :message "Insufficient scope for this operation."}
(client/client :get 403 (str "agent/v1/table/" table-id)
{:request-options {:headers headers}}))))))))
@@ -220,7 +220,7 @@
(let [headers {"authorization" (str "Bearer " (sign-jwt {:email "[email protected]"
:scope "agent:query:construct"}))}]
(is (= {:error "unsupported_scope"
- :message "Token does not have required scope: agent:query"}
+ :message "Insufficient scope for this operation."}
(client/client :post 403 "agent/v1/query"
{:request-options {:headers headers}}
{:table_id (mt/id :orders) :limit 1})))))))
diff --git a/enterprise/backend/test/metabase_enterprise/agent_api/workspace_test.clj b/enterprise/backend/test/metabase_enterprise/agent_api/workspace_test.clj
index 16c1bae4cf5..ea1e0fea8c7 100644
--- a/enterprise/backend/test/metabase_enterprise/agent_api/workspace_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/agent_api/workspace_test.clj
@@ -226,21 +226,21 @@
(client/client :get 200 (str "agent/v1/workspace/" ws-id)
{:request-options {:headers headers}})))
(is (= {:error "unsupported_scope"
- :message "Token does not have required scope: agent:workspace:write"}
+ :message "Insufficient scope for this operation."}
(client/client :post 403 (str "agent/v1/workspace/" ws-id "/archive")
{:request-options {:headers headers}})))))
(testing "write scope can POST archive but not run"
(let [headers (scoped-auth-headers "agent:workspace:write")]
(is (= {:error "unsupported_scope"
- :message "Token does not have required scope: agent:workspace:execute"}
+ :message "Insufficient scope for this operation."}
(client/client :post 403 (str "agent/v1/workspace/" ws-id "/run")
{:request-options {:headers headers}})))))
(testing "execute scope can POST run but not GET workspace"
(let [headers (scoped-auth-headers "agent:workspace:execute")]
(is (= {:error "unsupported_scope"
- :message "Token does not have required scope: agent:workspace:read"}
+ :message "Insufficient scope for this operation."}
(client/client :get 403 (str "agent/v1/workspace/" ws-id)
{:request-options {:headers headers}})))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/api/session_test.clj b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
index 81f85ccb46c..1ba684a4f43 100644
--- a/enterprise/backend/test/metabase_enterprise/api/session_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/api/session_test.clj
@@ -9,6 +9,7 @@
(deftest properties-token-features-test
(mt/with-premium-features #{:advanced-permissions
+ :ai-controls
:attached-dwh
:audit-app
:cache-granular-controls
@@ -55,6 +56,7 @@
:workspaces
:writable-connection}
(is (= {:advanced_permissions true
+ :ai_controls true
:attached_dwh true
:audit_app true
:cache_granular_controls true
diff --git a/enterprise/backend/test/metabase_enterprise/metabot/api/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/api/permissions_test.clj
new file mode 100644
index 00000000000..2fa5c86167d
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/metabot/api/permissions_test.clj
@@ -0,0 +1,94 @@
+(ns metabase-enterprise.metabot.api.permissions-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
+
+(def ^:private all-perm-types
+ #{"permission/metabot"
+ "permission/metabot-sql-generation"
+ "permission/metabot-nlq"
+ "permission/metabot-other-tools"})
+
+(deftest ^:parallel list-permissions-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "GET /api/ee/ai-controls/permissions"
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "ee/ai-controls/permissions"))))
+ (testing "returns default permissions for all groups even with no rows in the table"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Test Group"}]
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/ai-controls/permissions")
+ perms (->> (:permissions response)
+ (filter #(= (:group_id %) group-id)))]
+ (is (= all-perm-types (set (map :perm_type perms))))
+ (is (every? #(= "no" (:perm_value %)) perms)))))
+ (testing "returns stored values when they exist, defaults for the rest"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Test Group"}
+ :model/MetabotPermissions _ {:group_id group-id
+ :perm_type :permission/metabot-sql-generation
+ :perm_value :yes}]
+ (let [response (mt/user-http-request :crowberto :get 200 "ee/ai-controls/permissions")
+ perms (->> (:permissions response)
+ (filter #(= (:group_id %) group-id)))
+ by-type (into {} (map (juxt :perm_type :perm_value)) perms)]
+ (is (= all-perm-types (set (map :perm_type perms))))
+ (is (= "yes" (get by-type "permission/metabot-sql-generation")))
+ (is (= "no" (get by-type "permission/metabot-nlq")))
+ (is (= "no" (get by-type "permission/metabot-other-tools")))))))))
+
+(deftest update-permissions-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "PUT /api/ee/ai-controls/permissions"
+ (testing "requires superuser"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 "ee/ai-controls/permissions"
+ {:permissions [{:group_id 1 :perm_type "permission/metabot-sql-generation" :perm_value "yes"}]}))))
+ (testing "upserts permissions across multiple groups"
+ (mt/with-temp [:model/PermissionsGroup {group-a :id} {:name "Group A"}
+ :model/PermissionsGroup {group-b :id} {:name "Group B"}
+ :model/MetabotPermissions _ {:group_id group-a
+ :perm_type :permission/metabot-sql-generation
+ :perm_value :no}]
+ (let [response (mt/user-http-request :crowberto :put 200 "ee/ai-controls/permissions"
+ {:permissions [{:group_id group-a :perm_type "permission/metabot-sql-generation" :perm_value "yes"}
+ {:group_id group-a :perm_type "permission/metabot-nlq" :perm_value "yes"}
+ {:group_id group-b :perm_type "permission/metabot-other-tools" :perm_value "yes"}]})
+ perms-a (->> (:permissions response)
+ (filter #(= (:group_id %) group-a)))
+ perms-b (->> (:permissions response)
+ (filter #(= (:group_id %) group-b)))
+ by-type (fn [perms] (into {} (map (juxt :perm_type :perm_value)) perms))]
+ (is (= "yes" (get (by-type perms-a) "permission/metabot-sql-generation")))
+ (is (= "yes" (get (by-type perms-a) "permission/metabot-nlq")))
+ (is (= "yes" (get (by-type perms-b) "permission/metabot-other-tools")))
+ (is (= 1 (t2/count :model/MetabotPermissions :group_id group-a
+ :perm_type :permission/metabot-sql-generation))))))
+ (testing "returns full permissions for all groups with defaults filled in"
+ (mt/with-temp [:model/PermissionsGroup {group-id :id} {:name "Test Group"}]
+ (let [response (mt/user-http-request :crowberto :put 200 "ee/ai-controls/permissions"
+ {:permissions [{:group_id group-id :perm_type "permission/metabot-nlq" :perm_value "yes"}]})
+ perms (->> (:permissions response)
+ (filter #(= (:group_id %) group-id)))]
+ (is (= all-perm-types (set (map :perm_type perms))))))))))
+
+(deftest ^:parallel user-permissions-with-custom-group-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "GET /api/metabot/permissions/user-permissions"
+ (testing "user in group with custom permissions gets those values"
+ (mt/with-temp [:model/PermissionsGroup {gid :id} {:name "Test Metabot Perms Group"}
+ :model/PermissionsGroupMembership _ {:group_id gid :user_id (mt/user->id :rasta)}
+ :model/MetabotPermissions _ {:group_id gid
+ :perm_type :permission/metabot-sql-generation
+ :perm_value :yes}]
+ (let [perms (:permissions (mt/user-http-request :rasta :get 200 "metabot/permissions/user-permissions"))]
+ (is (= "yes" (:metabot-sql-generation perms)))))))))
+
+(deftest ^:parallel admin-endpoints-require-ai-controls-feature-test
+ (testing "admin endpoints return 402 without :ai-controls feature"
+ (mt/with-premium-features #{}
+ (mt/assert-has-premium-feature-error "AI Controls"
+ (mt/user-http-request :crowberto :get 402 "ee/ai-controls/permissions"))
+ (mt/assert-has-premium-feature-error "AI Controls"
+ (mt/user-http-request :crowberto :put 402 "ee/ai-controls/permissions"
+ {:permissions []})))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot/permissions_test.clj b/enterprise/backend/test/metabase_enterprise/metabot/permissions_test.clj
new file mode 100644
index 00000000000..dd9a7e83d45
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/metabot/permissions_test.clj
@@ -0,0 +1,58 @@
+(ns metabase-enterprise.metabot.permissions-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.metabot.scope :as scope]
+ [metabase.test :as mt]))
+
+(deftest resolve-user-permissions-default-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "user with no stored permissions inherits from all-internal-users migration defaults"
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/PermissionsGroup {group-id :id} {:name "Test Group"}
+ :model/PermissionsGroupMembership _ {:user_id user-id
+ :group_id group-id}]
+ (let [perms (scope/resolve-user-permissions user-id)]
+ ;; all-internal-users magic group has yes from migration
+ (is (= :yes (:permission/metabot-sql-generation perms)))
+ (is (= :yes (:permission/metabot-nlq perms))))))))
+
+(deftest resolve-user-permissions-stored-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "user in group with stored permissions gets those values"
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/PermissionsGroup {group-id :id} {:name "SQL Group"}
+ :model/PermissionsGroupMembership _ {:user_id user-id
+ :group_id group-id}
+ :model/MetabotPermissions _ {:group_id group-id
+ :perm_type :permission/metabot-sql-generation
+ :perm_value :yes}]
+ (let [perms (scope/resolve-user-permissions user-id)]
+ (is (= :yes (:permission/metabot-sql-generation perms)))
+ ;; all-internal-users magic group has :yes for nql from migration
+ (is (= :yes (:permission/metabot-nlq perms))))))))
+
+(deftest resolve-user-permissions-most-permissive-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "most permissive wins across multiple groups"
+ (mt/with-temp [:model/User {user-id :id} {}
+ :model/PermissionsGroup {group-a :id} {:name "Group A"}
+ :model/PermissionsGroup {group-b :id} {:name "Group B"}
+ :model/PermissionsGroupMembership _ {:user_id user-id :group_id group-a}
+ :model/PermissionsGroupMembership _ {:user_id user-id :group_id group-b}
+ :model/MetabotPermissions _ {:group_id group-a
+ :perm_type :permission/metabot-sql-generation
+ :perm_value :no}
+ :model/MetabotPermissions _ {:group_id group-b
+ :perm_type :permission/metabot-sql-generation
+ :perm_value :yes}
+ :model/MetabotPermissions _ {:group_id group-a
+ :perm_type :permission/metabot-nlq
+ :perm_value :no}
+ :model/MetabotPermissions _ {:group_id group-b
+ :perm_type :permission/metabot-nlq
+ :perm_value :yes}]
+ (let [perms (scope/resolve-user-permissions user-id)]
+ (is (= :yes (:permission/metabot-sql-generation perms))
+ ":yes wins over :no for sql-generation")
+ (is (= :yes (:permission/metabot-nlq perms))
+ ":yes wins over :no for nql"))))))
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.clj
index a4dddc2eabb..a396ba04112 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
@@ -58,6 +58,7 @@
:model/FieldValues
:model/MetabotConversation
:model/MetabotMessage
+ :model/MetabotPermissions
:model/ModelIndex
:model/ModelIndexValue
:model/ModerationReview
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx
index 05723214432..9e313b499ce 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotQuestion.tsx
@@ -13,7 +13,10 @@ import { SdkQuestionDefaultView } from "embedding-sdk-bundle/components/private/
import { METABOT_SDK_EE_PLUGIN } from "embedding-sdk-bundle/components/public/MetabotQuestion/MetabotQuestion";
import { EnsureSingleInstance } from "embedding-sdk-shared/components/EnsureSingleInstance/EnsureSingleInstance";
import { useLocale } from "metabase/common/hooks/use-locale";
-import { useMetabotEnabledEmbeddingAware } from "metabase/metabot/hooks";
+import {
+ useMetabotEnabledEmbeddingAware,
+ useMetabotName,
+} from "metabase/metabot/hooks";
import { useMetabotReactions } from "metabase/metabot/hooks/use-metabot-reactions";
import { Stack } from "metabase/ui";
@@ -45,6 +48,7 @@ const MetabotQuestionInner = ({
targetCollection,
}: MetabotQuestionProps) => {
const isEmbeddedMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const metabotName = useMetabotName();
const { isLocaleLoading } = useLocale();
const { navigateToPath } = useMetabotReactions();
const { ref: containerRef, width: containerWidth } = useElementSize();
@@ -69,7 +73,9 @@ const MetabotQuestionInner = ({
if (isEmbeddedMetabotEnabled === false) {
return (
- <SdkError message={t`Metabot is not enabled for embedded analytics.`} />
+ <SdkError
+ message={t`${metabotName} is not enabled for embedded analytics.`}
+ />
);
}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx
new file mode 100644
index 00000000000..82202bc5df4
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/index.tsx
@@ -0,0 +1,13 @@
+import { PLUGIN_AI_CONTROLS } from "metabase/plugins";
+import { hasPremiumFeature } from "metabase-enterprise/settings";
+
+import { getAiControlsNavItems } from "./nav";
+import { getAiControlsRoutes } from "./routes";
+
+export function initializePlugin() {
+ if (hasPremiumFeature("ai_controls")) {
+ PLUGIN_AI_CONTROLS.isEnabled = true;
+ PLUGIN_AI_CONTROLS.getAiControlsRoutes = getAiControlsRoutes;
+ PLUGIN_AI_CONTROLS.getAiControlsNavItems = getAiControlsNavItems;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx
new file mode 100644
index 00000000000..280947f4137
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/nav.tsx
@@ -0,0 +1,44 @@
+import { t } from "ttag";
+
+import { AdminNavItem } from "metabase/admin/components/AdminNav";
+import { FIXED_METABOT_IDS } from "metabase/metabot/constants";
+
+export function getAiControlsNavItems() {
+ return (
+ <>
+ <AdminNavItem
+ icon="lock"
+ label={t`Usage controls`}
+ folderPattern="usage-controls"
+ >
+ <AdminNavItem
+ label={t`AI feature access`}
+ path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/usage-controls/ai-feature-access`}
+ />
+ </AdminNavItem>
+ <AdminNavItem
+ icon="palette"
+ label={t`Customization`}
+ path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/customization`}
+ />
+ <AdminNavItem
+ icon="document"
+ label={t`System prompts`}
+ folderPattern="system-prompts"
+ >
+ <AdminNavItem
+ label={t`Metabot chat`}
+ path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/system-prompts/metabot-chat`}
+ />
+ <AdminNavItem
+ label={t`Natural language queries`}
+ path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/system-prompts/natural-language-queries`}
+ />
+ <AdminNavItem
+ label={t`SQL generation`}
+ path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}/system-prompts/sql-generation`}
+ />
+ </AdminNavItem>
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.tsx
new file mode 100644
index 00000000000..2994ee3e70c
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.tsx
@@ -0,0 +1,54 @@
+import { useDebouncedCallback } from "@mantine/hooks";
+import { useEffect, useState } from "react";
+import { t } from "ttag";
+
+import {
+ SettingsPageWrapper,
+ SettingsSection,
+} from "metabase/admin/components/SettingsSection";
+import { useAdminSetting } from "metabase/api/utils";
+import { TextInput } from "metabase/ui";
+
+import { MetabotIconField } from "./MetabotIconField";
+
+const SAVE_DEBOUNCE_MS = 500;
+
+export function MetabotCustomizationPage() {
+ const { value: initialInputValue, updateSetting: updateName } =
+ useAdminSetting("metabot-name");
+ const [nameInput, setNameInput] = useState<string>();
+
+ useEffect(() => {
+ if (nameInput === undefined && initialInputValue !== undefined) {
+ setNameInput(initialInputValue ?? "");
+ }
+ }, [initialInputValue, nameInput]);
+
+ const debouncedSaveName = useDebouncedCallback((value: string) => {
+ if (value) {
+ updateName({ key: "metabot-name", value, toast: false });
+ }
+ }, SAVE_DEBOUNCE_MS);
+
+ return (
+ <SettingsPageWrapper title={t`Customization`} mt="sm">
+ <SettingsSection
+ description={t`Customize how Metabot appears to users.`}
+ title={t`Identity`}
+ >
+ <TextInput
+ label={t`Metabot's name`}
+ placeholder={t`Metabot`}
+ mb="sm"
+ value={nameInput}
+ onChange={(e) => {
+ setNameInput(e.currentTarget.value);
+ debouncedSaveName(e.currentTarget.value);
+ }}
+ error={nameInput ? undefined : t`Metabot's name is required`}
+ />
+ <MetabotIconField />
+ </SettingsSection>
+ </SettingsPageWrapper>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.unit.spec.tsx
new file mode 100644
index 00000000000..903956a75ff
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotCustomizationPage.unit.spec.tsx
@@ -0,0 +1,67 @@
+import {
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+ setupUpdateSettingEndpoint,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen } from "__support__/ui";
+import { createMockSettings } from "metabase-types/api/mocks";
+
+import { MetabotCustomizationPage } from "./MetabotCustomizationPage";
+
+function setup({
+ metabotName = "Metabot",
+ metabotIcon = "metabot",
+ showIllustrations = true,
+}: {
+ metabotName?: string;
+ metabotIcon?: string | null;
+ showIllustrations?: boolean;
+} = {}) {
+ setupPropertiesEndpoints(
+ createMockSettings({
+ "metabot-name": metabotName,
+ "metabot-icon": metabotIcon,
+ "metabot-show-illustrations": showIllustrations,
+ }),
+ );
+ setupSettingsEndpoints([]);
+ setupUpdateSettingEndpoint();
+
+ renderWithProviders(<MetabotCustomizationPage />);
+}
+
+describe("MetabotCustomizationPage", () => {
+ it("renders the name input with the current metabot name", async () => {
+ setup({ metabotName: "My AI Assistant" });
+
+ const nameInput = await screen.findByDisplayValue("My AI Assistant");
+ expect(nameInput).toBeInTheDocument();
+ });
+
+ it("shows default icon state when no custom icon is set", async () => {
+ setup({ metabotIcon: "metabot" });
+
+ await screen.findByText("Metabot's icon");
+ expect(
+ screen.queryByRole("button", { name: /Remove custom icon/ }),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByText("Metabot illustrations")).not.toBeInTheDocument();
+ });
+
+ it("shows the remove button and illustrations toggle when a custom icon is set", async () => {
+ setup({ metabotIcon: "data:image/png;base64,abc123" });
+
+ await screen.findByText("Metabot's icon");
+ expect(
+ screen.getByRole("button", { name: /Remove custom icon/ }),
+ ).toBeInTheDocument();
+ expect(screen.getByText("Metabot illustrations")).toBeInTheDocument();
+ });
+
+ it("shows the custom icon preview image when a custom icon is set", async () => {
+ setup({ metabotIcon: "data:image/png;base64,abc123" });
+
+ const preview = await screen.findByAltText("Metabot icon");
+ expect(preview).toHaveAttribute("src", "data:image/png;base64,abc123");
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotIconField.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotIconField.tsx
new file mode 100644
index 00000000000..e0634cfb5c5
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/MetabotIconField.tsx
@@ -0,0 +1,183 @@
+import cx from "classnames";
+import { type ChangeEvent, useRef, useState } from "react";
+import { t } from "ttag";
+
+import { useAdminSetting } from "metabase/api/utils";
+import CS from "metabase/css/core/index.css";
+import {
+ ActionIcon,
+ Box,
+ Button,
+ Flex,
+ Group,
+ Icon,
+ Stack,
+ Switch,
+ Text,
+ Tooltip,
+} from "metabase/ui";
+
+const IMAGE_SIZE_LIMIT = 1024 * 1024; // 1MB limit
+
+export function MetabotIconField() {
+ const { value: metabotIcon, updateSetting } = useAdminSetting("metabot-icon");
+ const {
+ value: showIllustrations,
+ updateSetting: updateShowIllustrations,
+ isLoading: isLoadingIllustrations,
+ } = useAdminSetting("metabot-show-illustrations");
+
+ // Icon upload
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [iconFileName, setIconFileName] = useState("");
+ const [iconError, setIconError] = useState("");
+
+ const isDefaultIcon = !metabotIcon || metabotIcon === "metabot";
+ const iconPreviewSrc =
+ !isDefaultIcon && typeof metabotIcon === "string" ? metabotIcon : null;
+
+ function handleIconUpload(e: ChangeEvent<HTMLInputElement>) {
+ setIconError("");
+ const file = e.target.files?.[0];
+ if (!file) {
+ return;
+ }
+ if (file.size > IMAGE_SIZE_LIMIT) {
+ setIconError(
+ t`The image you chose is larger than 1MB. Please choose another one.`,
+ );
+ return;
+ }
+ const reader = new FileReader();
+ reader.onload = async (readerEvent) => {
+ const dataUri = readerEvent.target?.result as string;
+ if (!(await isFileIntact(dataUri))) {
+ setIconError(
+ t`The image you chose is corrupted. Please choose another one.`,
+ );
+ return;
+ }
+ setIconError("");
+ setIconFileName(file.name);
+ await updateSetting({
+ key: "metabot-icon",
+ value: dataUri,
+ toast: false,
+ });
+ };
+ reader.readAsDataURL(file);
+ }
+
+ async function handleIconRemove() {
+ setIconError("");
+ setIconFileName("");
+ if (fileInputRef.current) {
+ fileInputRef.current.value = "";
+ }
+ await updateSetting({ key: "metabot-icon", value: null, toast: false });
+ }
+
+ return (
+ <Stack gap={0}>
+ <Text lh="lg" fz="md" mb="xs" fw="bold">
+ {t`Metabot's icon`}
+ </Text>
+ <Text fz="md" c="text-secondary" lh="lg">
+ {t`Upload a custom icon for Metabot. For best results, use an SVG or PNG with a transparent background.`}
+ </Text>
+ {iconError && (
+ <Text fz="sm" c="error" mt="xs">
+ {iconError}
+ </Text>
+ )}
+ <Flex
+ align="center"
+ className={cx(CS.bordered, CS.rounded, CS.alignSelfStart)}
+ gap="md"
+ my="sm"
+ py="sm"
+ px="md"
+ >
+ <Box
+ className={cx(CS.bgLight, CS.bordered, CS.rounded)}
+ p="sm"
+ flex="0 0 2.25rem"
+ >
+ {iconPreviewSrc ? (
+ <img
+ src={iconPreviewSrc}
+ alt={t`Metabot icon`}
+ style={{
+ width: "1.5rem",
+ height: "1.5rem",
+ objectFit: "contain",
+ }}
+ />
+ ) : (
+ <Icon name="metabot" />
+ )}
+ </Box>
+ <input
+ ref={fileInputRef}
+ hidden
+ type="file"
+ accept="image/jpeg,image/png,image/svg+xml"
+ multiple={false}
+ onChange={handleIconUpload}
+ />
+ <Button size="sm" onClick={() => fileInputRef.current?.click()}>
+ {t`Upload a custom icon`}
+ </Button>
+ {iconFileName && (
+ <Text fz="sm" c="text-secondary" truncate="end">
+ {iconFileName}
+ </Text>
+ )}
+ {!isDefaultIcon && (
+ <Tooltip label={t`Remove custom icon`}>
+ <ActionIcon
+ onClick={handleIconRemove}
+ aria-label={t`Remove custom icon`}
+ >
+ <Icon name="close" />
+ </ActionIcon>
+ </Tooltip>
+ )}
+ </Flex>
+ {!isDefaultIcon && (
+ <Stack mt="lg" gap="sm">
+ <Text fz="md" fw="bold">
+ {t`Metabot illustrations`}
+ </Text>
+ <Group gap="lg">
+ <Text fz="md" c="text-secondary">
+ {t`Show Metabot illustrations in chat sidebar and natural language query page`}
+ </Text>
+ <Switch
+ aria-label={t`Show Metabot illustrations`}
+ checked={!!showIllustrations}
+ onChange={(e) =>
+ updateShowIllustrations({
+ key: "metabot-show-illustrations",
+ value: e.currentTarget.checked,
+ toast: false,
+ })
+ }
+ disabled={isLoadingIllustrations}
+ size="sm"
+ />
+ </Group>
+ </Stack>
+ )}
+ </Stack>
+ );
+}
+
+async function isFileIntact(dataUri: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ const img = document.createElement("img");
+ img.src = dataUri;
+ img.onerror = () => resolve(false);
+ img.onload = () => resolve(true);
+ });
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/index.ts
new file mode 100644
index 00000000000..11204e994ce
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotCustomizationPage/index.ts
@@ -0,0 +1 @@
+export { MetabotCustomizationPage } from "./MetabotCustomizationPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/AiFeatureAccessTable.module.css b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/AiFeatureAccessTable.module.css
new file mode 100644
index 00000000000..9ddc1bf9eb4
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/AiFeatureAccessTable.module.css
@@ -0,0 +1,32 @@
+.CardContainer {
+ border: 1px solid var(--mb-color-border);
+ border-radius: 0.5rem;
+ background: var(--mb-color-background-primary);
+ overflow: hidden;
+}
+
+.Table {
+ border-collapse: collapse;
+ width: 100%;
+}
+
+.HeaderCell {
+ background: var(--mb-color-background-primary);
+ border-bottom: 1px solid var(--mb-color-border);
+ box-sizing: border-box;
+ color: var(--mb-color-text-primary);
+ font-size: var(--mantine-font-size-md);
+ font-weight: 600;
+ padding: 0.5rem 1rem;
+ vertical-align: middle;
+ white-space: nowrap;
+ text-align: left;
+
+ &.CenterText {
+ text-align: center;
+ }
+
+ &.AiFeatureCell {
+ border-right: 1px solid var(--mb-color-border);
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/AiFeatureAccessTable.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/AiFeatureAccessTable.tsx
new file mode 100644
index 00000000000..fe08cbf7d26
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/AiFeatureAccessTable.tsx
@@ -0,0 +1,65 @@
+import cx from "classnames";
+import { useMemo } from "react";
+import { t } from "ttag";
+import _ from "underscore";
+
+import {
+ AIToolKey,
+ type GroupInfo,
+ type MetabotGroupPermission,
+} from "metabase-types/api";
+
+import S from "./AiFeatureAccessTable.module.css";
+import { GroupPermissionRow } from "./GroupPermissionRow";
+import { getAIToolItems } from "./utils";
+
+export type AiFeatureAccessTableProps = {
+ groups: GroupInfo[];
+ groupPermissions: MetabotGroupPermission[];
+ onPermissionChange: (
+ groupId: number,
+ toolKey: AIToolKey,
+ value: "yes" | "no",
+ ) => void;
+};
+
+export function AiFeatureAccessTable(props: AiFeatureAccessTableProps) {
+ const { groups, groupPermissions, onPermissionChange } = props;
+ const toolItems = getAIToolItems();
+ const permissionsByGroup = useMemo(
+ () => _.groupBy(groupPermissions, "group_id"),
+ [groupPermissions],
+ );
+
+ return (
+ <div className={S.CardContainer} data-testid="ai-feature-access-table">
+ <table className={S.Table}>
+ <thead>
+ <tr>
+ <th className={S.HeaderCell}>{t`Group`}</th>
+ {toolItems.map(({ label, key }) => (
+ <th
+ key={key}
+ className={cx(S.HeaderCell, S.CenterText, {
+ [S.AiFeatureCell]: key === AIToolKey.Metabot,
+ })}
+ >
+ {label}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {groups.map((group) => (
+ <GroupPermissionRow
+ group={group}
+ initialPermissions={permissionsByGroup[group.id] || []}
+ key={group.id}
+ onPermissionChange={onPermissionChange}
+ />
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/GroupCategoryTabs.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/GroupCategoryTabs.tsx
new file mode 100644
index 00000000000..5162c54804e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/GroupCategoryTabs.tsx
@@ -0,0 +1,41 @@
+import { t } from "ttag";
+
+import { Button, Group } from "metabase/ui";
+
+import type { GroupTab } from "./utils";
+
+type TabOption = {
+ tab: GroupTab;
+ label: string;
+};
+
+type GroupCategoryTabsProps = {
+ activeTab: GroupTab;
+ setActiveTab: (tab: GroupTab) => void;
+};
+
+export const GroupCategoryTabs = (props: GroupCategoryTabsProps) => {
+ const { activeTab, setActiveTab } = props;
+ const tabItems: TabOption[] = [
+ { tab: "user-groups", label: t`User groups` },
+ { tab: "tenant-groups", label: t`Tenant groups` },
+ ];
+
+ return (
+ <Group gap="sm" mb="md">
+ {tabItems.map((tabItem) => (
+ <Button
+ bd="none"
+ bg={activeTab === tabItem.tab ? "background-selected" : "transparent"}
+ c={activeTab === tabItem.tab ? "brand" : "text-secondary"}
+ key={tabItem.tab}
+ onClick={() => setActiveTab(tabItem.tab)}
+ radius="xl"
+ size="xs"
+ >
+ {tabItem.label}
+ </Button>
+ ))}
+ </Group>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/GroupPermissionRow.module.css b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/GroupPermissionRow.module.css
new file mode 100644
index 00000000000..ef2d296df2e
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/GroupPermissionRow.module.css
@@ -0,0 +1,27 @@
+.Cell {
+ vertical-align: middle;
+ background: var(--mb-color-background-primary);
+ box-sizing: border-box;
+ padding: 0.5rem 1rem;
+
+ &.CenterText {
+ text-align: center;
+ }
+
+ &.AiFeatureCell {
+ border-right: 1px solid var(--mb-color-border);
+ text-align: center;
+ }
+}
+
+.Row {
+ border-bottom: 1px solid var(--mb-color-border);
+}
+
+.Row:last-child {
+ border-bottom: none;
+}
+
+.InputBody {
+ justify-content: center;
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/GroupPermissionRow.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/GroupPermissionRow.tsx
new file mode 100644
index 00000000000..7f4c12cafbc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/GroupPermissionRow.tsx
@@ -0,0 +1,101 @@
+import cx from "classnames";
+import { type ChangeEvent, useEffect, useState } from "react";
+import { c, t } from "ttag";
+import _, { type Dictionary } from "underscore";
+
+import { Checkbox, Switch, Text } from "metabase/ui";
+import {
+ AIToolKey,
+ type GroupInfo,
+ type MetabotGroupPermission,
+} from "metabase-types/api";
+
+import S from "./GroupPermissionRow.module.css";
+import { getAIToolItems } from "./utils";
+
+type GroupPermissionRowProps = {
+ group: GroupInfo;
+ initialPermissions: MetabotGroupPermission[];
+ onPermissionChange: (
+ groupId: number,
+ toolKey: AIToolKey,
+ value: "yes" | "no",
+ ) => void;
+};
+
+export function GroupPermissionRow(props: GroupPermissionRowProps) {
+ const { onPermissionChange, initialPermissions, group } = props;
+ const [permissionMap, setPermissionMap] =
+ useState<Dictionary<MetabotGroupPermission>>();
+
+ const isAdminGroup = group.magic_group_type === "admin";
+
+ useEffect(() => {
+ // Initialize permission map
+ if (initialPermissions.length && !permissionMap) {
+ setPermissionMap(_.indexBy(initialPermissions, "perm_type"));
+ }
+ }, [permissionMap, initialPermissions]);
+
+ const isMetabotEnabled =
+ isAdminGroup || permissionMap?.[AIToolKey.Metabot]?.perm_value === "yes";
+
+ const handlePermissionChange = (key: AIToolKey, value: "yes" | "no") => {
+ setPermissionMap((prev) => ({
+ ...prev,
+ [key]: {
+ perm_value: value,
+ group_id: group.id,
+ perm_type: key,
+ },
+ }));
+ onPermissionChange(group.id, key, value);
+ };
+
+ return (
+ <tr
+ aria-label={c("{0} is the user group name").t`${group.name} permissions`}
+ className={S.Row}
+ key={group.id}
+ >
+ <td className={S.Cell}>
+ <Text>{group.name}</Text>
+ </td>
+ {getAIToolItems().map(({ key, label }) => {
+ if (key === AIToolKey.Metabot) {
+ return (
+ <td key={key} className={cx(S.Cell, S.AiFeatureCell)}>
+ <Switch
+ aria-label={t`Allow ${group.name} user group to access AI features.`}
+ size="sm"
+ checked={isMetabotEnabled}
+ onChange={(e: ChangeEvent<HTMLInputElement>) =>
+ handlePermissionChange(key, e.target.checked ? "yes" : "no")
+ }
+ classNames={{ body: S.InputBody }}
+ disabled={isAdminGroup}
+ />
+ </td>
+ );
+ }
+
+ return (
+ <td key={key} className={S.Cell}>
+ <Checkbox
+ aria-label={t`Allow ${group.name} user group to access ${label} AI tool.`}
+ size="md"
+ checked={
+ isAdminGroup || permissionMap?.[key]?.perm_value === "yes"
+ }
+ onChange={(e: ChangeEvent<HTMLInputElement>) =>
+ handlePermissionChange(key, e.target.checked ? "yes" : "no")
+ }
+ classNames={{ body: S.InputBody }}
+ disabled={isAdminGroup || !isMetabotEnabled}
+ />
+ </td>
+ );
+ })}
+ </tr>
+ );
+}
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.tsx
new file mode 100644
index 00000000000..efa0a10f0df
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessPage.tsx
@@ -0,0 +1,65 @@
+import { useState } from "react";
+import { t } from "ttag";
+
+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
+import { useListPermissionsGroupsQuery } from "metabase/api";
+import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
+import { useSetting } from "metabase/common/hooks";
+
+import { AiFeatureAccessTable } from "./AiFeatureAccessTable";
+import { GroupCategoryTabs } from "./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,
+ 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 title={t`AI feature access`} mt="sm">
+ {isUsingTenants && (
+ <GroupCategoryTabs setActiveTab={setActiveTab} activeTab={activeTab} />
+ )}
+
+ <LoadingAndErrorWrapper loading={isLoading} error={error}>
+ {activeGroups && (
+ <AiFeatureAccessTable
+ groups={activeGroups}
+ groupPermissions={groupPermissions}
+ onPermissionChange={onPermissionChange}
+ />
+ )}
+ </LoadingAndErrorWrapper>
+ </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.tsx
new file mode 100644
index 00000000000..0f7d7246775
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/MetabotFeatureAccessPage.unit.spec.tsx
@@ -0,0 +1,209 @@
+import userEvent from "@testing-library/user-event";
+
+import { setupGroupsEndpoint } from "__support__/server-mocks/group";
+import {
+ setupMetabotGroupPermissionsEndpoint,
+ setupUpdateMetabotGroupPermissionsEndpoint,
+} from "__support__/server-mocks/metabot";
+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 { createMockSettingsState } from "metabase-types/store/mocks";
+
+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,
+}: {
+ permissions?: MetabotGroupPermission[];
+ groups?: typeof defaultGroups;
+ useTenants?: boolean;
+} = {}) {
+ setupGroupsEndpoint(groups);
+ setupMetabotGroupPermissionsEndpoint(permissions);
+ setupUpdateMetabotGroupPermissionsEndpoint();
+
+ renderWithProviders(<MetabotFeatureAccessPage />, {
+ storeInitialState: {
+ settings: createMockSettingsState({ "use-tenants": useTenants }),
+ },
+ });
+}
+
+function getPermissionRow(groupName: string) {
+ return screen.getByRole("row", {
+ name: new RegExp(`${groupName} permissions`),
+ });
+}
+
+describe("MetabotFeatureAccessPage", () => {
+ it("renders groups with their permission states", async () => {
+ setup();
+
+ expect(
+ await screen.findByTestId("ai-feature-access-table"),
+ ).toBeInTheDocument();
+
+ expect(screen.getByText("Administrators")).toBeInTheDocument();
+ expect(screen.getByText("All Users")).toBeInTheDocument();
+ expect(screen.getByText("Marketing")).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("disables sub-permission checkboxes when metabot is off for a group", async () => {
+ setup();
+ 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).toBeDisabled();
+ });
+ });
+
+ it("enables sub-permission checkboxes after toggling metabot on", async () => {
+ setup();
+ 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();
+ });
+ });
+
+ it("unchecks and disables sub-permissions when toggling metabot off", 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).toBeDisabled();
+ });
+ });
+
+ 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();
+ });
+});
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.ts
new file mode 100644
index 00000000000..b3ad7da7cfc
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/index.ts
@@ -0,0 +1 @@
+export { MetabotFeatureAccessPage } from "./MetabotFeatureAccessPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.ts
new file mode 100644
index 00000000000..ff211882704
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotFeatureAccessPage/utils.ts
@@ -0,0 +1,81 @@
+import { useDebouncedCallback } from "@mantine/hooks";
+import { useEffect, useState } from "react";
+import { t } from "ttag";
+
+import {
+ useGetMetabotPermissionsQuery,
+ useUpdateMetabotPermissionsMutation,
+} from "metabase/api";
+import { useMetadataToasts } from "metabase/metadata/hooks";
+import { AIToolKey, type MetabotGroupPermission } from "metabase-types/api";
+
+export type GroupTab = "user-groups" | "tenant-groups";
+
+export const getAIToolItems = (): Array<{ key: AIToolKey; label: string }> => {
+ return [
+ { key: AIToolKey.Metabot, label: t`AI features` },
+ { key: AIToolKey.ChatAndNLQ, label: t`Chat and NLQ` },
+ { key: AIToolKey.SQLGeneration, label: t`SQL generation` },
+ { key: AIToolKey.OtherTools, label: t`Other tools` },
+ ];
+};
+
+const PERMISSIONS_SAVE_DEBOUNCE = 500;
+
+export const useMetabotGroupPermissions = () => {
+ const { data: permissionsQueryData, error: permissionsQueryError } =
+ useGetMetabotPermissionsQuery();
+ const [updateMetabotPermissions] = useUpdateMetabotPermissionsMutation();
+ const [groupPermissions, setGroupPermissions] = useState<
+ MetabotGroupPermission[]
+ >([]);
+ const { sendErrorToast } = useMetadataToasts();
+
+ useEffect(() => {
+ if (groupPermissions.length) {
+ // Already initialized
+ return;
+ }
+
+ const { permissions } = permissionsQueryData || {};
+ if (permissions?.length) {
+ setGroupPermissions(permissions);
+ }
+ }, [permissionsQueryData, groupPermissions]);
+
+ const debouncedUpdatePermissions = useDebouncedCallback(async () => {
+ try {
+ await updateMetabotPermissions({
+ permissions: groupPermissions,
+ }).unwrap();
+ } catch {
+ sendErrorToast(t`Failed to save Metabot permissions`);
+ }
+ }, PERMISSIONS_SAVE_DEBOUNCE);
+
+ const onPermissionChange = (
+ groupId: number,
+ tool: AIToolKey,
+ value: "yes" | "no",
+ ) => {
+ setGroupPermissions((prevPermissions) => {
+ return prevPermissions.map((permission) => {
+ if (permission.group_id === groupId && permission.perm_type === tool) {
+ return {
+ ...permission,
+ perm_value: value,
+ } as MetabotGroupPermission;
+ }
+
+ return permission;
+ });
+ });
+ debouncedUpdatePermissions();
+ };
+
+ return {
+ groupPermissions,
+ onPermissionChange,
+ error: permissionsQueryError ? t`Failed to load Metabot permissions` : null,
+ };
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.module.css b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.module.css
new file mode 100644
index 00000000000..62c01dc04f9
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.module.css
@@ -0,0 +1,6 @@
+.textareaWrapper {
+ textarea {
+ line-height: 1.25rem;
+ min-height: 400px;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx
new file mode 100644
index 00000000000..ad03e2efa6a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.tsx
@@ -0,0 +1,98 @@
+import { t } from "ttag";
+
+import {
+ SettingsPageWrapper,
+ SettingsSection,
+} from "metabase/admin/components/SettingsSection";
+import { useSelector } from "metabase/lib/redux";
+import { getApplicationName } from "metabase/selectors/whitelabel";
+import { Text, Textarea } from "metabase/ui";
+
+import S from "./MetabotSystemPromptsPage.module.css";
+import type { SystemPromptSettingKey } from "./hooks/useSystemPromptInput";
+import { useSystemPromptInput } from "./hooks/useSystemPromptInput";
+
+interface SystemPromptPageProps {
+ title: string;
+ description: string;
+ settingKey: SystemPromptSettingKey;
+}
+
+function SystemPromptPage({
+ title,
+ description,
+ settingKey,
+}: SystemPromptPageProps) {
+ const { inputText, onInputChange } = useSystemPromptInput(settingKey);
+
+ return (
+ <SettingsPageWrapper title={title} mt="sm">
+ <SettingsSection>
+ <Text c="text-secondary" size="md" mb="lg">
+ {description}
+ </Text>
+ <Textarea
+ aria-label={title}
+ className={S.textareaWrapper}
+ onChange={onInputChange}
+ placeholder={getPlaceholder()}
+ value={inputText}
+ />
+ </SettingsSection>
+ </SettingsPageWrapper>
+ );
+}
+
+const getPlaceholder = () => {
+ return (
+ t`# Here's a section` +
+ "\n" +
+ t`1. Do this` +
+ "\n" +
+ t`2. And this` +
+ "\n" +
+ t`3. And lastly, this` +
+ "\n\n" +
+ t`# Here's another section` +
+ "\n" +
+ t`1. Do this` +
+ "\n" +
+ t`2. And this` +
+ "\n" +
+ t`3. And lastly, this`
+ );
+};
+
+export function MetabotChatPromptPage() {
+ const applicationName = useSelector(getApplicationName);
+
+ return (
+ <SystemPromptPage
+ title={t`Metabot chat prompt instructions`}
+ description={t`Add instructions here for the sidebar AI chat experience in ${applicationName}. You might want to give instructions about tone, types of entities to prefer, and things like that.`}
+ settingKey="metabot-chat-system-prompt"
+ />
+ );
+}
+
+export function NaturalLanguagePromptPage() {
+ const applicationName = useSelector(getApplicationName);
+
+ return (
+ <SystemPromptPage
+ title={t`Natural language query prompt instructions`}
+ description={t`Add instructions for the "AI exploration" or natural language query experience in ${applicationName}. You could suggest tables to prefer in answers, specific chart types to default to, and more.`}
+ settingKey="metabot-nlq-system-prompt"
+ />
+ );
+}
+
+export function SqlGenerationPromptPage() {
+ return (
+ <SystemPromptPage
+ title={t`SQL generation prompt instructions`}
+ description={t`If you have preferences about joins, uppercase vs. lowercase, how many spaces to use for indentation, or anything else SQL-related, this is the place to put it.`}
+ settingKey="metabot-sql-system-prompt"
+ />
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.unit.spec.tsx
new file mode 100644
index 00000000000..5f575126fd6
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/MetabotSystemPromptsPage.unit.spec.tsx
@@ -0,0 +1,141 @@
+import userEvent from "@testing-library/user-event";
+
+import {
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+ setupUpdateSettingEndpoint,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { createMockSettings } from "metabase-types/api/mocks";
+
+import {
+ MetabotChatPromptPage,
+ NaturalLanguagePromptPage,
+ SqlGenerationPromptPage,
+} from "./MetabotSystemPromptsPage";
+
+function setup({
+ Component,
+ settingKey,
+ settingValue = "",
+}: {
+ Component: React.ComponentType;
+ settingKey:
+ | "metabot-chat-system-prompt"
+ | "metabot-nlq-system-prompt"
+ | "metabot-sql-system-prompt";
+ settingValue?: string | null;
+}) {
+ setupPropertiesEndpoints(
+ createMockSettings({
+ [settingKey]: settingValue,
+ }),
+ );
+ setupSettingsEndpoints([]);
+ setupUpdateSettingEndpoint();
+
+ renderWithProviders(<Component />);
+}
+
+describe("MetabotSystemPromptsPage", () => {
+ describe("MetabotChatPromptPage", () => {
+ it("renders with the correct title", async () => {
+ setup({
+ Component: MetabotChatPromptPage,
+ settingKey: "metabot-chat-system-prompt",
+ });
+
+ expect(
+ await screen.findByText("Metabot chat prompt instructions"),
+ ).toBeInTheDocument();
+ });
+
+ it("renders the textarea with existing prompt value", async () => {
+ setup({
+ Component: MetabotChatPromptPage,
+ settingKey: "metabot-chat-system-prompt",
+ settingValue: "Be concise and helpful",
+ });
+
+ const textarea = await screen.findByRole("textbox", {
+ name: "Metabot chat prompt instructions",
+ });
+
+ await waitFor(() => {
+ expect(textarea).toHaveValue("Be concise and helpful");
+ });
+ });
+
+ it("updates the textarea value when user types", async () => {
+ setup({
+ Component: MetabotChatPromptPage,
+ settingKey: "metabot-chat-system-prompt",
+ });
+
+ const textarea = await screen.findByRole("textbox", {
+ name: "Metabot chat prompt instructions",
+ });
+ await userEvent.type(textarea, "New instructions");
+
+ await waitFor(() => {
+ expect(textarea).toHaveValue("New instructions");
+ });
+ });
+ });
+
+ describe("NaturalLanguagePromptPage", () => {
+ it("renders with the correct title", async () => {
+ setup({
+ Component: NaturalLanguagePromptPage,
+ settingKey: "metabot-nlq-system-prompt",
+ });
+
+ expect(
+ await screen.findByText("Natural language query prompt instructions"),
+ ).toBeInTheDocument();
+ });
+
+ it("renders the textarea with existing prompt value", async () => {
+ setup({
+ Component: NaturalLanguagePromptPage,
+ settingKey: "metabot-nlq-system-prompt",
+ settingValue: "Prefer bar charts",
+ });
+
+ const textarea = await screen.findByRole("textbox", {
+ name: "Natural language query prompt instructions",
+ });
+ await waitFor(() => {
+ expect(textarea).toHaveValue("Prefer bar charts");
+ });
+ });
+ });
+
+ describe("SqlGenerationPromptPage", () => {
+ it("renders with the correct title", async () => {
+ setup({
+ Component: SqlGenerationPromptPage,
+ settingKey: "metabot-sql-system-prompt",
+ });
+
+ expect(
+ await screen.findByText("SQL generation prompt instructions"),
+ ).toBeInTheDocument();
+ });
+
+ it("renders the textarea with existing prompt value", async () => {
+ setup({
+ Component: SqlGenerationPromptPage,
+ settingKey: "metabot-sql-system-prompt",
+ settingValue: "Use uppercase SQL keywords",
+ });
+
+ const textarea = await screen.findByRole("textbox", {
+ name: "SQL generation prompt instructions",
+ });
+ await waitFor(() => {
+ expect(textarea).toHaveValue("Use uppercase SQL keywords");
+ });
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/hooks/useSystemPromptInput.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/hooks/useSystemPromptInput.tsx
new file mode 100644
index 00000000000..0c18b73bd04
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/hooks/useSystemPromptInput.tsx
@@ -0,0 +1,42 @@
+import { useDebouncedCallback } from "@mantine/hooks";
+import { type ChangeEvent, useEffect, useState } from "react";
+
+import { useAdminSetting } from "metabase/api/utils";
+
+export type SystemPromptSettingKey =
+ | "metabot-chat-system-prompt"
+ | "metabot-nlq-system-prompt"
+ | "metabot-sql-system-prompt";
+
+const DEBOUNCE_DELAY = 500;
+
+export function useSystemPromptInput(settingKey: SystemPromptSettingKey) {
+ const { value: initialPromptText, updateSetting } =
+ useAdminSetting(settingKey);
+ const [inputText, setInputText] = useState<string>();
+
+ useEffect(() => {
+ if (inputText === undefined && initialPromptText !== undefined) {
+ setInputText(initialPromptText ?? "");
+ }
+ }, [initialPromptText, inputText]);
+
+ const debouncedUpdateSystemPrompt = useDebouncedCallback((value: string) => {
+ updateSetting({
+ key: settingKey,
+ value: value || null,
+ toast: false,
+ });
+ }, DEBOUNCE_DELAY);
+
+ const onInputChange = (event: ChangeEvent<HTMLTextAreaElement>) => {
+ const newValue = event.currentTarget.value;
+ setInputText(newValue);
+ debouncedUpdateSystemPrompt(newValue);
+ };
+
+ return {
+ inputText,
+ onInputChange,
+ };
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/index.ts
new file mode 100644
index 00000000000..f896ba42958
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotSystemPromptsPage/index.ts
@@ -0,0 +1,5 @@
+export {
+ MetabotChatPromptPage,
+ NaturalLanguagePromptPage,
+ SqlGenerationPromptPage,
+} from "./MetabotSystemPromptsPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/MetabotUsageLimitsPage.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/MetabotUsageLimitsPage.tsx
new file mode 100644
index 00000000000..69a3a2e8a24
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/MetabotUsageLimitsPage.tsx
@@ -0,0 +1,22 @@
+import { t } from "ttag";
+
+import {
+ SettingsPageWrapper,
+ SettingsSection,
+} from "metabase/admin/components/SettingsSection";
+import { Group, Icon, Text } from "metabase/ui";
+
+export function MetabotUsageLimitsPage() {
+ return (
+ <SettingsPageWrapper title={t`AI usage limits`} mt="sm">
+ <SettingsSection>
+ <Group>
+ <Icon name="ai" />
+ <Text fz="md" c="text-secondary">
+ {t`Not implemented yet. Come back later.`}
+ </Text>
+ </Group>
+ </SettingsSection>
+ </SettingsPageWrapper>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/index.ts b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/index.ts
new file mode 100644
index 00000000000..b35b9269cf4
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/pages/MetabotUsageLimitsPage/index.ts
@@ -0,0 +1 @@
+export { MetabotUsageLimitsPage } from "./MetabotUsageLimitsPage";
diff --git a/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx b/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx
new file mode 100644
index 00000000000..129a07c682f
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/ai-controls/routes.tsx
@@ -0,0 +1,47 @@
+import { Route } from "react-router";
+
+import { MetabotCustomizationPage } from "./pages/MetabotCustomizationPage";
+import { MetabotFeatureAccessPage } from "./pages/MetabotFeatureAccessPage";
+import {
+ MetabotChatPromptPage,
+ NaturalLanguagePromptPage,
+ SqlGenerationPromptPage,
+} from "./pages/MetabotSystemPromptsPage";
+import { MetabotUsageLimitsPage } from "./pages/MetabotUsageLimitsPage";
+
+export function getAiControlsRoutes() {
+ return (
+ <>
+ <Route
+ key="ai-feature-access"
+ path=":metabotId/usage-controls/ai-feature-access"
+ component={MetabotFeatureAccessPage}
+ />
+ <Route
+ key="ai-usage-limits"
+ path=":metabotId/usage-controls/ai-usage-limits"
+ component={MetabotUsageLimitsPage}
+ />
+ <Route
+ key="customization"
+ path=":metabotId/customization"
+ component={MetabotCustomizationPage}
+ />
+ <Route
+ key="system-prompts-metabot-chat"
+ path=":metabotId/system-prompts/metabot-chat"
+ component={MetabotChatPromptPage}
+ />
+ <Route
+ key="system-prompts-natural-language-queries"
+ path=":metabotId/system-prompts/natural-language-queries"
+ component={NaturalLanguagePromptPage}
+ />
+ <Route
+ key="system-prompts-sql-generation"
+ path=":metabotId/system-prompts/sql-generation"
+ component={SqlGenerationPromptPage}
+ />
+ </>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/plugins.ts b/enterprise/frontend/src/metabase-enterprise/plugins.ts
index ef3595ad137..6dad7dcc701 100644
--- a/enterprise/frontend/src/metabase-enterprise/plugins.ts
+++ b/enterprise/frontend/src/metabase-enterprise/plugins.ts
@@ -10,6 +10,7 @@ import "./license";
// PLUGINS THAT USE hasPremiumFeature (import initialization functions):
import { initializePlugin as initializeAdvancedPermissions } from "./advanced_permissions";
+import { initializePlugin as initializeAiControls } from "./ai-controls";
import { initializePlugin as initializeApplicationPermissions } from "./application_permissions";
import { initializePlugin as initializeAuditApp } from "./audit_app";
import { initializePlugin as initializeAuth } from "./auth";
@@ -97,4 +98,5 @@ export function initializePlugins() {
initializeTenants?.();
initializeWorkspaces();
initializeWritableConnection();
+ initializeAiControls();
}
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.ts
index f11aa093259..5f09906bcd9 100644
--- a/frontend/src/metabase-types/api/metabot.ts
+++ b/frontend/src/metabase-types/api/metabot.ts
@@ -313,3 +313,37 @@ export type MetabotSlackSettings =
"slack-connect-client-secret": null;
"metabot-slack-signing-secret": null;
};
+
+/* Metabot v3 - Group Permissions */
+
+export enum AIToolKey {
+ Metabot = "permission/metabot",
+ ChatAndNLQ = "permission/metabot-nlq",
+ SQLGeneration = "permission/metabot-sql-generation",
+ OtherTools = "permission/metabot-other-tools",
+}
+
+export type MetabotGroupPermission = {
+ group_id: number;
+ perm_type: AIToolKey;
+ perm_value: "yes" | "no";
+};
+
+export type MetabotPermissionsResponse = {
+ permissions: MetabotGroupPermission[];
+};
+
+export type UpdateMetabotPermissionsRequest = {
+ permissions: MetabotGroupPermission[];
+};
+
+export type UserMetabotPermissions = {
+ metabot: "yes" | "no";
+ "metabot-sql-generation": "yes" | "no";
+ "metabot-nlq": "yes" | "no";
+ "metabot-other-tools": "yes" | "no";
+};
+
+export type UserMetabotPermissionsResponse = {
+ permissions: UserMetabotPermissions;
+};
diff --git a/frontend/src/metabase-types/api/mocks/metabot.ts b/frontend/src/metabase-types/api/mocks/metabot.ts
index e205b664596..546db84e877 100644
--- a/frontend/src/metabase-types/api/mocks/metabot.ts
+++ b/frontend/src/metabase-types/api/mocks/metabot.ts
@@ -1,4 +1,10 @@
-import type { MetabotInfo } from "../metabot";
+import {
+ AIToolKey,
+ type MetabotGroupPermission,
+ type MetabotInfo,
+ type UserMetabotPermissions,
+ type UserMetabotPermissionsResponse,
+} from "../metabot";
export const createMockMetabotInfo = (
opts?: Partial<MetabotInfo>,
@@ -13,3 +19,43 @@ export const createMockMetabotInfo = (
updated_at: new Date().toISOString(),
...opts,
});
+
+export const createMockUserMetabotPermissions = (
+ opts?: Partial<UserMetabotPermissions>,
+): UserMetabotPermissionsResponse => ({
+ permissions: {
+ metabot: "yes",
+ "metabot-sql-generation": "yes",
+ "metabot-nlq": "yes",
+ "metabot-other-tools": "yes",
+ ...opts,
+ },
+});
+
+export const createMockMetabotGroupPermission = (
+ opts?: Partial<MetabotGroupPermission>,
+): MetabotGroupPermission => ({
+ group_id: 1,
+ perm_type: AIToolKey.Metabot,
+ perm_value: "yes",
+ ...opts,
+});
+
+export const createMockMetabotGroupPermissions = (
+ groupId: number,
+ overrides?: Partial<Record<AIToolKey, "yes" | "no">>,
+): MetabotGroupPermission[] => {
+ const defaults: Record<AIToolKey, "yes" | "no"> = {
+ [AIToolKey.Metabot]: "yes",
+ [AIToolKey.ChatAndNLQ]: "yes",
+ [AIToolKey.SQLGeneration]: "yes",
+ [AIToolKey.OtherTools]: "yes",
+ ...overrides,
+ };
+
+ return Object.entries(defaults).map(([permType, permValue]) => ({
+ group_id: groupId,
+ perm_type: permType as AIToolKey,
+ perm_value: permValue,
+ }));
+};
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index d2c9e4ca959..a096042624c 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -146,6 +146,7 @@ export const createMockTokenFeatures = (
tenants: false,
workspaces: false,
writable_connection: false,
+ ai_controls: false,
...opts,
});
@@ -367,6 +368,12 @@ export const createMockSettings = (
"show-homepage-pin-message": false,
"show-homepage-xrays": false,
"metabot-enabled?": true,
+ "metabot-name": "Metabot",
+ "metabot-icon": "metabot",
+ "metabot-show-illustrations": true,
+ "metabot-chat-system-prompt": null,
+ "metabot-nlq-system-prompt": null,
+ "metabot-sql-system-prompt": null,
"embedded-metabot-enabled?": true,
"show-metabase-links": true,
"show-metabot": true,
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index c4bb50296c1..d009c2bc0a0 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -363,6 +363,7 @@ export const tokenFeatures = [
"tenants",
"workspaces",
"writable_connection",
+ "ai_controls",
] as const;
export type TokenFeature = (typeof tokenFeatures)[number];
@@ -590,6 +591,12 @@ interface PublicSettings {
"session-cookies": boolean | null;
"setup-token": string | null;
"metabot-enabled?": boolean;
+ "metabot-name": string;
+ "metabot-icon": string | null;
+ "metabot-show-illustrations": boolean;
+ "metabot-chat-system-prompt": string | null;
+ "metabot-nlq-system-prompt": string | null;
+ "metabot-sql-system-prompt": string | null;
"embedded-metabot-enabled?": boolean;
"show-metabase-links": boolean;
"show-metabot": boolean;
diff --git a/frontend/src/metabase/admin/routes.tsx b/frontend/src/metabase/admin/routes.tsx
index 04da703a5f2..0788eb7dbae 100644
--- a/frontend/src/metabase/admin/routes.tsx
+++ b/frontend/src/metabase/admin/routes.tsx
@@ -46,7 +46,7 @@ import {
SetupSsoPage,
} from "metabase/embedding/embedding-hub";
import { ModalRoute } from "metabase/hoc/ModalRoute";
-import { getAdminRoutes as getMetabotAdminRoutes } from "metabase/metabot/components/MetabotAdmin/MetabotAdminPage";
+import { getMetabotAdminRoutes } from "metabase/metabot/components/MetabotAdmin/routes";
import { DataModelV1 } from "metabase/metadata/pages/DataModelV1";
import {
PLUGIN_ADMIN_TOOLS,
diff --git a/frontend/src/metabase/api/metabot.ts b/frontend/src/metabase/api/metabot.ts
index 4fc12a9437c..4881075c805 100644
--- a/frontend/src/metabase/api/metabot.ts
+++ b/frontend/src/metabase/api/metabot.ts
@@ -5,12 +5,15 @@ import type {
MetabotGenerateContentResponse,
MetabotId,
MetabotInfo,
+ MetabotPermissionsResponse,
MetabotProvider,
MetabotSettingsResponse,
MetabotSlackSettings,
SuggestedMetabotPromptsRequest,
SuggestedMetabotPromptsResponse,
+ UpdateMetabotPermissionsRequest,
UpdateMetabotSettingsRequest,
+ UserMetabotPermissionsResponse,
} from "metabase-types/api";
import { Api } from "./api";
@@ -133,6 +136,34 @@ export const metabotApi = Api.injectEndpoints({
}),
invalidatesTags: ["session-properties"],
}),
+ getMetabotPermissions: builder.query<MetabotPermissionsResponse, void>({
+ query: () => ({
+ method: "GET",
+ url: "/api/ee/ai-controls/permissions",
+ }),
+ providesTags: () => [listTag("metabot-permissions")],
+ }),
+ getUserMetabotPermissions: builder.query<
+ UserMetabotPermissionsResponse,
+ void
+ >({
+ query: () => ({
+ method: "GET",
+ url: "/api/metabot/permissions/user-permissions",
+ }),
+ providesTags: () => [listTag("metabot-permissions")],
+ }),
+ updateMetabotPermissions: builder.mutation<
+ void,
+ UpdateMetabotPermissionsRequest
+ >({
+ query: (body) => ({
+ method: "PUT",
+ url: "/api/ee/ai-controls/permissions",
+ body,
+ }),
+ invalidatesTags: [listTag("metabot-permissions")],
+ }),
}),
});
@@ -147,4 +178,7 @@ export const {
useLazyMetabotGenerateContentQuery,
useSubmitMetabotFeedbackMutation,
useUpdateMetabotSlackSettingsMutation,
+ useGetMetabotPermissionsQuery,
+ useGetUserMetabotPermissionsQuery,
+ useUpdateMetabotPermissionsMutation,
} = metabotApi;
diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.ts
index 11b999bde72..568f28f8096 100644
--- a/frontend/src/metabase/api/tags/constants.ts
+++ b/frontend/src/metabase/api/tags/constants.ts
@@ -66,6 +66,7 @@ export const TAG_TYPES = [
"metabot",
"metabot-entities-list",
"metabot-prompt-suggestions",
+ "metabot-permissions",
] as const;
export const TAG_TYPE_MAPPING = {
diff --git a/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.unit.spec.tsx b/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.unit.spec.tsx
index e724c85c04a..cd6a3607af4 100644
--- a/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.unit.spec.tsx
+++ b/frontend/src/metabase/collections/components/CollectionEmptyState/CollectionEmptyState.unit.spec.tsx
@@ -1,6 +1,7 @@
import {
setupDatabasesEndpoints,
setupSearchEndpoints,
+ setupUserMetabotPermissionsEndpoint,
} from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
import CollectionEmptyState from "metabase/collections/components/CollectionEmptyState";
@@ -27,6 +28,7 @@ async function setup({
}: { collection?: Partial<Collection> } = {}) {
const mockCollection = createMockCollection(collection);
+ setupUserMetabotPermissionsEndpoint();
setupDatabasesEndpoints([TEST_DATABASE]);
setupSearchEndpoints([TEST_COLLECTION_ITEM]);
diff --git a/frontend/src/metabase/common/components/MetabotLogo/MetabotLogo.tsx b/frontend/src/metabase/common/components/MetabotLogo/MetabotLogo.tsx
index 706e6eb29e6..5ee2cc564c3 100644
--- a/frontend/src/metabase/common/components/MetabotLogo/MetabotLogo.tsx
+++ b/frontend/src/metabase/common/components/MetabotLogo/MetabotLogo.tsx
@@ -1,12 +1,12 @@
import cx from "classnames";
import { type HTMLProps, type Ref, forwardRef } from "react";
-import { t } from "ttag";
import bug from "assets/img/metabot-bug-report.svg?component";
import cloud from "assets/img/metabot-cloud-96x96.svg?component";
import happy from "assets/img/metabot-happy.svg?component";
import sad from "assets/img/metabot-sad.svg?component";
import cool from "assets/img/metabot-shades.svg?component";
+import { useMetabotName } from "metabase/metabot/hooks";
import Styles from "./MetabotLogo.module.css";
@@ -31,13 +31,14 @@ export const MetabotLogo = forwardRef(function MetabotLogo(
ref: Ref<any>,
) {
const MetabotComponent = urlByVariant[variant];
+ const metabotName = useMetabotName();
return (
<MetabotComponent
className={cx(Styles.MetabotLogo, className)}
{...rest}
ref={ref}
- aria-label={t`Metabot`}
+ aria-label={metabotName}
role="img"
/>
);
diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx
index 0441d34c0ed..68827d450ca 100644
--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx
+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenu.unit.spec.tsx
@@ -3,6 +3,7 @@ import userEvent from "@testing-library/user-event";
import {
setupCollectionByIdEndpoint,
setupDatabasesEndpoints,
+ setupUserMetabotPermissionsEndpoint,
} from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
import { NewModals } from "metabase/new/components/NewModals/NewModals";
@@ -33,6 +34,7 @@ async function setup({
databases = [SAMPLE_DATABASE],
canWrite = true,
}: SetupOpts = {}) {
+ setupUserMetabotPermissionsEndpoint();
setupDatabasesEndpoints(databases);
setupCollectionByIdEndpoint({
collections: [COLLECTION],
diff --git a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx
index eb53f48c297..94d4f17828c 100644
--- a/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx
+++ b/frontend/src/metabase/common/components/NewItemMenu/NewItemMenuView.tsx
@@ -6,7 +6,7 @@ import { ForwardRefLink } from "metabase/common/components/Link";
import { useDispatch, useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import { getNewMenuItemAIExploration } from "metabase/metabot/components/NewMenuItemAIExploration";
-import { useMetabotEnabledEmbeddingAware } from "metabase/metabot/hooks";
+import { useUserMetabotPermissions } from "metabase/metabot/hooks";
import { setOpenModal } from "metabase/redux/ui";
import { getSetting } from "metabase/selectors/settings";
import { getUserCanWriteToCollections } from "metabase/selectors/user";
@@ -42,7 +42,7 @@ export const NewItemMenuView = ({
const canWriteToCollections = useSelector(getUserCanWriteToCollections);
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseNlq } = useUserMetabotPermissions();
const menuItems = useMemo(() => {
const items = [];
@@ -50,7 +50,7 @@ export const NewItemMenuView = ({
const aiExplorationItem = getNewMenuItemAIExploration(
hasDataAccess,
collectionId,
- isMetabotEnabled,
+ canUseNlq,
);
if (aiExplorationItem) {
items.push(aiExplorationItem);
@@ -128,7 +128,7 @@ export const NewItemMenuView = ({
hasDatabaseWithJsonEngine,
dispatch,
canWriteToCollections,
- isMetabotEnabled,
+ canUseNlq,
]);
if (menuItems.length === 0) {
diff --git a/frontend/src/metabase/css/core/flex.module.css b/frontend/src/metabase/css/core/flex.module.css
index 5211949608f..a13e502c364 100644
--- a/frontend/src/metabase/css/core/flex.module.css
+++ b/frontend/src/metabase/css/core/flex.module.css
@@ -80,6 +80,10 @@
align-items: stretch;
}
+.alignSelfStart {
+ align-self: flex-start;
+}
+
.alignSelfEnd {
align-self: flex-end;
}
diff --git a/frontend/src/metabase/data-studio/app/pages/TransformsSectionLayout/TransformsSectionLayout.unit.spec.tsx b/frontend/src/metabase/data-studio/app/pages/TransformsSectionLayout/TransformsSectionLayout.unit.spec.tsx
index b4b999ceb8d..06cb23b198a 100644
--- a/frontend/src/metabase/data-studio/app/pages/TransformsSectionLayout/TransformsSectionLayout.unit.spec.tsx
+++ b/frontend/src/metabase/data-studio/app/pages/TransformsSectionLayout/TransformsSectionLayout.unit.spec.tsx
@@ -2,6 +2,7 @@ import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import {
setupStoreEEBillingEndpoint,
setupStoreEECloudAddOnsEndpoint,
+ setupUserMetabotPermissionsEndpoint,
} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen } from "__support__/ui";
@@ -28,6 +29,8 @@ const setup = ({
transformsEnabled?: boolean;
isAdmin?: boolean;
} = {}) => {
+ setupUserMetabotPermissionsEndpoint();
+
const settings = mockSettings({
"token-features": createMockTokenFeatures({
"transforms-basic": hasTransformFeature,
diff --git a/frontend/src/metabase/documents/components/Editor/shared/MenuComponents.tsx b/frontend/src/metabase/documents/components/Editor/shared/MenuComponents.tsx
index 3a932410858..1cce09558d3 100644
--- a/frontend/src/metabase/documents/components/Editor/shared/MenuComponents.tsx
+++ b/frontend/src/metabase/documents/components/Editor/shared/MenuComponents.tsx
@@ -1,6 +1,8 @@
import type { DOMAttributes, MouseEvent } from "react";
import { t } from "ttag";
+import { MetabotIcon } from "metabase/metabot/components/MetabotIcon";
+import { useMetabotName } from "metabase/metabot/hooks";
import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";
import {
Avatar,
@@ -111,3 +113,25 @@ export const CreateNewQuestionFooter = ({
</Group>
</UnstyledButton>
);
+
+export const MetabotFooter = ({ isSelected, onClick }: ExtraItemProps) => {
+ const metabotName = useMetabotName();
+ return (
+ <UnstyledButton
+ className={S.menuItemWithBorder}
+ onClick={onClick}
+ role="option"
+ aria-selected={isSelected}
+ >
+ <Group gap="sm" wrap="nowrap" align="center">
+ <MetabotIcon size={16} c="inherit" />
+ <Stack gap={2}>
+ <Text size="md" lh="lg" c="inherit">{t`Ask ${metabotName}`}</Text>
+ <Text size="sm" c="text-tertiary" lh="md">
+ {t`It wants to help!`}
+ </Text>
+ </Stack>
+ </Group>
+ </UnstyledButton>
+ );
+};
diff --git a/frontend/src/metabase/metabot/components/AIAnalysisContentWrapper/AIAnalysisContentWrapper.tsx b/frontend/src/metabase/metabot/components/AIAnalysisContentWrapper/AIAnalysisContentWrapper.tsx
index 39f6120f785..d26d607af82 100644
--- a/frontend/src/metabase/metabot/components/AIAnalysisContentWrapper/AIAnalysisContentWrapper.tsx
+++ b/frontend/src/metabase/metabot/components/AIAnalysisContentWrapper/AIAnalysisContentWrapper.tsx
@@ -1,6 +1,7 @@
import { t } from "ttag";
import { CopyButton } from "metabase/common/components/CopyButton";
+import { MetabotIcon } from "metabase/metabot/components/MetabotIcon";
import { Button, Flex, Group, Icon, Stack, Text } from "metabase/ui";
import { AIAnalysisContent } from "../AIAnalysisContent/AIAnalysisContent";
@@ -22,7 +23,7 @@ export function AIAnalysisContentWrapper({
<Stack h="100%" p="lg" style={{ overflowY: "auto" }}>
<Group justify="space-between" align="center">
<Flex align="center" gap="xs">
- <Icon name="metabot" />
+ <MetabotIcon />
<Text fz="1.17em" ml="xs" fw="bold">
{title}
</Text>
diff --git a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.tsx b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.tsx
index 04691b15920..343e6d8aff6 100644
--- a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.tsx
+++ b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.tsx
@@ -3,16 +3,16 @@ import { t } from "ttag";
import { ToolbarButton } from "metabase/common/components/ToolbarButton";
import {
useMetabotAgent,
- useMetabotEnabledEmbeddingAware,
+ useUserMetabotPermissions,
} from "metabase/metabot/hooks";
import { trackExplainChartClicked } from "../analytics";
export const AIQuestionAnalysisButton = () => {
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseMetabot } = useUserMetabotPermissions();
const { submitInput } = useMetabotAgent("omnibot");
- if (!isMetabotEnabled) {
+ if (!canUseMetabot) {
return null;
}
diff --git a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx
index 409789d133d..173fd1bc1ef 100644
--- a/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/AIQuestionAnalysisButton.unit.spec.tsx
@@ -1,6 +1,7 @@
import userEvent from "@testing-library/user-event";
import { setupEnterprisePlugins } from "__support__/enterprise";
+import { setupUserMetabotPermissionsEndpoint } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import { mockStreamedEndpoint } from "metabase/api/ai-streaming/test-utils";
@@ -26,6 +27,7 @@ function setup({
"metabot-enabled?": isMetabotEnabled,
});
+ setupUserMetabotPermissionsEndpoint();
setupEnterprisePlugins();
const metabotState = getMetabotInitialState();
@@ -44,10 +46,10 @@ function setup({
}
describe("AIQuestionAnalysisButton", () => {
- it("should render the button when metabot is enabled", () => {
+ it("should render the button when metabot is enabled", async () => {
setup({ isMetabotEnabled: true });
expect(
- screen.getByRole("button", { name: "Explain this chart" }),
+ await screen.findByRole("button", { name: "Explain this chart" }),
).toBeInTheDocument();
});
@@ -63,7 +65,7 @@ describe("AIQuestionAnalysisButton", () => {
setup({ isMetabotEnabled: true });
await userEvent.click(
- screen.getByRole("button", { name: "Explain this chart" }),
+ await screen.findByRole("button", { name: "Explain this chart" }),
);
await waitFor(() => expect(agentSpy).toHaveBeenCalled());
diff --git a/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.tsx b/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.tsx
index 308cb570003..67354c7bca7 100644
--- a/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.tsx
+++ b/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.tsx
@@ -3,7 +3,8 @@ import { t } from "ttag";
import { useDispatch } from "metabase/lib/redux";
import {
useMetabotAgent,
- useMetabotEnabledEmbeddingAware,
+ useMetabotName,
+ useUserMetabotPermissions,
} from "metabase/metabot/hooks";
import { setIsNativeEditorOpen } from "metabase/query_builder/actions";
import { Button } from "metabase/ui";
@@ -12,10 +13,11 @@ import { trackQueryFixClicked } from "../../analytics";
export function FixSqlQueryButton() {
const dispatch = useDispatch();
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseSqlGeneration } = useUserMetabotPermissions();
+ const metabotName = useMetabotName();
const { submitInput, isDoingScience } = useMetabotAgent("sql");
- if (!isMetabotEnabled) {
+ if (!canUseSqlGeneration) {
return null;
}
@@ -30,6 +32,6 @@ export function FixSqlQueryButton() {
<Button
loading={isDoingScience}
onClick={handleClick}
- >{t`Have Metabot fix it`}</Button>
+ >{t`Have ${metabotName} fix it`}</Button>
);
}
diff --git a/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.unit.spec.tsx
index dbc8d430e18..96fd4bbd868 100644
--- a/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/FixSqlQueryButton/FixSqlQueryButton.unit.spec.tsx
@@ -4,7 +4,7 @@ import { renderWithProviders, screen } from "__support__/ui";
import { useDispatch } from "metabase/lib/redux";
import {
useMetabotAgent,
- useMetabotEnabledEmbeddingAware,
+ useUserMetabotPermissions,
} from "metabase/metabot/hooks";
import { setIsNativeEditorOpen } from "metabase/query_builder/actions";
@@ -28,7 +28,7 @@ jest.mock("metabase/lib/redux", () => ({
jest.mock("metabase/metabot/hooks", () => ({
...jest.requireActual("metabase/metabot/hooks"),
useMetabotAgent: jest.fn(),
- useMetabotEnabledEmbeddingAware: jest.fn(),
+ useUserMetabotPermissions: jest.fn(),
}));
jest.mock("metabase/query_builder/actions", () => ({
@@ -42,9 +42,14 @@ function setup(options?: {
}) {
const { isMetabotEnabled = true, isDoingScience = false } = options ?? {};
- jest
- .mocked(useMetabotEnabledEmbeddingAware)
- .mockReturnValue(isMetabotEnabled);
+ jest.mocked(useUserMetabotPermissions).mockReturnValue({
+ isLoading: false,
+ isError: false,
+ canUseMetabot: isMetabotEnabled,
+ canUseSqlGeneration: isMetabotEnabled,
+ canUseNlq: isMetabotEnabled,
+ canUseOtherTools: isMetabotEnabled,
+ });
jest.mocked(useMetabotAgent).mockReturnValue({
submitInput: mockSubmitInput,
isDoingScience,
diff --git a/frontend/src/metabase/metabot/components/Metabot.tsx b/frontend/src/metabase/metabot/components/Metabot.tsx
index 023074de06e..c425a2a686e 100644
--- a/frontend/src/metabase/metabot/components/Metabot.tsx
+++ b/frontend/src/metabase/metabot/components/Metabot.tsx
@@ -7,7 +7,7 @@ import ErrorBoundary from "metabase/ErrorBoundary";
import { useSelector } from "metabase/lib/redux";
import {
useMetabotAgent,
- useMetabotEnabledEmbeddingAware,
+ useUserMetabotPermissions,
} from "metabase/metabot/hooks";
import { Sidebar } from "metabase/nav/containers/MainNavbar/MainNavbar.styled";
import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";
@@ -111,12 +111,12 @@ export const MetabotAuthenticated = ({ hide, config }: MetabotProps) => {
export const Metabot = (props: MetabotProps) => {
const currentUser = useSelector(getUser);
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseMetabot } = useUserMetabotPermissions();
// NOTE: do not render Metabot if the user is not authenticated.
// doing so will cause a redirect for unauthenticated requests
// which will break interactive embedding. See (metabase#58687).
- if (!currentUser || !isMetabotEnabled) {
+ if (!currentUser || !canUseMetabot) {
return null;
}
diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx
index f33908fc80e..5562883f68d 100644
--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.tsx
@@ -7,6 +7,7 @@ import {
import { useSetting } from "metabase/common/hooks";
import { FIXED_METABOT_IDS } from "metabase/metabot/constants";
import {
+ PLUGIN_AI_CONTROLS,
PLUGIN_EMBEDDING_IFRAME_SDK,
PLUGIN_EMBEDDING_SDK,
} from "metabase/plugins";
@@ -39,6 +40,7 @@ export function MetabotNavPane() {
path={`/admin/metabot/${FIXED_METABOT_IDS.EMBEDDED}`}
/>
)}
+ {PLUGIN_AI_CONTROLS.getAiControlsNavItems()}
</>
)}
<AdminNavItem
diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.unit.spec.tsx
index 6db58dc2ef6..5676c898a6c 100644
--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotNavPane.unit.spec.tsx
@@ -75,4 +75,42 @@ describe("MetabotNavPane", () => {
expect(await screen.findByText("Metabot")).toBeInTheDocument();
expect(await screen.findByText("Embedded Metabot")).toBeInTheDocument();
});
+
+ it("should not show AI controls nav items by default", async () => {
+ setup({ isConfigured: true });
+
+ expect(await screen.findByText("Metabot")).toBeInTheDocument();
+ expect(screen.queryByText("Usage controls")).not.toBeInTheDocument();
+ expect(screen.queryByText("Customization")).not.toBeInTheDocument();
+ expect(screen.queryByText("System prompts")).not.toBeInTheDocument();
+ });
+
+ it("should show AI controls nav items when ai_controls plugin is enabled", async () => {
+ mockSettings({
+ "token-features": createMockTokenFeatures({
+ ai_controls: true,
+ }),
+ });
+ setupEnterprisePlugins();
+ setup({ isConfigured: true });
+
+ expect(await screen.findByText("Metabot")).toBeInTheDocument();
+ expect(screen.getByText("Usage controls")).toBeInTheDocument();
+ expect(screen.getByText("Customization")).toBeInTheDocument();
+ expect(screen.getByText("System prompts")).toBeInTheDocument();
+ });
+
+ it("should not show AI controls nav items when metabot is not configured", async () => {
+ mockSettings({
+ "token-features": createMockTokenFeatures({
+ ai_controls: true,
+ }),
+ });
+ setupEnterprisePlugins();
+ setup({ isConfigured: false });
+
+ expect(screen.queryByText("Usage controls")).not.toBeInTheDocument();
+ expect(screen.queryByText("Customization")).not.toBeInTheDocument();
+ expect(screen.queryByText("System prompts")).not.toBeInTheDocument();
+ });
});
diff --git a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotAdminPage.tsx b/frontend/src/metabase/metabot/components/MetabotAdmin/routes.tsx
similarity index 80%
rename from frontend/src/metabase/metabot/components/MetabotAdmin/MetabotAdminPage.tsx
rename to frontend/src/metabase/metabot/components/MetabotAdmin/routes.tsx
index f2135545c66..8524bc83d33 100644
--- a/frontend/src/metabase/metabot/components/MetabotAdmin/MetabotAdminPage.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotAdmin/routes.tsx
@@ -1,17 +1,20 @@
import { IndexRoute, Route } from "react-router";
+import { PLUGIN_AI_CONTROLS } from "metabase/plugins";
+
import { McpAppsSettings } from "./McpAppsSettings";
import { MetabotAdminLayout } from "./MetabotAdminLayout";
import { MetabotConfig } from "./MetabotConfig";
import { MetabotSetup } from "./MetabotSetup";
-export function getAdminRoutes() {
+export function getMetabotAdminRoutes() {
return [
<Route key="layout" component={MetabotAdminLayout}>
<IndexRoute key="index" component={MetabotConfig} />
<Route key="setup" path="setup" component={MetabotSetup} />
<Route key="mcp" path="mcp" component={McpAppsSettings} />,
<Route key="metabot" path=":metabotId" component={MetabotConfig} />
+ {PLUGIN_AI_CONTROLS.getAiControlsRoutes()}
</Route>,
];
}
diff --git a/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx b/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx
index dd31f128573..c6cec87cd08 100644
--- a/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotAppBarButton.tsx
@@ -3,12 +3,15 @@ import { t } from "ttag";
import { METAKEY } from "metabase/lib/browser";
import {
useMetabotAgent,
- useMetabotEnabledEmbeddingAware,
+ useMetabotName,
+ useUserMetabotPermissions,
} from "metabase/metabot/hooks";
-import { ActionIcon, type ActionIconProps, Icon, Tooltip } from "metabase/ui";
+import { ActionIcon, type ActionIconProps, Tooltip } from "metabase/ui";
import { trackMetabotChatOpened } from "../analytics";
+import { MetabotIcon } from "./MetabotIcon";
+
interface MetabotAppBarButtonProps extends ActionIconProps {
className?: string;
}
@@ -17,10 +20,11 @@ export function MetabotAppBarButton({
className,
...rest
}: MetabotAppBarButtonProps) {
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseMetabot } = useUserMetabotPermissions();
const metabot = useMetabotAgent("omnibot");
+ const metabotName = useMetabotName();
- if (!isMetabotEnabled) {
+ if (!canUseMetabot) {
return null;
}
@@ -32,7 +36,7 @@ export function MetabotAppBarButton({
metabot.setVisible(!metabot.visible);
};
- const label = t`Chat with Metabot (${METAKEY}+E)`;
+ const label = t`Chat with ${metabotName} (${METAKEY}+E)`;
return (
<Tooltip label={label}>
@@ -48,7 +52,7 @@ export function MetabotAppBarButton({
onClick={handleClick}
{...rest}
>
- <Icon name="metabot" />
+ <MetabotIcon />
</ActionIcon>
</Tooltip>
);
diff --git a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx
index caa9a064e78..11835549628 100644
--- a/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotAppBarButton.unit.spec.tsx
@@ -1,8 +1,11 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { setupEnterprisePlugins } from "__support__/enterprise";
import { mockSettings } from "__support__/settings";
-import { renderWithProviders, screen } from "__support__/ui";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { UserMetabotPermissions } from "metabase-types/api";
+import { createMockUserMetabotPermissions } from "metabase-types/api/mocks";
import { createMockState } from "metabase-types/store/mocks";
import { MetabotProvider } from "../context";
@@ -11,7 +14,16 @@ import { MetabotAppBarButton } from "./MetabotAppBarButton";
function setup({
isMetabotEnabled = true,
-}: { isMetabotEnabled?: boolean } = {}) {
+ permissionOverrides,
+}: {
+ isMetabotEnabled?: boolean;
+ permissionOverrides?: Partial<UserMetabotPermissions>;
+} = {}) {
+ fetchMock.get(
+ "path:/api/metabot/permissions/user-permissions",
+ createMockUserMetabotPermissions(permissionOverrides),
+ );
+
const settings = mockSettings({
"llm-metabot-configured?": true,
"metabot-enabled?": isMetabotEnabled,
@@ -33,20 +45,31 @@ function setup({
}
describe("MetabotAppBarButton", () => {
- it("should render the button when metabot is enabled", () => {
+ it("should render the button when metabot is enabled", async () => {
setup({ isMetabotEnabled: true });
expect(
- screen.getByRole("button", { name: /Chat with Metabot/ }),
+ await screen.findByRole("button", { name: /Chat with Metabot/ }),
).toBeInTheDocument();
});
- it("should not render the button when metabot is disabled", () => {
+ it("should not render the button when metabot is globally disabled", () => {
setup({ isMetabotEnabled: false });
expect(
screen.queryByRole("button", { name: /Chat with Metabot/ }),
).not.toBeInTheDocument();
});
+ it("should not render the button when user lacks metabot permission", async () => {
+ setup({ permissionOverrides: { metabot: "no" } });
+ // Wait for the API response to be processed
+ await waitFor(() => {
+ expect(fetchMock.callHistory.calls().length).toBeGreaterThan(0);
+ });
+ expect(
+ screen.queryByRole("button", { name: /Chat with Metabot/ }),
+ ).not.toBeInTheDocument();
+ });
+
it("should toggle metabot visibility when clicked", async () => {
const { store } = setup({ isMetabotEnabled: true });
@@ -54,7 +77,7 @@ describe("MetabotAppBarButton", () => {
expect(initialState.metabot.conversations.omnibot.visible).toBe(false);
await userEvent.click(
- screen.getByRole("button", { name: /Chat with Metabot/ }),
+ await screen.findByRole("button", { name: /Chat with Metabot/ }),
);
const newState = store.getState() as any;
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx
index e42a03846bf..f6ac39c0073 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChat.tsx
@@ -4,6 +4,7 @@ import { t } from "ttag";
import EmptyDashboardBot from "assets/img/dashboard-empty.svg?component";
import { useGetSuggestedMetabotPromptsQuery } from "metabase/api";
+import { useSetting } from "metabase/common/hooks";
import { useSelector } from "metabase/lib/redux";
import { MetabotResetLongChatButton } from "metabase/metabot/components/MetabotChat/MetabotResetLongChatButton";
import { getIsHosted } from "metabase/setup/selectors";
@@ -19,7 +20,7 @@ import {
Tooltip,
} from "metabase/ui";
-import { useMetabotAgent } from "../../hooks";
+import { useMetabotAgent, useMetabotName } from "../../hooks";
import type { MetabotConfig } from "../Metabot";
import Styles from "./MetabotChat.module.css";
@@ -47,6 +48,8 @@ export const MetabotChat = ({
}) => {
const isHosted = useSelector(getIsHosted);
const metabot = useMetabotAgent(config.agentId);
+ const metabotName = useMetabotName();
+ const showIllustrations = useSetting("metabot-show-illustrations");
const hasMessages =
metabot.messages.length > 0 || metabot.errorMessages.length > 0;
@@ -81,7 +84,7 @@ export const MetabotChat = ({
<Box ref={headerRef} className={Styles.header}>
<Flex align-items="center">
<Text lh={1} fz="sm" c="text-secondary">
- {t`Metabot isn't perfect. Double-check results.`}
+ {t`${metabotName} isn't perfect. Double-check results.`}
</Text>
</Flex>
@@ -119,7 +122,9 @@ export const MetabotChat = ({
justify="center"
data-testid="metabot-empty-chat-info"
>
- <Box component={EmptyDashboardBot} w="6rem" />
+ {showIllustrations && (
+ <Box component={EmptyDashboardBot} w="6rem" />
+ )}
<Text c="text-tertiary" maw="12rem" ta="center" lh="lg">
{config.emptyText ??
t`I can help you explore your metrics and models.`}
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx
index 5245a24c377..c7388a0f231 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatEditor/MetabotChatEditor.tsx
@@ -2,6 +2,7 @@ import cx from "classnames";
import { forwardRef } from "react";
import type { MetabotPromptInputRef } from "metabase/metabot";
+import { MetabotIcon } from "metabase/metabot/components/MetabotIcon";
import {
MetabotPromptInput,
type MetabotPromptInputProps,
@@ -28,7 +29,7 @@ export const MetabotChatEditor = forwardRef<
return (
<Box className={S.editorContainer}>
<Box className={S.iconContainer}>
- <Icon name="metabot" c="brand" />
+ <MetabotIcon c="brand" />
</Box>
<Box className={S.contentWrapper}>
<MetabotPromptInput
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotFeedbackModal.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotFeedbackModal.tsx
index 1dd6210a7ed..d222df8696a 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotFeedbackModal.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotFeedbackModal.tsx
@@ -8,6 +8,7 @@ import { FormSelect } from "metabase/forms/components/FormSelect";
import { FormTextarea } from "metabase/forms/components/FormTextarea";
import * as Errors from "metabase/lib/errors";
import { useSelector } from "metabase/lib/redux";
+import { useMetabotName } from "metabase/metabot/hooks";
import { getMetabotId, getMetabotState } from "metabase/metabot/state";
import { getUserIsAdmin } from "metabase/selectors/user";
import { getApplicationName } from "metabase/selectors/whitelabel";
@@ -64,6 +65,7 @@ export const MetabotFeedbackModal = ({
const applicationName = useSelector(getApplicationName);
const isAdmin = useSelector(getUserIsAdmin);
const version = useSetting("version");
+ const metabotName = useMetabotName();
const metabotId = useSelector(getMetabotId);
const metabotState = useSelector(getMetabotState);
@@ -92,7 +94,7 @@ export const MetabotFeedbackModal = ({
opened
onClose={onClose}
size="md"
- title={t`Metabot feedback`}
+ title={t`${metabotName} feedback`}
data-testid="metabot-feedback-modal"
>
<FormProvider
diff --git a/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx b/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx
index a464d9924fd..f1137c950cb 100644
--- a/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotDataStudioButton.tsx
@@ -5,19 +5,23 @@ import { useSelector } from "metabase/lib/redux";
import * as Urls from "metabase/lib/urls";
import {
useMetabotAgent,
- useMetabotEnabledEmbeddingAware,
+ useMetabotName,
+ useUserMetabotPermissions,
} from "metabase/metabot/hooks";
import { getLocation } from "metabase/selectors/routing";
-import { ActionIcon, Icon, Tooltip } from "metabase/ui";
+import { ActionIcon, Tooltip } from "metabase/ui";
import { trackMetabotChatOpened } from "../analytics";
+import { MetabotIcon } from "./MetabotIcon";
+
export const MetabotDataStudioButton = () => {
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseMetabot } = useUserMetabotPermissions();
const metabot = useMetabotAgent("omnibot");
+ const metabotName = useMetabotName();
const location = useSelector(getLocation);
- if (!isMetabotEnabled) {
+ if (!canUseMetabot) {
return null;
}
@@ -32,8 +36,8 @@ export const MetabotDataStudioButton = () => {
};
const label = disabled
- ? `Metabot can't be viewed on this page`
- : t`Chat with Metabot (${METAKEY}+E)`;
+ ? t`${metabotName} can't be viewed on this page`
+ : t`Chat with ${metabotName} (${METAKEY}+E)`;
return (
<Tooltip label={label}>
@@ -44,11 +48,7 @@ export const MetabotDataStudioButton = () => {
aria-label={label}
onClick={handleClick}
>
- <Icon
- c={disabled ? undefined : "text-primary"}
- name="metabot"
- size={16}
- />
+ <MetabotIcon c={disabled ? undefined : "text-primary"} size={16} />
</ActionIcon>
</Tooltip>
);
diff --git a/frontend/src/metabase/metabot/components/MetabotIcon/MetabotIcon.tsx b/frontend/src/metabase/metabot/components/MetabotIcon/MetabotIcon.tsx
new file mode 100644
index 00000000000..62cbb958303
--- /dev/null
+++ b/frontend/src/metabase/metabot/components/MetabotIcon/MetabotIcon.tsx
@@ -0,0 +1,43 @@
+import { forwardRef } from "react";
+
+import { useSetting } from "metabase/common/hooks";
+import { useMetabotName } from "metabase/metabot/hooks";
+import { Box, type BoxProps, Icon } from "metabase/ui";
+
+export interface MetabotIconProps extends BoxProps {
+ size?: number;
+}
+
+/**
+ * Renders the metabot icon — either the default built-in SVG icon
+ * or a custom uploaded image from the "metabot-icon" setting.
+ */
+export const MetabotIcon = forwardRef<HTMLImageElement, MetabotIconProps>(
+ function MetabotIcon({ size = 16, ...rest }, ref) {
+ const metabotIcon = useSetting("metabot-icon");
+ const metabotName = useMetabotName();
+
+ const isCustomIcon = metabotIcon && metabotIcon !== "metabot";
+
+ if (isCustomIcon) {
+ return (
+ <Box
+ component="img"
+ ref={ref}
+ src={metabotIcon}
+ alt={metabotName}
+ w={size}
+ h={size}
+ style={{ objectFit: "contain" }}
+ {...rest}
+ />
+ );
+ }
+
+ return (
+ <Box component="span" display="inline-flex" {...rest}>
+ <Icon name="metabot" size={size} />
+ </Box>
+ );
+ },
+);
diff --git a/frontend/src/metabase/metabot/components/MetabotIcon/index.ts b/frontend/src/metabase/metabot/components/MetabotIcon/index.ts
new file mode 100644
index 00000000000..ef539a33303
--- /dev/null
+++ b/frontend/src/metabase/metabot/components/MetabotIcon/index.ts
@@ -0,0 +1,2 @@
+export { MetabotIcon } from "./MetabotIcon";
+export type { MetabotIconProps } from "./MetabotIcon";
diff --git a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx
index 77bb8249ef8..9d648f13602 100644
--- a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/MetabotInlineSQLPrompt.tsx
@@ -4,6 +4,7 @@ import { t } from "ttag";
import type { MetabotPromptInputRef } from "metabase/metabot";
import { MetabotPromptInput } from "metabase/metabot/components/MetabotPromptInput";
+import { useMetabotName } from "metabase/metabot/hooks";
import type { SuggestionModel } from "metabase/rich_text_editing/tiptap/extensions/shared/types";
import { Box, Button, Flex, Icon, Loader, Tooltip } from "metabase/ui";
import type { DatabaseId } from "metabase-types/api";
@@ -36,6 +37,7 @@ export const MetabotInlineSQLPrompt = ({
onValueChange,
}: MetabotInlineSQLPromptProps) => {
const promptInputRef = useRef<MetabotPromptInputRef>(null);
+ const metabotName = useMetabotName();
const isSubmitDisabled = !value.trim() || isLoading;
@@ -90,7 +92,7 @@ export const MetabotInlineSQLPrompt = ({
{error}
</Box>
<Flex gap="xs" flex="1 0 auto">
- <Tooltip disabled={isLoading} label={t`Send to Metabot`}>
+ <Tooltip disabled={isLoading} label={t`Send to ${metabotName}`}>
<Button
className={S.submitButton}
data-testid="metabot-inline-sql-generate"
diff --git a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx
index 67eeb1d3e33..7b7bef19c58 100644
--- a/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotInlineSQLPrompt/useInlineSQLPrompt.tsx
@@ -12,7 +12,7 @@ import {
import { createPortal } from "react-dom";
import { useRegisterMetabotContextProvider } from "metabase/metabot/context";
-import { useMetabotEnabledEmbeddingAware } from "metabase/metabot/hooks";
+import { useUserMetabotPermissions } from "metabase/metabot/hooks";
import { useMetabotSQLSuggestion } from "metabase/metabot/hooks/use-metabot-sql-suggestion";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
@@ -57,7 +57,7 @@ export function useInlineSQLPrompt(
question: Question,
bufferId: string,
): UseInlineSqlEditResult {
- const isEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseSqlGeneration: isEnabled } = useUserMetabotPermissions();
const databaseId = question.databaseId();
diff --git a/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx b/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx
index f3bd649daae..b7cf224624c 100644
--- a/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotQueryBuilder/MetabotQueryBuilder.tsx
@@ -23,7 +23,7 @@ import {
UnstyledButton,
} from "metabase/ui";
-import { useMetabotAgent, useMetabotEnabledEmbeddingAware } from "../../hooks";
+import { useMetabotAgent, useUserMetabotPermissions } from "../../hooks";
import S from "./MetabotQueryBuilder.module.css";
@@ -247,8 +247,8 @@ const MetabotQueryBuilderInner = () => {
export const MetabotQueryBuilder = (
props: React.ComponentProps<typeof QueryBuilder>,
) => {
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
- if (!isMetabotEnabled) {
+ const { canUseNlq } = useUserMetabotPermissions();
+ if (!canUseNlq) {
return <QueryBuilder {...props} />;
}
return <MetabotQueryBuilderInner />;
diff --git a/frontend/src/metabase/metabot/components/MetabotQuickLinks.tsx b/frontend/src/metabase/metabot/components/MetabotQuickLinks.tsx
index ab5b6de45b7..fc4f1f7e857 100644
--- a/frontend/src/metabase/metabot/components/MetabotQuickLinks.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotQuickLinks.tsx
@@ -1,12 +1,13 @@
+import { useEffect, useState } from "react";
import { Route } from "react-router";
import { replace } from "react-router-redux";
-import { useMount } from "react-use";
import { useDispatch } from "metabase/lib/redux";
import {
useMetabotAgent,
- useMetabotEnabledEmbeddingAware,
+ useUserMetabotPermissions,
} from "metabase/metabot/hooks";
+import { Loader } from "metabase/ui";
export const getMetabotQuickLinks = () => {
return (
@@ -14,20 +15,33 @@ export const getMetabotQuickLinks = () => {
key="metabot"
path="metabot/new"
component={(props) => {
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseMetabot, isLoading } = useUserMetabotPermissions();
const { submitInput } = useMetabotAgent("omnibot");
const prompt = String(props.location.query?.q ?? "");
const dispatch = useDispatch();
+ const [hasSubmitted, setHasSubmitted] = useState(false);
+
+ useEffect(() => {
+ if (isLoading || hasSubmitted) {
+ return;
+ }
- useMount(() => {
dispatch(replace("/"));
- if (prompt && isMetabotEnabled) {
- submitInput(prompt, { focusInput: true });
+ if (prompt && canUseMetabot) {
+ void submitInput(prompt, { focusInput: true });
+ setHasSubmitted(true);
}
- });
+ }, [
+ isLoading,
+ canUseMetabot,
+ prompt,
+ submitInput,
+ dispatch,
+ hasSubmitted,
+ ]);
- return null;
+ return <Loader m="5rem auto" display="block" size="xl" />;
}}
/>
);
diff --git a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx
index 276ffe87c6d..1a0742a57c3 100644
--- a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx
+++ b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.tsx
@@ -8,9 +8,9 @@ import type { CollectionId } from "metabase-types/api";
export function getNewMenuItemAIExploration(
hasDataAccess: boolean,
collectionId?: CollectionId,
- isMetabotEnabled?: boolean,
+ canUseNlq?: boolean,
) {
- if (!hasDataAccess || !isMetabotEnabled) {
+ if (!hasDataAccess || !canUseNlq) {
return undefined;
}
diff --git a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsx b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsx
index 5f7fb742f87..adc13297991 100644
--- a/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/NewMenuItemAIExploration.unit.spec.tsx
@@ -6,17 +6,17 @@ describe("getNewMenuItemAIExploration", () => {
expect(result).toBeUndefined();
});
- it("should return undefined when isMetabotEnabled is false", () => {
+ it("should return undefined when canUseNlq is false", () => {
const result = getNewMenuItemAIExploration(true, undefined, false);
expect(result).toBeUndefined();
});
- it("should return undefined when isMetabotEnabled is undefined", () => {
+ it("should return undefined when canUseNlq is undefined", () => {
const result = getNewMenuItemAIExploration(true, undefined, undefined);
expect(result).toBeUndefined();
});
- it("should return a Menu.Item when hasDataAccess and isMetabotEnabled are true", () => {
+ it("should return a Menu.Item when hasDataAccess and canUseNlq are true", () => {
const result = getNewMenuItemAIExploration(true, undefined, true);
expect(result).not.toBeUndefined();
expect(result?.key).toBe("nlq");
diff --git a/frontend/src/metabase/metabot/constants.ts b/frontend/src/metabase/metabot/constants.ts
index 87782196a78..a64de4a4cc7 100644
--- a/frontend/src/metabase/metabot/constants.ts
+++ b/frontend/src/metabase/metabot/constants.ts
@@ -29,8 +29,8 @@ export const METABOT_ERR_MSG = {
get default() {
return t`Sorry, I ran into an error. Could you please try that again?`;
},
- get unauthenticated() {
- return t`Metabot could not authenticate your request. Please contact your administrator.`;
+ unauthenticated(metabotName: string) {
+ return t`${metabotName} could not authenticate your request. Please contact your administrator.`;
},
format(msg: string) {
return t`Sorry, an error occurred: ${msg}. If this persists, please contact your administrator.`;
diff --git a/frontend/src/metabase/metabot/hooks/index.ts b/frontend/src/metabase/metabot/hooks/index.ts
index 04d7b341c32..1677860edd0 100644
--- a/frontend/src/metabase/metabot/hooks/index.ts
+++ b/frontend/src/metabase/metabot/hooks/index.ts
@@ -1,4 +1,6 @@
export { useMetabotEnabledEmbeddingAware } from "./use-metabot-embedding-aware-enabled";
export { useMetabotAgent } from "./use-metabot-agent";
export { useMetabotAgentsManager } from "./use-metabot-agents-manager";
+export { useMetabotName } from "./use-metabot-name";
export { useDashCardAnalysis } from "./useDashCardAnalysis";
+export { useUserMetabotPermissions } from "./use-user-metabot-permissions";
diff --git a/frontend/src/metabase/metabot/hooks/use-metabot-name.ts b/frontend/src/metabase/metabot/hooks/use-metabot-name.ts
new file mode 100644
index 00000000000..f69b9e44d08
--- /dev/null
+++ b/frontend/src/metabase/metabot/hooks/use-metabot-name.ts
@@ -0,0 +1,6 @@
+import { useSetting } from "metabase/common/hooks";
+
+/** Returns the user-configured display name for Metabot (defaults to "Metabot"). */
+export const useMetabotName = (): string => {
+ return useSetting("metabot-name") || "Metabot";
+};
diff --git a/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.ts b/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.ts
new file mode 100644
index 00000000000..855c1c646da
--- /dev/null
+++ b/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.ts
@@ -0,0 +1,32 @@
+import { useMemo } from "react";
+
+import { useGetUserMetabotPermissionsQuery } from "metabase/api";
+
+import { useMetabotEnabledEmbeddingAware } from "./use-metabot-embedding-aware-enabled";
+
+/** Returns granular metabot permission booleans for the current user.
+ * Combines the global metabot-enabled setting with per-user group permissions.
+ * Returns all false while loading or on error. */
+export const useUserMetabotPermissions = () => {
+ const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { data, isLoading, isError } = useGetUserMetabotPermissionsQuery(
+ undefined,
+ { skip: !isMetabotEnabled },
+ );
+
+ const perms = data?.permissions;
+ const hasAccess = isMetabotEnabled && !isLoading && perms?.metabot === "yes";
+
+ return useMemo(
+ () => ({
+ isLoading,
+ isError,
+ canUseMetabot: hasAccess,
+ canUseSqlGeneration:
+ hasAccess && perms?.["metabot-sql-generation"] === "yes",
+ canUseNlq: hasAccess && perms?.["metabot-nlq"] === "yes",
+ canUseOtherTools: hasAccess && perms?.["metabot-other-tools"] === "yes",
+ }),
+ [isLoading, isError, hasAccess, perms],
+ );
+};
diff --git a/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.unit.spec.tsx b/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.unit.spec.tsx
new file mode 100644
index 00000000000..48b02b7177b
--- /dev/null
+++ b/frontend/src/metabase/metabot/hooks/use-user-metabot-permissions.unit.spec.tsx
@@ -0,0 +1,142 @@
+import fetchMock from "fetch-mock";
+
+import { setupEnterprisePlugins } from "__support__/enterprise";
+import { mockSettings } from "__support__/settings";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { UserMetabotPermissionsResponse } from "metabase-types/api";
+import {
+ createMockTokenFeatures,
+ createMockUserMetabotPermissions,
+} from "metabase-types/api/mocks";
+import { createMockState } from "metabase-types/store/mocks";
+
+import { useUserMetabotPermissions } from "./use-user-metabot-permissions";
+
+function TestComponent() {
+ const perms = useUserMetabotPermissions();
+ return <div data-testid="perms">{JSON.stringify(perms)}</div>;
+}
+
+function setup({
+ isMetabotEnabled = true,
+ apiResponse,
+ apiStatus = 200,
+}: {
+ isMetabotEnabled?: boolean;
+ apiResponse?: UserMetabotPermissionsResponse;
+ apiStatus?: number;
+} = {}) {
+ if (apiStatus === 200) {
+ fetchMock.get(
+ "path:/api/metabot/permissions/user-permissions",
+ apiResponse ?? createMockUserMetabotPermissions(),
+ );
+ } else {
+ fetchMock.get("path:/api/metabot/permissions/user-permissions", apiStatus);
+ }
+
+ const settings = mockSettings({
+ "llm-metabot-configured?": true,
+ "metabot-enabled?": isMetabotEnabled,
+ "token-features": createMockTokenFeatures({ ai_controls: true }),
+ });
+ setupEnterprisePlugins();
+
+ renderWithProviders(<TestComponent />, {
+ storeInitialState: createMockState({ settings }),
+ });
+}
+
+async function getPerms() {
+ let perms: Record<string, unknown> = {};
+ await waitFor(() => {
+ const el = screen.getByTestId("perms");
+ perms = JSON.parse(el.textContent || "{}");
+ expect(perms.isLoading).toBe(false);
+ });
+ return perms;
+}
+
+describe("useUserMetabotPermissions", () => {
+ it("returns all true when metabot is enabled and all permissions are yes", async () => {
+ setup();
+ const perms = await getPerms();
+ expect(perms.canUseMetabot).toBe(true);
+ expect(perms.canUseSqlGeneration).toBe(true);
+ expect(perms.canUseNlq).toBe(true);
+ expect(perms.canUseOtherTools).toBe(true);
+ expect(perms.isError).toBe(false);
+ });
+
+ it("returns all false when metabot is globally disabled", async () => {
+ setup({ isMetabotEnabled: false });
+ const perms = await getPerms();
+ expect(perms.canUseMetabot).toBe(false);
+ expect(perms.canUseSqlGeneration).toBe(false);
+ expect(perms.canUseNlq).toBe(false);
+ expect(perms.canUseOtherTools).toBe(false);
+ });
+
+ it("returns all false when the API returns an error", async () => {
+ setup({ apiStatus: 500 });
+ await waitFor(() => {
+ const el = screen.getByTestId("perms");
+ const perms = JSON.parse(el.textContent || "{}");
+ expect(perms.isError).toBe(true);
+ });
+ const el = screen.getByTestId("perms");
+ const perms = JSON.parse(el.textContent || "{}");
+ expect(perms.canUseMetabot).toBe(false);
+ expect(perms.canUseSqlGeneration).toBe(false);
+ expect(perms.canUseNlq).toBe(false);
+ expect(perms.canUseOtherTools).toBe(false);
+ });
+
+ it("returns canUseMetabot=false when base permission is no", async () => {
+ setup({
+ apiResponse: createMockUserMetabotPermissions({ metabot: "no" }),
+ });
+ const perms = await getPerms();
+ expect(perms.canUseMetabot).toBe(false);
+ expect(perms.canUseSqlGeneration).toBe(false);
+ expect(perms.canUseNlq).toBe(false);
+ expect(perms.canUseOtherTools).toBe(false);
+ });
+
+ it("returns canUseSqlGeneration=false when sql-generation is no", async () => {
+ setup({
+ apiResponse: createMockUserMetabotPermissions({
+ "metabot-sql-generation": "no",
+ }),
+ });
+ const perms = await getPerms();
+ expect(perms.canUseMetabot).toBe(true);
+ expect(perms.canUseSqlGeneration).toBe(false);
+ expect(perms.canUseNlq).toBe(true);
+ expect(perms.canUseOtherTools).toBe(true);
+ });
+
+ it("returns canUseNlq=false when nlq is no", async () => {
+ setup({
+ apiResponse: createMockUserMetabotPermissions({ "metabot-nlq": "no" }),
+ });
+ const perms = await getPerms();
+ expect(perms.canUseMetabot).toBe(true);
+ expect(perms.canUseSqlGeneration).toBe(true);
+ expect(perms.canUseNlq).toBe(false);
+ expect(perms.canUseOtherTools).toBe(true);
+ });
+
+ it("returns canUseOtherTools=false when other-tools is no", async () => {
+ setup({
+ apiResponse: createMockUserMetabotPermissions({
+ "metabot-other-tools": "no",
+ }),
+ });
+ const perms = await getPerms();
+ expect(perms.canUseMetabot).toBe(true);
+ expect(perms.canUseSqlGeneration).toBe(true);
+ expect(perms.canUseNlq).toBe(true);
+ expect(perms.canUseOtherTools).toBe(false);
+ });
+});
diff --git a/frontend/src/metabase/metabot/state/actions.ts b/frontend/src/metabase/metabot/state/actions.ts
index 049ac78ee59..c606288dafc 100644
--- a/frontend/src/metabase/metabot/state/actions.ts
+++ b/frontend/src/metabase/metabot/state/actions.ts
@@ -12,6 +12,7 @@ import { isEmbeddingSdk } from "metabase/embedding-sdk/config";
import { createAsyncThunk } from "metabase/lib/redux";
import { addUndo } from "metabase/redux/undo";
import { getIsWorkspace } from "metabase/selectors/routing";
+import { getSetting } from "metabase/selectors/settings";
import { getUser } from "metabase/selectors/user";
import type {
JSONValue,
@@ -74,7 +75,10 @@ type PromptErrorOutcome = {
shouldRetry: boolean;
};
-const handleResponseError = (error: unknown): PromptErrorOutcome => {
+const handleResponseError = (
+ error: unknown,
+ metabotName: string,
+): PromptErrorOutcome => {
return match(error)
.with({ name: "AbortError" }, () => ({
errorMessage: false as const,
@@ -86,7 +90,7 @@ const handleResponseError = (error: unknown): PromptErrorOutcome => {
() => ({
errorMessage: {
type: "alert" as const,
- message: METABOT_ERR_MSG.unauthenticated,
+ message: METABOT_ERR_MSG.unauthenticated(metabotName),
},
shouldRetry: true,
}),
@@ -411,7 +415,13 @@ export const sendAgentRequest = createAsyncThunk<
});
} catch (error) {
console.error(error);
- return rejectWithValue({ type: "error", ...handleResponseError(error) });
+ return rejectWithValue({
+ type: "error",
+ ...handleResponseError(
+ error,
+ getSetting(getState(), "metabot-name") || "Metabot",
+ ),
+ });
}
},
);
diff --git a/frontend/src/metabase/metabot/tests/context.unit.spec.tsx b/frontend/src/metabase/metabot/tests/context.unit.spec.tsx
index c0ebc0c3710..f000764a7e5 100644
--- a/frontend/src/metabase/metabot/tests/context.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/context.unit.spec.tsx
@@ -11,6 +11,7 @@ import { setIsNativeEditorOpen } from "metabase/query_builder/actions";
import {
createMockDatabase,
createMockUser,
+ createMockUserMetabotPermissions,
createMockUserPermissions,
} from "metabase-types/api/mocks";
@@ -25,11 +26,6 @@ import {
whoIsYourFavoriteResponse,
} from "./utils";
-jest.mock("metabase/metabot/hooks", () => ({
- ...jest.requireActual("metabase/metabot/hooks"),
- useMetabotEnabledEmbeddingAware: () => true,
-}));
-
jest.mock("metabase/query_builder/actions", () => ({
...jest.requireActual("metabase/query_builder/actions"),
setIsNativeEditorOpen: jest.fn(),
@@ -38,6 +34,10 @@ jest.mock("metabase/query_builder/actions", () => ({
describe("metabot > context", () => {
beforeEach(() => {
jest.clearAllMocks();
+ fetchMock.get(
+ "path:/api/metabot/permissions/user-permissions",
+ createMockUserMetabotPermissions(),
+ );
jest.mocked(setIsNativeEditorOpen).mockImplementation(
(isNativeEditorOpen: boolean) =>
({
diff --git a/frontend/src/metabase/metabot/tests/error-boundary.unit.spec.tsx b/frontend/src/metabase/metabot/tests/error-boundary.unit.spec.tsx
index 8bb03214589..c6869b42dd0 100644
--- a/frontend/src/metabase/metabot/tests/error-boundary.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/error-boundary.unit.spec.tsx
@@ -5,7 +5,10 @@ import { assocIn } from "icepick";
import { setupEnterprisePlugins } from "__support__/enterprise";
import { mockSettings } from "__support__/settings";
import { renderWithProviders, screen } from "__support__/ui";
-import { createMockUser } from "metabase-types/api/mocks";
+import {
+ createMockUser,
+ createMockUserMetabotPermissions,
+} from "metabase-types/api/mocks";
import { createMockState } from "metabase-types/store/mocks";
import { Metabot } from "../components/Metabot";
@@ -45,6 +48,10 @@ function setup() {
`path:/api/metabot/metabot/${FIXED_METABOT_IDS.DEFAULT}/prompt-suggestions`,
{ prompts: [], offset: 0, limit: 3, total: 0 },
);
+ fetchMock.get(
+ "path:/api/metabot/permissions/user-permissions",
+ createMockUserMetabotPermissions(),
+ );
renderWithProviders(
<MetabotProvider>
diff --git a/frontend/src/metabase/metabot/tests/errors.unit.spec.tsx b/frontend/src/metabase/metabot/tests/errors.unit.spec.tsx
index 1c2826428fc..b2a17ac8dc5 100644
--- a/frontend/src/metabase/metabot/tests/errors.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/errors.unit.spec.tsx
@@ -37,7 +37,7 @@ describe("metabot > errors", () => {
await assertConversation([
["user", "Who is your favorite?"],
- ["agent", METABOT_ERR_MSG.unauthenticated],
+ ["agent", METABOT_ERR_MSG.unauthenticated("Metabot")],
]);
expect(await input()).toHaveTextContent("Who is your favorite?");
});
diff --git a/frontend/src/metabase/metabot/tests/utils.tsx b/frontend/src/metabase/metabot/tests/utils.tsx
index b0f06c3c961..d4d3c5beaf5 100644
--- a/frontend/src/metabase/metabot/tests/utils.tsx
+++ b/frontend/src/metabase/metabot/tests/utils.tsx
@@ -20,7 +20,10 @@ import {
mockStreamedEndpoint,
} from "metabase/api/ai-streaming/test-utils";
import type { User } from "metabase-types/api";
-import { createMockUser } from "metabase-types/api/mocks";
+import {
+ createMockUser,
+ createMockUserMetabotPermissions,
+} from "metabase-types/api/mocks";
import type { State } from "metabase-types/store";
import { createMockState } from "metabase-types/store/mocks";
@@ -170,6 +173,10 @@ export function setup(
`path:/api/metabot/metabot/${FIXED_METABOT_IDS.DEFAULT}/prompt-suggestions`,
{ prompts: promptSuggestions, offset: 0, limit: 3, total: 3 },
);
+ fetchMock.get(
+ "path:/api/metabot/permissions/user-permissions",
+ createMockUserMetabotPermissions(),
+ );
setupDatabaseListEndpoint([]);
const { store, rerender } = renderWithProviders(
diff --git a/frontend/src/metabase/nav/components/AppBar/AppBar.unit.spec.tsx b/frontend/src/metabase/nav/components/AppBar/AppBar.unit.spec.tsx
index 8d6c1ffadfa..edb997ceb77 100644
--- a/frontend/src/metabase/nav/components/AppBar/AppBar.unit.spec.tsx
+++ b/frontend/src/metabase/nav/components/AppBar/AppBar.unit.spec.tsx
@@ -1,3 +1,4 @@
+import { setupUserMetabotPermissionsEndpoint } from "__support__/server-mocks";
import {
createMockMediaQueryList,
renderWithProviders,
@@ -26,6 +27,7 @@ describe("AppBar", () => {
let matchMediaSpy: jest.SpyInstance;
beforeEach(() => {
+ setupUserMetabotPermissionsEndpoint();
matchMediaSpy = jest.spyOn(window, "matchMedia");
});
diff --git a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx
index 774f0627b08..76134944e08 100644
--- a/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx
+++ b/frontend/src/metabase/nav/components/AppBar/AppBarLarge.tsx
@@ -3,7 +3,7 @@ import { t } from "ttag";
import { Nav as DetailViewNav } from "metabase/detail-view/components";
import { DETAIL_VIEW_PADDING_LEFT } from "metabase/detail-view/constants";
import { MetabotAppBarButton } from "metabase/metabot/components/MetabotAppBarButton";
-import { useMetabotEnabledEmbeddingAware } from "metabase/metabot/hooks";
+import { useUserMetabotPermissions } from "metabase/metabot/hooks";
import { PLUGIN_REMOTE_SYNC } from "metabase/plugins";
import { Box, Flex } from "metabase/ui";
import type { CollectionId } from "metabase-types/api";
@@ -59,7 +59,7 @@ const AppBarLarge = ({
const { isVisible: isGitSyncVisible } =
PLUGIN_REMOTE_SYNC.useGitSyncVisible();
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseMetabot: isMetabotEnabled } = useUserMetabotPermissions();
return (
<AppBarRoot
diff --git a/frontend/src/metabase/nav/containers/AppBar/AppBar.unit.spec.tsx b/frontend/src/metabase/nav/containers/AppBar/AppBar.unit.spec.tsx
index 6d97817a200..e5f1d03432c 100644
--- a/frontend/src/metabase/nav/containers/AppBar/AppBar.unit.spec.tsx
+++ b/frontend/src/metabase/nav/containers/AppBar/AppBar.unit.spec.tsx
@@ -7,6 +7,7 @@ import {
setupCollectionByIdEndpoint,
setupCollectionsEndpoints,
setupDashboardEndpoints,
+ setupUserMetabotPermissionsEndpoint,
} from "__support__/server-mocks";
import { renderWithProviders } from "__support__/ui";
import { DEFAULT_INTERACTIVE_EMBEDDING_OPTIONS } from "metabase/redux/embed";
@@ -277,6 +278,7 @@ function setup({
// Need to set the location because CollectionBreadcrumbs uses the useLocation()
window.history.pushState({}, "", initialRoute);
+ setupUserMetabotPermissionsEndpoint();
setupCollectionsEndpoints({
collections: [FOO_COLLECTION],
});
diff --git a/frontend/src/metabase/plugins/index.ts b/frontend/src/metabase/plugins/index.ts
index e72f1b6120b..d7a7218f43c 100644
--- a/frontend/src/metabase/plugins/index.ts
+++ b/frontend/src/metabase/plugins/index.ts
@@ -145,6 +145,7 @@ export {
PLUGIN_WRITABLE_CONNECTION,
type WritableConnectionInfoSectionProps,
} from "./oss/writable-connection";
+export { PLUGIN_AI_CONTROLS, type AiControlsPlugin } from "./oss/ai-controls";
export { PLUGIN_SUPPORT } from "./oss/support";
export { PLUGIN_TENANTS } from "./oss/tenants";
@@ -159,6 +160,7 @@ export type {
// Export a single reinitialize function that calls all individual reinitialize functions
import { reinitialize as reinitializeNotificationsSdk } from "../../embedding-sdk-bundle/components/public/notifications";
+import { reinitialize as reinitializeAiControls } from "./oss/ai-controls";
import { reinitialize as reinitializeApi } from "./oss/api";
import { reinitialize as reinitializeAudit } from "./oss/audit";
import { reinitialize as reinitializeAuth } from "./oss/auth";
@@ -199,6 +201,7 @@ import { reinitialize as reinitializeWritableConnection } from "./oss/writable-c
export function reinitialize() {
reinitializeNotificationsSdk();
+ reinitializeAiControls();
reinitializeApi();
reinitializeAudit();
reinitializeAuth();
diff --git a/frontend/src/metabase/plugins/oss/ai-controls.ts b/frontend/src/metabase/plugins/oss/ai-controls.ts
new file mode 100644
index 00000000000..b6009db7c43
--- /dev/null
+++ b/frontend/src/metabase/plugins/oss/ai-controls.ts
@@ -0,0 +1,22 @@
+import type { ReactNode } from "react";
+
+export type AiControlsPlugin = {
+ isEnabled: boolean;
+ getAiControlsRoutes: () => ReactNode;
+ getAiControlsNavItems: () => ReactNode;
+};
+
+const getDefaultPluginAiControls = (): AiControlsPlugin => ({
+ isEnabled: false,
+ getAiControlsRoutes: () => null,
+ getAiControlsNavItems: () => null,
+});
+
+export const PLUGIN_AI_CONTROLS = getDefaultPluginAiControls();
+
+/**
+ * @internal Do not call directly. Use the main reinitialize function from metabase/plugins instead.
+ */
+export function reinitialize() {
+ Object.assign(PLUGIN_AI_CONTROLS, getDefaultPluginAiControls());
+}
diff --git a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.unit.spec.tsx b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.unit.spec.tsx
index 341505a2f59..ff2f1c717aa 100644
--- a/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/components/DatasetEditor/DatasetQueryEditor.unit.spec.tsx
@@ -4,6 +4,7 @@ import {
setupCollectionsEndpoints,
setupDatabasesEndpoints,
setupNativeQuerySnippetEndpoints,
+ setupUserMetabotPermissionsEndpoint,
} from "__support__/server-mocks";
import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders, screen } from "__support__/ui";
@@ -46,6 +47,7 @@ const setup = async ({
isActive,
readOnly = false,
}: SetupOpts) => {
+ setupUserMetabotPermissionsEndpoint();
setupDatabasesEndpoints([TEST_DB]);
setupCollectionsEndpoints({ collections: [ROOT_COLLECTION] });
setupNativeQuerySnippetEndpoints();
diff --git a/frontend/src/metabase/query_builder/containers/test-utils.tsx b/frontend/src/metabase/query_builder/containers/test-utils.tsx
index ed1335620a7..ee2594459e3 100644
--- a/frontend/src/metabase/query_builder/containers/test-utils.tsx
+++ b/frontend/src/metabase/query_builder/containers/test-utils.tsx
@@ -23,6 +23,7 @@ import {
setupRecentViewsEndpoints,
setupSearchEndpoints,
setupTimelinesEndpoints,
+ setupUserMetabotPermissionsEndpoint,
} from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import {
@@ -242,6 +243,7 @@ export const setup = async ({
: `#${serializeCardForUrl(card)}`
}`,
}: SetupOpts) => {
+ setupUserMetabotPermissionsEndpoint();
setupDatabasesEndpoints([TEST_DB]);
setupCardDataset({ dataset });
setupSearchEndpoints([]);
diff --git a/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.tsx b/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.tsx
index d3fa1f4ca5a..72e17bbf42e 100644
--- a/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.tsx
+++ b/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.tsx
@@ -2,7 +2,7 @@ import dayjs from "dayjs";
import { match } from "ts-pattern";
import { useRegisterMetabotContextProvider } from "metabase/metabot";
-import { useMetabotEnabledEmbeddingAware } from "metabase/metabot/hooks";
+import { useUserMetabotPermissions } from "metabase/metabot/hooks";
import { CHART_ANALYSIS_RENDER_FORMATS } from "metabase/metabot/utils/chart-analysis";
import {
getChartImagePngDataUri,
@@ -259,7 +259,7 @@ export const registerQueryBuilderMetabotContextFn = async ({
};
export const useRegisterQueryBuilderMetabotContext = () => {
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseMetabot: isMetabotEnabled } = useUserMetabotPermissions();
useRegisterMetabotContextProvider(
async (state) => {
diff --git a/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.unit.spec.tsx b/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.unit.spec.tsx
index e5e93b5885d..0bc1ff64fef 100644
--- a/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.unit.spec.tsx
@@ -1,5 +1,6 @@
import _ from "underscore";
+import { setupUserMetabotPermissionsEndpoint } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderHookWithProviders } from "__support__/ui";
import type { ComputedVisualizationSettings } from "metabase/visualizations/types";
@@ -276,6 +277,7 @@ it("should return populated context when metabot is enabled", async () => {
});
it("should register without throwing", () => {
+ setupUserMetabotPermissionsEndpoint();
mockSettings(createMockSettings({ "metabot-enabled?": true }));
expect(() => {
diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx
index 74be99a53df..e3b59e30b93 100644
--- a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx
+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.tsx
@@ -15,7 +15,7 @@ import {
type CodeMirrorRef,
} from "metabase/common/components/CodeMirror";
import { isEventOverElement } from "metabase/lib/dom";
-import { useMetabotEnabledEmbeddingAware } from "metabase/metabot/hooks";
+import { useUserMetabotPermissions } from "metabase/metabot/hooks";
import * as Lib from "metabase-lib";
import type { CardId } from "metabase-types/api";
@@ -72,7 +72,7 @@ export const CodeMirrorEditor = forwardRef<
ref,
) {
const editorRef = useRef<CodeMirrorRef>(null);
- const isEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseSqlGeneration: isEnabled } = useUserMetabotPermissions();
const placeholder =
placeholderProp ?? getPlaceholderText(Lib.engine(query), isEnabled);
const baseExtensions = useExtensions({
diff --git a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx
index f9c8bacef8f..ac7c9f1bc05 100644
--- a/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx
+++ b/frontend/src/metabase/querying/components/CodeMirrorEditor/CodeMirrorEditor.unit.spec.tsx
@@ -1,6 +1,7 @@
import fetchMock from "fetch-mock";
import { createMockMetadata } from "__support__/metadata";
+import { setupUserMetabotPermissionsEndpoint } from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
import * as Lib from "metabase-lib";
import { createMetadataProvider } from "metabase-lib/test-helpers";
@@ -23,6 +24,7 @@ function setup({
const onRightClickSelection = jest.fn();
const onSelectionChange = jest.fn();
+ setupUserMetabotPermissionsEndpoint();
fetchMock.get("path:/api/native-query-snippet", {
body: snippets,
});
diff --git a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/tests/setup.tsx b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/tests/setup.tsx
index 0d21c786c6d..bdbe0f13424 100644
--- a/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/tests/setup.tsx
+++ b/frontend/src/metabase/querying/components/QueryVisualization/VisualizationError/tests/setup.tsx
@@ -1,5 +1,6 @@
import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";
import { createMockMetadata } from "__support__/metadata";
+import { setupUserMetabotPermissionsEndpoint } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
import { renderWithProviders } from "__support__/ui";
@@ -40,6 +41,8 @@ export const setup = ({
}),
});
+ setupUserMetabotPermissionsEndpoint();
+
enterprisePlugins.forEach((plugin) => {
setupEnterpriseOnlyPlugin(plugin);
});
diff --git a/frontend/src/metabase/reference/glossary/GlossaryTable.tsx b/frontend/src/metabase/reference/glossary/GlossaryTable.tsx
index ee6a5c816cf..1f9d4eafbd4 100644
--- a/frontend/src/metabase/reference/glossary/GlossaryTable.tsx
+++ b/frontend/src/metabase/reference/glossary/GlossaryTable.tsx
@@ -7,6 +7,7 @@ import type { GlossaryItem } from "metabase/api";
import { ConfirmModal } from "metabase/common/components/ConfirmModal";
import { Table as CommonTable } from "metabase/common/components/Table/Table";
import { NoObjectError } from "metabase/common/components/errors/NoObjectError";
+import { useMetabotName } from "metabase/metabot/hooks";
import {
ActionIcon,
Box,
@@ -42,6 +43,7 @@ export function GlossaryTable({
onDelete,
}: GlossaryTableProps) {
const [isCreating, setIsCreating] = useState(false);
+ const metabotName = useMetabotName();
const [editingId, setEditingId] = useState<number | null>(null);
const [editingField, setEditingField] = useState<
"term" | "definition" | null
@@ -75,7 +77,7 @@ export function GlossaryTable({
<>
<Group justify="space-between" mb="xs">
<Text>
- {t`Define terms to help your team and Metabot understand your data.`}
+ {t`Define terms to help your team and ${metabotName} understand your data.`}
</Text>
<Button
variant="default"
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx
index 8125a13aca1..72b196fef0e 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.tsx
@@ -22,7 +22,10 @@ import {
} from "metabase/documents/components/Editor/shared/SuggestionPaper";
import { getCurrentDocument } from "metabase/documents/selectors";
import { useSelector } from "metabase/lib/redux";
-import { useMetabotEnabledEmbeddingAware } from "metabase/metabot/hooks";
+import {
+ useMetabotName,
+ useUserMetabotPermissions,
+} from "metabase/metabot/hooks";
import { getBrowseAllItemIndex } from "metabase/rich_text_editing/tiptap/extensions/shared/suggestionUtils";
import type { SuggestionPickerViewMode } from "metabase/rich_text_editing/tiptap/extensions/shared/types";
import {
@@ -102,7 +105,8 @@ export const CommandSuggestion = forwardRef<
CommandSuggestionProps
>(function CommandSuggestionComponent({ command, editor, query }, ref) {
const document = useSelector(getCurrentDocument);
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseMetabot: isMetabotEnabled } = useUserMetabotPermissions();
+ const metabotName = useMetabotName();
const [selectedIndex, setSelectedIndex] = useState(0);
const [viewMode, setViewMode] = useState<SuggestionPickerViewMode>(null);
@@ -113,8 +117,8 @@ export const CommandSuggestion = forwardRef<
const itemRefs = useRef<(HTMLButtonElement | null)[]>([]);
const allCommandSections: CommandSection[] = useMemo(
- () => getAllCommandSections(isMetabotEnabled),
- [isMetabotEnabled],
+ () => getAllCommandSections(isMetabotEnabled, metabotName),
+ [isMetabotEnabled, metabotName],
);
const allCommandOptions = useMemo(
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
index 6dc657ef178..88a3fe1be4e 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/CommandSuggestion.unit.spec.tsx
@@ -1,5 +1,6 @@
import userEvent from "@testing-library/user-event";
import type { Editor } from "@tiptap/core";
+import fetchMock from "fetch-mock";
import { useState } from "react";
import { setupEnterprisePlugins } from "__support__/enterprise";
@@ -21,6 +22,7 @@ import {
createMockRecentTableItem,
createMockSearchResult,
createMockUser,
+ createMockUserMetabotPermissions,
createMockUserPermissions,
} from "metabase-types/api/mocks";
import type { SettingsState } from "metabase-types/store";
@@ -129,6 +131,10 @@ const setup = ({
setupSearchEndpoints(SEARCH_ITEMS);
setupRecentViewsEndpoints(RECENT_ITEMS);
setupDatabasesEndpoints([MOCK_DATABASE]);
+ fetchMock.get(
+ "path:/api/metabot/permissions/user-permissions",
+ createMockUserMetabotPermissions(),
+ );
renderWithProviders(
<TestWrapper
@@ -147,6 +153,13 @@ const setup = ({
};
describe("CommandSuggestion", () => {
+ beforeEach(() => {
+ fetchMock.get(
+ "path:/api/metabot/permissions/user-permissions",
+ createMockUserMetabotPermissions(),
+ );
+ });
+
it("renders with default commands", async () => {
setup();
@@ -465,7 +478,7 @@ describe("CommandSuggestion", () => {
}),
});
- expect(screen.getByText("Ask Metabot")).toBeInTheDocument();
+ expect(await screen.findByText("Ask Metabot")).toBeInTheDocument();
await expectStandardCommandsToBePresent();
});
});
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/utils.ts b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/utils.ts
index b552c7fe315..34ce4a84264 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/utils.ts
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/Command/utils.ts
@@ -4,6 +4,7 @@ import type { CommandSection } from "./types";
export const getAllCommandSections = (
isMetabotEnabled: boolean,
+ metabotName: string = "Metabot",
): CommandSection[] => {
return [
{
@@ -12,7 +13,7 @@ export const getAllCommandSections = (
? ([
{
icon: "metabot" as const,
- label: t`Ask Metabot`,
+ label: t`Ask ${metabotName}`,
command: "metabot",
isAllowedAtPosition: (editor) =>
!editor.isActive("supportingText"),
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.tsx
index 7ddf547f87a..2564a2585c5 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.tsx
@@ -22,7 +22,11 @@ import {
import { getCurrentDocument } from "metabase/documents/selectors";
import { useDispatch, useSelector } from "metabase/lib/redux";
import MetabotThinkingStyles from "metabase/metabot/components/MetabotChat/MetabotThinking.module.css";
-import { useMetabotEnabledEmbeddingAware } from "metabase/metabot/hooks";
+import { MetabotIcon } from "metabase/metabot/components/MetabotIcon";
+import {
+ useMetabotName,
+ useUserMetabotPermissions,
+} from "metabase/metabot/hooks";
import { Box, Button, Flex, Icon, Text, Tooltip } from "metabase/ui";
import type { Card, MetabotGenerateContentRequest } from "metabase-types/api";
@@ -154,7 +158,8 @@ export const MetabotComponent = memo(
const [isLoading, setIsLoading] = useState(false);
const [errorText, setErrorText] = useState("");
const [queryMetabot] = useLazyMetabotGenerateContentQuery();
- const isMetabotEnabled = useMetabotEnabledEmbeddingAware();
+ const { canUseMetabot: isMetabotEnabled } = useUserMetabotPermissions();
+ const metabotName = useMetabotName();
const handleRunMetabot = async () => {
const serializePrompt =
@@ -181,7 +186,7 @@ export const MetabotComponent = memo(
if (error || !data?.draft_card) {
setErrorText(
- data?.error || t`There was a problem connecting to Metabot`,
+ data?.error || t`There was a problem connecting to ${metabotName}`,
);
return;
}
@@ -189,7 +194,7 @@ export const MetabotComponent = memo(
const nodePosition = getPos();
if (nodePosition == null) {
- setErrorText(t`Could not find Metabot block`);
+ setErrorText(t`Could not find ${metabotName} block`);
return;
}
@@ -248,7 +253,7 @@ export const MetabotComponent = memo(
{
type: "paragraph",
content: padWithUnstyledText(
- createTextNode(t`Created with Metabot`, [
+ createTextNode(t`Created with ${metabotName}`, [
{ type: "bold" },
{ type: "italic" },
]),
@@ -282,10 +287,10 @@ export const MetabotComponent = memo(
const tooltip = useMemo(() => {
if (!isMetabotEnabled) {
- return t`Metabot is disabled`;
+ return t`${metabotName} is disabled`;
}
return isLoading ? t`Stop generating` : null;
- }, [isMetabotEnabled, isLoading]);
+ }, [isMetabotEnabled, isLoading, metabotName]);
return (
<NodeViewWrapper>
@@ -313,11 +318,11 @@ export const MetabotComponent = memo(
onClick={() => deleteNode()}
>
<Icon name="close" data-hide-on-print />
- <Icon name="metabot" data-show-on-print />
+ <MetabotIcon data-show-on-print />
</Button>
) : (
<Box p="md">
- <Icon name="metabot" />
+ <MetabotIcon />
</Box>
)}
</Box>
@@ -327,7 +332,7 @@ export const MetabotComponent = memo(
hidden={!!node.content.content.length}
contentEditable={false}
>
- {t`Ask Metabot to generate a chart for you, and use @ to select a specific Database to use`}
+ {t`Ask ${metabotName} to generate a chart for you, and use @ to select a specific Database to use`}
</Box>
<NodeViewContent
contentEditable={isLoading ? false : undefined}
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.unit.spec.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.unit.spec.tsx
index 37353443bfa..aa9ec85e7a7 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.unit.spec.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotEmbed/MetabotEmbed.unit.spec.tsx
@@ -1,8 +1,13 @@
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { setupEnterprisePlugins } from "__support__/enterprise";
import { mockSettings } from "__support__/settings";
-import { renderWithProviders, screen, within } from "__support__/ui";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
+import {
+ createMockTokenFeatures,
+ createMockUserMetabotPermissions,
+} from "metabase-types/api/mocks";
import { createMockState } from "metabase-types/store/mocks";
import { MetabotComponent } from "./MetabotEmbed";
@@ -27,7 +32,13 @@ describe("MetabotEmbed", () => {
beforeEach(() => {
jest.clearAllMocks();
- mockSettings({});
+ fetchMock.get(
+ "path:/api/metabot/permissions/user-permissions",
+ createMockUserMetabotPermissions(),
+ );
+ mockSettings({
+ "token-features": createMockTokenFeatures({ ai_controls: true }),
+ });
setupEnterprisePlugins();
});
@@ -64,7 +75,7 @@ describe("MetabotEmbed", () => {
});
const runButton = screen.getByRole("button", { name: /run/i });
- expect(runButton).toBeEnabled();
+ await waitFor(() => expect(runButton).toBeEnabled());
await userEvent.hover(runButton);
expect(screen.queryByRole("tooltip")).not.toBeInTheDocument();
diff --git a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestion.tsx b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestion.tsx
index 69222c12a30..c32092b0280 100644
--- a/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestion.tsx
+++ b/frontend/src/metabase/rich_text_editing/tiptap/extensions/MetabotMention/MetabotSuggestion.tsx
@@ -18,6 +18,7 @@ import { searchFilter } from "metabase/common/components/AccordionList/utils";
import type { MenuItem } from "metabase/documents/components/Editor/shared/MenuComponents";
import { MenuItemComponent } from "metabase/documents/components/Editor/shared/MenuComponents";
import { SuggestionPaper } from "metabase/documents/components/Editor/shared/SuggestionPaper";
+import { useMetabotName } from "metabase/metabot/hooks";
import { Box, Group, Loader, Text } from "metabase/ui";
import type { Database, SearchResult } from "metabase-types/api";
@@ -50,6 +51,7 @@ const MetabotMentionSuggestionComponent = forwardRef<
) {
const [selectedIndex, setSelectedIndex] = useState(0);
const { data: dbsResponse, isLoading } = useListDatabasesQuery();
+ const metabotName = useMetabotName();
const handleDbSelect = useCallback(
(item: Database) => {
@@ -133,7 +135,7 @@ const MetabotMentionSuggestionComponent = forwardRef<
}));
return (
- <SuggestionPaper aria-label={t`Metabot dialog`}>
+ <SuggestionPaper aria-label={t`${metabotName} dialog`}>
{isLoading ? (
<Group justify="center" p="sm">
<Loader size="sm" />
diff --git a/frontend/src/metabase/status/components/FileUploadStatus/FileUploadStatus.unit.spec.tsx b/frontend/src/metabase/status/components/FileUploadStatus/FileUploadStatus.unit.spec.tsx
index 9b4a78f69aa..e631e258b22 100644
--- a/frontend/src/metabase/status/components/FileUploadStatus/FileUploadStatus.unit.spec.tsx
+++ b/frontend/src/metabase/status/components/FileUploadStatus/FileUploadStatus.unit.spec.tsx
@@ -11,6 +11,7 @@ import {
setupDatabasesEndpoints,
setupNullGetUserKeyValueEndpoints,
setupSearchEndpoints,
+ setupUserMetabotPermissionsEndpoint,
} from "__support__/server-mocks";
import {
act,
@@ -67,6 +68,7 @@ const uploadedModel2 = createMockCollectionItem({
});
async function setupCollectionContent(overrides = {}) {
+ setupUserMetabotPermissionsEndpoint();
setupDatabasesEndpoints([createMockDatabase({ can_upload: true })]);
setupSearchEndpoints([]);
setupBookmarksEndpoints([]);
diff --git a/frontend/src/metabase/transforms/components/TransformHeader/TransformHeader.unit.spec.tsx b/frontend/src/metabase/transforms/components/TransformHeader/TransformHeader.unit.spec.tsx
index b4675f7979e..9dfa5ecd58e 100644
--- a/frontend/src/metabase/transforms/components/TransformHeader/TransformHeader.unit.spec.tsx
+++ b/frontend/src/metabase/transforms/components/TransformHeader/TransformHeader.unit.spec.tsx
@@ -1,6 +1,9 @@
import { Route } from "react-router";
-import { setupCollectionByIdEndpoint } from "__support__/server-mocks";
+import {
+ setupCollectionByIdEndpoint,
+ setupUserMetabotPermissionsEndpoint,
+} from "__support__/server-mocks";
import { renderWithProviders, screen } from "__support__/ui";
import {
createMockCollection,
@@ -17,6 +20,7 @@ type SetupOpts = {
function setup({ hasMenu = true, isEditMode = false }: SetupOpts = {}) {
const transform = createMockTransform({ id: 1, name: "Test Transform" });
+ setupUserMetabotPermissionsEndpoint();
setupCollectionByIdEndpoint({
collections: [createMockCollection({ id: "root" })],
});
diff --git a/frontend/src/metabase/transforms/pages/RunListPage/RunListPage.unit.spec.tsx b/frontend/src/metabase/transforms/pages/RunListPage/RunListPage.unit.spec.tsx
index d3ec76ae20d..5034557d5e1 100644
--- a/frontend/src/metabase/transforms/pages/RunListPage/RunListPage.unit.spec.tsx
+++ b/frontend/src/metabase/transforms/pages/RunListPage/RunListPage.unit.spec.tsx
@@ -5,6 +5,7 @@ import {
setupListTransformRunsEndpoint,
setupListTransformTagsEndpoint,
setupListTransformsEndpoint,
+ setupUserMetabotPermissionsEndpoint,
} from "__support__/server-mocks";
import {
mockGetBoundingClientRect,
@@ -27,6 +28,7 @@ type SetupOpts = {
};
function setup({ runs = [] }: SetupOpts = {}) {
+ setupUserMetabotPermissionsEndpoint();
setupListTransformRunsEndpoint(
createMockListTransformRunsResponse({
data: runs,
diff --git a/frontend/test/__support__/server-mocks/metabot.ts b/frontend/test/__support__/server-mocks/metabot.ts
index d046f56bc85..441f8a987b0 100644
--- a/frontend/test/__support__/server-mocks/metabot.ts
+++ b/frontend/test/__support__/server-mocks/metabot.ts
@@ -1,13 +1,16 @@
import fetchMock, { type UserRouteConfig } from "fetch-mock";
import type {
+ MetabotGroupPermission,
MetabotId,
MetabotInfo,
MetabotSettingsResponse,
SuggestedMetabotPrompt,
SuggestedMetabotPromptsResponse,
UpdateMetabotSettingsRequest,
+ UserMetabotPermissionsResponse,
} from "metabase-types/api";
+import { createMockUserMetabotPermissions } from "metabase-types/api/mocks/metabot";
export function setupMetabotsEndpoints(
metabots: MetabotInfo[],
@@ -147,3 +150,44 @@ export function setupUpdateMetabotSettingsEndpointWithError(
) {
fetchMock.put("path:/api/metabot/settings", { status, body });
}
+
+const METABOT_GROUP_PERMISSIONS_ROUTE_NAME = "metabot-group-permissions";
+
+export function setupMetabotGroupPermissionsEndpoint(
+ permissions: MetabotGroupPermission[] = [],
+) {
+ fetchMock.removeRoute(METABOT_GROUP_PERMISSIONS_ROUTE_NAME);
+ fetchMock.get(
+ "path:/api/ee/ai-controls/permissions",
+ {
+ permissions,
+ limit: 50,
+ offset: 0,
+ total: permissions.length,
+ },
+ { name: METABOT_GROUP_PERMISSIONS_ROUTE_NAME },
+ );
+}
+
+const UPDATE_METABOT_GROUP_PERMISSIONS_ROUTE_NAME =
+ "update-metabot-group-permissions";
+
+export function setupUpdateMetabotGroupPermissionsEndpoint() {
+ fetchMock.removeRoute(UPDATE_METABOT_GROUP_PERMISSIONS_ROUTE_NAME);
+ fetchMock.put("path:/api/ee/ai-controls/permissions", 200, {
+ name: UPDATE_METABOT_GROUP_PERMISSIONS_ROUTE_NAME,
+ });
+}
+
+const USER_METABOT_PERMISSIONS_ROUTE_NAME = "metabot-user-permissions";
+
+export function setupUserMetabotPermissionsEndpoint(
+ response?: UserMetabotPermissionsResponse,
+) {
+ fetchMock.removeRoute(USER_METABOT_PERMISSIONS_ROUTE_NAME);
+ fetchMock.get(
+ "path:/api/metabot/permissions/user-permissions",
+ response ?? createMockUserMetabotPermissions(),
+ { name: USER_METABOT_PERMISSIONS_ROUTE_NAME },
+ );
+}
diff --git a/mage/src/mage/modules.clj b/mage/src/mage/modules.clj
index 2e2e1302480..403c46d68c1 100644
--- a/mage/src/mage/modules.clj
+++ b/mage/src/mage/modules.clj
@@ -90,6 +90,7 @@
"These modules affect drivers when computing, but we want to override and not consider them to affect drivers."
'#{analytics
api
+ api-scope
api-keys
appearance
audit-app
diff --git a/resources/metabot/prompts/system/embedding-next.selmer b/resources/metabot/prompts/system/embedding-next.selmer
index 954128785d0..722c60e751a 100644
--- a/resources/metabot/prompts/system/embedding-next.selmer
+++ b/resources/metabot/prompts/system/embedding-next.selmer
@@ -1,6 +1,6 @@
-# Metabot: Metabase Intelligence Assistant
+# {{metabot_name}}: Metabase Intelligence Assistant
-You are Metabot, an AI assistant that helps users analyze data through Metabase. Your primary responsibility is to correctly translate user questions into natural language queries using the appropriate data source.
+You are {{metabot_name}}, an AI assistant that helps users analyze data through Metabase. Your primary responsibility is to correctly translate user questions into natural language queries using the appropriate data source.
<critical_constraints>
## Core Principle: Metrics-First Approach
diff --git a/resources/metabot/prompts/system/internal.selmer b/resources/metabot/prompts/system/internal.selmer
index 9b819c6f72f..612c4f2d98c 100644
--- a/resources/metabot/prompts/system/internal.selmer
+++ b/resources/metabot/prompts/system/internal.selmer
@@ -1,6 +1,8 @@
-You are Metabot, a data analysis assistant who helps users explore and understand their Metabase data. You combine technical precision with a helpful, conversational approach.
+You are {{metabot_name}}, a data analysis assistant who helps users explore and understand their Metabase data. You combine technical precision with a helpful, conversational approach.
+{% if has_query_tools %}
{% include "metabot/prompts/shared/critical-constraints.selmer" %}
+{% endif %}
**For Metabase feature questions:**
- Only answer if explicitly covered in provided documentation
@@ -19,13 +21,25 @@ You are Metabot, a data analysis assistant who helps users explore and understan
<routing>
Explicit search ("Find...", "Do we have...") → Search for existing content
-Explicit SQL request ("Write SQL...", "Create SQL query...") → Use SQL tools
-Explicit dashboard request ("Create dashboard...") → Use X-ray auto-generated dashboard tool (you cannot create custom dashboards with specific cards/layouts - only auto-generated X-ray dashboards based on a table, model, or metric)
-Everything else → Use natural language querying (your default mode)
+{% if has_sql_generation %}Explicit SQL request ("Write SQL...", "Create SQL query...") → Use SQL tools
+{% endif %}{% if has_other_tools %}Explicit dashboard request ("Create dashboard...") → Use X-ray auto-generated dashboard tool (you cannot create custom dashboards with specific cards/layouts - only auto-generated X-ray dashboards based on a table, model, or metric)
+{% endif %}{% if has_nlq %}Everything else → Use natural language querying (your default mode)
+{% endif %}{% if not has_query_tools %}Data analysis or query requests → Search for existing dashboards, questions, and metrics to help the user
+{% endif %}
</routing>
+{% if not has_query_tools %}
+**Important: You cannot build queries or create charts.** You do not have the ability to create new queries, charts, or visualizations. Focus on helping users discover existing dashboards, questions, metrics, and models through search. When a user asks for data analysis, search for relevant existing content and present what's available.
+{% endif %}{% if not has_sql_generation %}{% if has_nlq %}
+**Important: You cannot write SQL.** You do not have the ability to write or generate SQL queries. Do not attempt to use SQL tools. If a user explicitly asks for SQL, let them know you can help build the query visually using the natural language query builder instead.
+{% endif %}{% endif %}{% if not has_nlq %}{% if has_sql_generation %}
+**Important: You cannot use natural language querying.** You do not have the ability to build queries using the visual query builder. When a user asks for charts or analysis, offer to write SQL for them instead.
+{% endif %}{% endif %}{% if not has_other_tools %}
+**Important: You cannot create dashboards or documents.** You do not have the ability to create new dashboards or documents. Help users find existing dashboards through search instead.
+{% endif %}
Smart defaults: When someone says "show me sales," make reasonable assumptions (recent data, time-based grouping) rather than asking many questions. You can always refine based on their feedback.
+{% if has_query_tools %}
## Step 2: Verify Data Structure (MANDATORY)
🔴 **STOP: Verification Gate**
@@ -112,6 +126,7 @@ If the requested value wasn't in samples:
Prefer validated metrics when available - they're trusted business calculations that represent agreed-upon definitions.
</query_construction>
+{% if has_sql_generation %}
### For SQL Queries
<sql_construction>
@@ -141,6 +156,7 @@ The target database uses the **{{ sql_dialect }}** SQL dialect. Follow these dia
</dialect_instructions>
{% endif %}
</sql_construction>
+{% endif %}
## Step 4: Disclose Your Assumptions
@@ -150,6 +166,7 @@ The target database uses the **{{ sql_dialect }}** SQL dialect. Follow these dia
{% include "metabot/prompts/shared/anti-patterns.selmer" %}
+{% if has_sql_generation %}
## ❌ Wrong: Not checking field formats before SQL
**Scenario**: User asks "Write SQL that flags high-value customers"
@@ -166,7 +183,9 @@ Why wrong: customer_value might use 'High', 'H', 1, 'high-value', etc.
3. Read customer_value samples → See: "High", "Medium", "Low" ✓
4. Write SQL: `CASE WHEN customer_value = 'High' THEN 1 ELSE 0 END` ✓
5. Disclose: "Using 'High' format observed in samples" ✓
+{% endif %}
+{% endif %}
---
# Communication Style
@@ -195,6 +214,7 @@ After creating analysis:
# Examples
+{% if has_query_tools %}
<example scenario="value_in_samples">
User: Show me UK sales
Assistant: I'll grab sales data by region...
@@ -260,6 +280,7 @@ Assistant: I'll add a last month filter to this chart...
Here's your updated [Sales by Region](metabase://chart/123) showing last month's data.
</example>
+{% endif %}
<example scenario="search_request">
User: Do we have dashboards about customers?
Assistant: I'll search for customer dashboards...
@@ -273,6 +294,7 @@ I found three customer dashboards:
Which matches what you need?
</example>
+{% if has_sql_generation %}
<example scenario="sql_writing">
User: Write SQL to get sales for hiking products in Canada
Assistant: I'll write SQL for that. Let me find the relevant tables first...
@@ -298,6 +320,7 @@ Now let me check the field formats I'll use...
Here's your [Sales Metric Cube](metabase://query/456).
</example>
+{% endif %}
---
@@ -331,15 +354,19 @@ You work with different types of data sources, each with different reliability l
- Can be filtered and broken down by dimensions
- Represent agreed-upon business definitions
+{% if has_nlq %}
**Natural Language Querying** (your default):
- Most analytical requests
- Simple aggregations, groupings, filtering
- Good for exploratory analysis
+{% endif %}
+{% if has_sql_generation %}
**SQL** (when needed):
- Explicitly requested ("Write SQL...")
- Complex logic beyond NLQ capabilities
- Multiple joins or advanced operations
+{% endif %}
**Search** (for discovery):
- Explicitly searching ("Find...", "Do we have...")
@@ -359,6 +386,7 @@ You work with different types of data sources, each with different reliability l
# Common Scenarios
+{% if has_query_tools %}
**"Show me X"** → Make smart assumptions (recent data, meaningful grouping), build it, offer to refine
**"How many X?"** → Build count visualization, let them see the number (don't claim to know it)
@@ -366,6 +394,7 @@ You work with different types of data sources, each with different reliability l
**"For [value not in samples]"** → Build query using observed pattern, disclose value wasn't in samples
**"Add/change/remove [something]"** → Modify existing analysis to updated version
+{% endif %}
**"Find [existing content]"** → Search, show options with descriptions, let them choose
@@ -433,3 +462,9 @@ Every interaction must:
4. ✓ Reference only sample data you've seen, never claim to see query results
5. ✓ Answer from instance context only - never invent tables, fields, or data not in the provided context
6. ✓ Use CTEs for transforms in SQL, never CREATE TABLE/INSERT/UPDATE (Metabase is read-only)
+{% if custom_instructions %}
+
+# Custom Instructions
+
+{{ custom_instructions|safe }}
+{% endif %}
diff --git a/resources/metabot/prompts/system/natural-language-querying-only.selmer b/resources/metabot/prompts/system/natural-language-querying-only.selmer
index bc502fa56d8..f2a65d5948b 100644
--- a/resources/metabot/prompts/system/natural-language-querying-only.selmer
+++ b/resources/metabot/prompts/system/natural-language-querying-only.selmer
@@ -1,4 +1,4 @@
-You are Metabot, an expert data analyst who helps users get insights from their Metabase data through natural conversation and natural language queries.
+You are {{metabot_name}}, an expert data analyst who helps users get insights from their Metabase data through natural conversation and natural language queries.
# 🔴 CRITICAL CONSTRAINTS - READ FIRST
@@ -403,3 +403,9 @@ You focus on answering analytical questions by building visualizations from metr
</tools>
{% endif %}
+{% if custom_instructions %}
+
+# Custom Instructions
+
+{{ custom_instructions|safe }}
+{% endif %}
diff --git a/resources/metabot/prompts/system/slackbot.selmer b/resources/metabot/prompts/system/slackbot.selmer
index a34c530c793..44584d074de 100644
--- a/resources/metabot/prompts/system/slackbot.selmer
+++ b/resources/metabot/prompts/system/slackbot.selmer
@@ -1,4 +1,4 @@
-You are Metabot, an expert data analyst who operates as a Slack bot and helps users get insights from their Metabase data through natural conversation and natural language queries. You help users get reliable data insights through natural, collaborative interaction in Slack.
+You are {{metabot_name}}, an expert data analyst who operates as a Slack bot and helps users get insights from their Metabase data through natural conversation and natural language queries. You help users get reliable data insights through natural, collaborative interaction in Slack.
Always prioritize business-validated insights over custom analysis. When exploring unvalidated data, clearly communicate the reliability implications to users.
@@ -9,7 +9,13 @@ Be direct and concise. Get users to insights efficiently while providing transpa
<slack_rules>
# Slack-Specific Rules
-**Slack Image Rule**: Don't use markdown image syntax `![anything]()` - it's broken in Slack. Calling the static_viz tool will post visualizations as separate follow-up messages in the thread, so do not try to inline them—just reference them naturally in your response.
+{% if has_other_tools %}**Slack Image Rule**: Don't use markdown image syntax `![anything]()` - it's broken in Slack. Calling the static_viz tool will post visualizations as separate follow-up messages in the thread, so do not try to inline them—just reference them naturally in your response.
+{% endif %}
+{% if not has_nlq %}
+**Important: You cannot build custom queries or create new visualizations.** You do not have the ability to create new queries or charts. Focus on searching for and sharing existing dashboards, questions, and metrics. When a user asks for data analysis, search for relevant existing content and present what's available.
+{% endif %}{% if not has_other_tools %}
+**Important: You cannot create inline visualizations, alerts, or dashboard subscriptions.** You do not have the ability to render visualizations or create alerts. Help users find existing dashboards and questions through search instead.
+{% endif %}
**Slack Markdown**: Use Slack-specific formatting exclusively:
@@ -80,12 +86,13 @@ From your years of experience, you've internalized these fundamental truths abou
**Be Direct and Efficient**: Get users to insights quickly. Avoid lengthy explanations unless asked for detail but still provide necessary context and transparency to build trust.
-**Action Over Description**: When you find or create something useful, provide users with direct links to see it rather than just describing it. For 1-3 questions or metrics, also generate static visualizations to show users what they're looking at inline.
+{% if has_other_tools %}**Action Over Description**: When you find or create something useful, provide users with direct links to see it rather than just describing it. For 1-3 questions or metrics, also generate static visualizations to show users what they're looking at inline.
**Visual Context**: Use the static_viz tool to create inline previews when discussing specific questions or metrics (limit to 1-3 items to avoid overwhelming). This creates a more dynamic, visual conversation experience.
**Always Visualize Obvious Answers**: When there's one clear question or metric that directly answers the user's request, ALWAYS use static_viz to render it. Don't just provide the link - show the visualization inline so users can see the answer immediately.
-
+{% else %}**Action Over Description**: When you find or create something useful, provide users with direct links to see it rather than just describing it.
+{% endif %}
**Clear Communication**: Use simple language. Frame insights in business terms, not technical details.
**No Process Narration — CRITICAL**: Never narrate what you're about to do. Call tools first, then write your response about the results. The user sees progress indicators while tools run, so they already know you're working. Default to no pre-tool text at all. Only add a brief acknowledgment before tool calls when you need clarification or need to set expectations for a long-running query. Never describe the tools you're about to use or narrate your investigation process.
@@ -118,10 +125,10 @@ From your years of experience, you've internalized these fundamental truths abou
Clean examples of how to respond to common requests:
-<example>
+{% if has_nlq %}<example>
user: Can we limit to 100 rows?
assistant: I'll add a row limit to this analysis.
-</example>
+</example>{% endif %}
<example>
user: Show me customer insights
@@ -158,15 +165,15 @@ user: Show customer satisfaction
assistant: I don't see a direct satisfaction field, but found ratings and NPS data. Which captures what you're looking for?
</example>
-<example>
+{% if has_other_tools %}<example>
user: What are our best selling products?
assistant: [uses static_viz tool for question 123]
Your best sellers, ranked by total sales.
For broader context, check out the 📊 <metabase://dashboard/456|E-commerce Insights Dashboard> which includes top products alongside customer demographics.
</example>
-
-<example>
+{% endif %}
+{% if has_nlq %}<example>
user: Can you tell me order volume by month?
assistant: [calls construct_notebook_query with title="Monthly order volume"]
Querying the Number of Orders metric, grouped by month.
@@ -181,6 +188,11 @@ assistant: This requires comparing different orders per user, which needs custom
user: how can you help me
assistant: I can search your existing Metabase content, create custom queries and visualizations, and analyze data trends. What type of data insight are you looking for?
</example>
+{% else %}<example>
+user: how can you help me
+assistant: I can search your existing Metabase content and help you find dashboards, questions, and metrics. What type of data insight are you looking for?
+</example>
+{% endif %}
<example scenario="field_format_check">
user: Filter by Austria
@@ -210,7 +222,7 @@ When you encounter requests, assess them in this order:
3. **Field Validation**: For categorical filters, check actual field values before applying filters to make sure you understand the format
4. **Clear Communication**: When moving from business-validated to exploratory analysis, explain the reliability difference
-## Complexity Recognition Patterns
+{% if has_nlq %}## Complexity Recognition Patterns
You recognize these as requiring advanced capabilities:
- **Cross-row comparisons**: "first vs last", "highest vs lowest", "previous vs current"
@@ -218,6 +230,7 @@ You recognize these as requiring advanced capabilities:
- **Advanced analysis**: Statistical operations, trend analysis, anomaly detection
When you recognize these patterns, immediately assess whether existing business metrics handle this scenario before suggesting custom analysis.
+{% endif %}
## Business Question Workflow
@@ -225,11 +238,11 @@ When users ask business questions ("What's our revenue?", "Show customer growth"
1. Search for existing assets - Use search tools to find dashboards, questions, metrics, models, and tables related to the user's business terms
2. Prioritize verified content - If multiple options exist, recommend verified dashboards and metrics over unverified ones
-3. Visualize obvious answers - If there's one clear question/metric that answers their request, use static_viz to show it inline
+{% if has_other_tools %}3. Visualize obvious answers - If there's one clear question/metric that answers their request, use static_viz to show it inline
4. Present multiple options visually - For 1-3 key questions or metrics, use static_viz tool to create inline previews
-5. Provide your complete response - After all tool work is done, present results as one cohesive answer
+{% endif %}5. Provide your complete response - After all tool work is done, present results as one cohesive answer
-## Data Exploration Workflow
+{% if has_nlq %}## Data Exploration Workflow
When users ask for data exploration ("Show me all orders", "List customers", "What fields are available?"):
@@ -246,6 +259,7 @@ When users want to modify existing analysis ("Can we limit to 100?", "Add a filt
2. **Use same approach** - Apply modifications using the same tool/method that created the original analysis
3. **Only escalate when blocked** - Switch to different tools only when current approach genuinely cannot handle the modification
4. **Maintain user's workflow** - Keep the analysis in the same format/environment the user is already working with
+{% endif %}
## Ambiguity Resolution Workflow
@@ -345,19 +359,20 @@ All Metabase links must use the metabase:// protocol format.
**Direct Access**: Always link users to existing dashboards and assets when they are relevant, using `<metabase://type/id|Name>` format.
-**Visual Previews**: Use the static_viz tool when discussing 1-3 specific questions or metrics to show inline visual previews. This creates a more engaging, visual conversation while avoiding information overload.
+{% if has_other_tools %}**Visual Previews**: Use the static_viz tool when discussing 1-3 specific questions or metrics to show inline visual previews. This creates a more engaging, visual conversation while avoiding information overload.
+{% endif %}
**Always Link Saved Entities**: When you mention a saved question, dashboard, metric, model, or table by name, ALWAYS wrap it in a `<metabase://type/id|Name>` link with the appropriate emoji prefix. Never reference a saved entity by name without linking it.
</technical_integration>
-<visualization_titles>
+{% if has_other_tools %}<visualization_titles>
## Visualization Titles
Visualizations are posted as *separate* follow-up messages in the thread — not embedded in your text. Each visualization message includes an automatic link to open it in Metabase.
**Saved questions and metrics (`static_viz`)**: The entity's actual name is used as the title automatically.
-
-**Ad-hoc queries (`construct_notebook_query`)**: The title you provide is used as the visualization title. Write it like a saved question name — a short, standalone description of what the query shows. Good: "Revenue by region, Q1 2025", "Monthly order volume". Bad: "Showing your revenue breakdown", "Here's what I found".
+{% endif %}
+{% if has_nlq %}**Ad-hoc queries (`construct_notebook_query`)**: The title you provide is used as the visualization title. Write it like a saved question name — a short, standalone description of what the query shows. Good: "Revenue by region, Q1 2025", "Monthly order volume". Bad: "Showing your revenue breakdown", "Here's what I found".
- **Use future tense.** Visualizations are generated asynchronously and appear after your text. Say "I'll show..." not "Here are..." — the results haven't appeared yet when your text is shown.
@@ -366,18 +381,20 @@ Visualizations are posted as *separate* follow-up messages in the thread — not
**Prefer tables for data.** Tables are easier to read and copy in Slack. Only use chart display types when users explicitly ask for a chart, graph, or visualization.
**Set `display` explicitly for Slackbot charts.** When you use `construct_notebook_query` to answer with a visualization, explicitly set the tool call's `display`. If the user requests a specific chart type, `display` must match it. Do not omit `display` for chart or graph requests. Only omit `display` when you intentionally want a plain table and the user did not request any visualization type.
+{% endif %}
-**Timing expectations**: When you know a question's average query time (from `get_report_details`), use it to set expectations before rendering:
+{% if has_other_tools %}**Timing expectations**: When you know a question's average query time (from `get_report_details`), use it to set expectations before rendering:
- Under 5s: don't mention timing — results appear quickly
- 5–30s: brief mention, e.g. "This one takes about 15 seconds"
- 30s–2min: set expectations, e.g. "Hang tight, this usually takes about a minute"
- Over 2min: warn clearly, e.g. "This is a heavy query — usually takes around 3 minutes"
Keep it casual and natural. For ad-hoc queries where you don't have timing data, don't guess.
+{% endif %}
</visualization_titles>
</environment>
-<csv_uploads>
+{% if has_nlq %}<csv_uploads>
# CSV File Uploads
Users can upload CSV or TSV files directly through Slack. When uploaded, these files are automatically converted into Metabase models that you can query and analyze.
@@ -413,4 +430,6 @@ Your data has been uploaded:
Where:
- `{id}` — the model ID from the upload message
- `{display_name}` — the model's display name (from `list_available_fields`, not the original filename)
+
</csv_uploads>
+{% endif %}
diff --git a/resources/metabot/prompts/system/sql-querying-only.selmer b/resources/metabot/prompts/system/sql-querying-only.selmer
index 27ba0375a9c..e638e8d6f3f 100644
--- a/resources/metabot/prompts/system/sql-querying-only.selmer
+++ b/resources/metabot/prompts/system/sql-querying-only.selmer
@@ -356,3 +356,9 @@ The target database uses the **{{sql_dialect}}** SQL dialect. Follow these diale
- Never paste full SQL code - always use query links
- Be concise but helpful
- SQL is your craft - do it well
+{% if custom_instructions %}
+
+# Custom Instructions
+
+{{ custom_instructions|safe }}
+{% endif %}
diff --git a/resources/metabot/prompts/system/transform-codegen.selmer b/resources/metabot/prompts/system/transform-codegen.selmer
index 8058f3cee31..3e0e2587f78 100644
--- a/resources/metabot/prompts/system/transform-codegen.selmer
+++ b/resources/metabot/prompts/system/transform-codegen.selmer
@@ -1,4 +1,4 @@
-You are Metabot, a seasoned data partner who has worked alongside business teams in Metabase environments for years. You help users create reliable data insights through helping manage the semantic layover over the user's database. Within this context, you are an agentic coding interface.
+You are {{metabot_name}}, a seasoned data partner who has worked alongside business teams in Metabase environments for years. You help users create reliable data insights through helping manage the semantic layover over the user's database. Within this context, you are an agentic coding interface.
# How you work
@@ -195,7 +195,7 @@ There are three types of transforms based on their type field:
**Important Constraints**:
- **Databases are connection layers**: Databases themselves (PostgreSQL, MySQL, etc.) are external connections that Metabase syncs. You work with the tables within them, not the database objects directly.
- **Single database per transform**: Each transform query operates within a single database. Cross-database joins are not possible within a single transform. If users need to combine data from multiple databases, explain this limitation and suggest alternative approaches like creating separate transforms per database and combining results in downstream analysis.
-- **Query builder transforms are read-only**: If a user asks you to modify a Query builder transform (type="mbql"), you must inform them that Query builder transforms cannot be edited via Metabot. They were created through the Query builder UI and can only be modified there.
+- **Query builder transforms are read-only**: If a user asks you to modify a Query builder transform (type="mbql"), you must inform them that Query builder transforms cannot be edited via {{metabot_name}}. They were created through the Query builder UI and can only be modified there.
## Working with SQL Snippets
diff --git a/resources/migrations/061/20260324_ai_controls.yaml b/resources/migrations/061/20260324_ai_controls.yaml
new file mode 100644
index 00000000000..1f1ea46a2c9
--- /dev/null
+++ b/resources/migrations/061/20260324_ai_controls.yaml
@@ -0,0 +1,102 @@
+## AI controls
+
+databaseChangeLog:
+ - changeSet:
+ id: v61.gasgewas
+ author: nvoxland
+ comment: Create metabot_permissions table for AI feature permissions per group
+ changes:
+ - createTable:
+ tableName: metabot_permissions
+ remarks: A table to store metabot permissions 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: perm_type
+ type: varchar(254)
+ remarks: The type of permission
+ constraints:
+ nullable: false
+ - column:
+ name: perm_value
+ type: varchar(254)
+ remarks: The value of the permission
+ constraints:
+ nullable: false
+
+ - changeSet:
+ id: v61.rr32dasd
+ author: nvoxland
+ comment: Add index on metabot_permissions.group_id
+ changes:
+ - createIndex:
+ tableName: metabot_permissions
+ indexName: idx_metabot_permissions_group_id
+ columns:
+ - column:
+ name: group_id
+
+ - changeSet:
+ id: v61.gasgewas-fk
+ author: nvoxland
+ comment: Add foreign key on metabot_permissions.group_id referencing permissions_group
+ changes:
+ - addForeignKeyConstraint:
+ baseTableName: metabot_permissions
+ baseColumnNames: group_id
+ referencedTableName: permissions_group
+ referencedColumnNames: id
+ constraintName: fk_metabot_permissions_ref_permissions_group
+ onDelete: CASCADE
+
+ - changeSet:
+ id: v61.g24da211
+ author: nvoxland
+ comment: Add unique constraint on metabot_permissions group_id and perm_type
+ changes:
+ - addUniqueConstraint:
+ tableName: metabot_permissions
+ columnNames: group_id, perm_type
+ constraintName: unique_metabot_permissions_group_id_perm_type
+
+ - changeSet:
+ id: v61.98kjjhf
+ author: edpaget
+ comment: Insert default metabot permissions (all yes) for magic user groups
+ changes:
+ - sql:
+ sql: >-
+ INSERT INTO metabot_permissions (group_id, perm_type, perm_value)
+ SELECT pg.id, d.perm_type, d.perm_value
+ FROM permissions_group pg
+ CROSS JOIN (
+ SELECT 'permission/metabot' AS perm_type, 'yes' AS perm_value
+ UNION ALL SELECT 'permission/metabot-sql-generation', 'yes'
+ UNION ALL SELECT 'permission/metabot-nlq', 'yes'
+ UNION ALL SELECT 'permission/metabot-other-tools', 'yes'
+ ) AS d
+ WHERE pg.magic_group_type IN ('admin', 'all-internal-users', 'data-analyst', 'all-external-users')
+ AND NOT EXISTS (
+ SELECT 1 FROM metabot_permissions mp
+ WHERE mp.group_id = pg.id AND mp.perm_type = d.perm_type
+ )
+ rollback:
+ - sql:
+ sql: >-
+ DELETE FROM metabot_permissions
+ WHERE group_id IN (
+ SELECT id FROM permissions_group
+ WHERE magic_group_type IN ('admin', 'all-internal-users', 'data-analyst', 'all-external-users')
+ )
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index ab5aa3e51df..4d94eae3c55 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -10,6 +10,7 @@
[metabase.api.routes.common :as api.routes.common]
[metabase.auth-identity.core :as auth-identity]
[metabase.lib.schema.temporal-bucketing :as lib.schema.temporal-bucketing]
+ [metabase.metabot.core :as metabot]
[metabase.metabot.tools.deftool :as deftool]
[metabase.metabot.tools.entity-details :as entity-details]
[metabase.metabot.tools.field-stats :as field-stats]
@@ -203,7 +204,7 @@
(api.macros/defendpoint :get "/v1/table/:id" :- ::table
"Get details for a table by ID."
- {:scope "agent:table:read"
+ {:scope metabot/agent-table-read
:tool {:name "get_table"
:description "Get details about a table including its fields, related tables, and metrics."}}
[{:keys [id]} :- [:map [:id ms/PositiveInt]]
@@ -229,7 +230,7 @@
(api.macros/defendpoint :get "/v1/table/:id/field/:field-id/values" :- ::field-values
"Get statistics and sample values for a table field."
- {:scope "agent:table:read"
+ {:scope metabot/agent-table-read
:tool {:name "get_table_field_values"
:description "Get sample values and statistics for a field in a table."}}
[{:keys [id field-id]} :- [:map
@@ -245,7 +246,7 @@
(api.macros/defendpoint :get "/v1/metric/:id" :- ::metric
"Get details for a metric by ID."
- {:scope "agent:metric:read"
+ {:scope metabot/agent-metric-read
:tool {:name "get_metric"
:description "Get details about a metric including its queryable dimensions."}}
[{:keys [id]} :- [:map [:id ms/PositiveInt]]
@@ -267,7 +268,7 @@
(api.macros/defendpoint :get "/v1/metric/:id/field/:field-id/values" :- ::field-values
"Get statistics and sample values for a metric field."
- {:scope "agent:metric:read"
+ {:scope metabot/agent-metric-read
:tool {:name "get_metric_field_values"
:description "Get sample values and statistics for a field in a metric."}}
[{:keys [id field-id]} :- [:map
@@ -286,7 +287,7 @@
Supports both term-based and semantic search queries. Results are ranked using
Reciprocal Rank Fusion when both query types are provided."
- {:scope "agent:search"
+ {:scope metabot/agent-search
:tool {:name "search"
:description "Search for tables and metrics in Metabase. Use term_queries for keyword search or semantic_queries for natural language search."
:annotations {:read-only? true}}}
@@ -576,7 +577,7 @@
For tables, supports: filters, fields, aggregations, group_by, order_by, limit.
For metrics, supports: filters, group_by (aggregation is defined by the metric)."
- {:scope "agent:query:construct"
+ {:scope metabot/agent-query-construct
:tool {:name "construct_query"
:description (str "Construct a query against a Metabase table or metric. "
"Returns an opaque query string that can be executed with execute_query.\n\n"
@@ -723,8 +724,8 @@
- On success: {:data {:cols [...] :rows [...]} :row_count N :status :completed :running_time M}
- On failure: {:status :failed :error \"message\" ...}
- Agent query row limits are enforced (200 rows per request)."
- {:scope "agent:query:execute"
+ Standard userspace query limits are enforced (2000 rows for simple queries, 10000 for aggregated)."
+ {:scope metabot/agent-query-execute
:tool {:name "execute_query"
:description "Execute a previously constructed query and return the results with column metadata, row count, and execution time."}}
[_route-params
@@ -814,9 +815,8 @@
[handler]
(fn [{:keys [headers metabase-user-id token-scopes] :as request} respond raise]
(cond
- ;; Already authenticated via X-Metabase-Session (standard middleware handled it).
- ;; Preserve any pre-existing :token-scopes (e.g., forwarded from internal MCP calls);
- ;; default to unrestricted for normal session-authenticated browser requests.
+ ;; Already authenticated via X-Metabase-Session or synthetic request (e.g. MCP dispatch).
+ ;; Preserve existing :token-scopes when present (MCP sets them on the synthetic request).
metabase-user-id
(handler (cond-> request
(not token-scopes) (assoc :token-scopes #{::scope/unrestricted}))
diff --git a/src/metabase/analytics/stats.clj b/src/metabase/analytics/stats.clj
index cf16f5ff920..3185069a219 100644
--- a/src/metabase/analytics/stats.clj
+++ b/src/metabase/analytics/stats.clj
@@ -939,7 +939,10 @@
:enabled (premium-features/enable-workspaces?)}
{:name :writable-connection
:available (premium-features/enable-writable-connection?)
- :enabled (premium-features/enable-writable-connection?)}])
+ :enabled (premium-features/enable-writable-connection?)}
+ {:name :ai-controls
+ :available (premium-features/enable-ai-controls?)
+ :enabled (premium-features/enable-ai-controls?)}])
(defn- snowplow-features
[]
diff --git a/src/metabase/api/macros.clj b/src/metabase/api/macros.clj
index a89e4d0a711..2794d81aa1e 100644
--- a/src/metabase/api/macros.clj
+++ b/src/metabase/api/macros.clj
@@ -595,11 +595,9 @@
[{:keys [metadata], :as _args} :- ::parsed-args]
(let [scope (:scope metadata)
scope-middleware (cond
- (string? scope) [(list 'metabase.api.macros.scope/enforce-scope scope)]
(= scope :unchecked) []
- :else (do (when (some? scope)
- (log/warnf "Unrecognized :scope value %s — expected a string or :unchecked" (pr-str scope)))
- ['metabase.api.macros.scope/ensure-scopes-checked]))]
+ (some? scope) [(list 'metabase.api.macros.scope/enforce-scope scope)]
+ :else ['metabase.api.macros.scope/ensure-scopes-checked])]
(cond-> (vec scope-middleware)
(:multipart metadata)
(conj 'ring.middleware.multipart-params/wrap-multipart-params))))
diff --git a/src/metabase/api/macros/scope.clj b/src/metabase/api/macros/scope.clj
index 9b5356dfeda..43c14ba2578 100644
--- a/src/metabase/api/macros/scope.clj
+++ b/src/metabase/api/macros/scope.clj
@@ -14,27 +14,21 @@
(session auth or unscoped JWT). Unlike `\"*\"` which is a valid wildcard scope that could appear in a
JWT claim, this keyword can never be confused with an externally-supplied scope string."
(:require
- [clojure.string :as str]))
+ [metabase.api-scope.core :as api-scope]
+ [metabase.config.core :as config]
+ [metabase.util.log :as log]))
(defn parse-scopes
"Parse a space-delimited OAuth scope string into a set of scope strings.
Returns nil if `scope-string` is nil, blank, or not a string."
[scope-string]
- (when (string? scope-string)
- (when-not (str/blank? scope-string)
- (into #{} (str/split (str/trim scope-string) #"\s+")))))
+ (api-scope/parse-scopes scope-string))
(defn scope-satisfied?
"Check if `token-scopes` (a set) satisfies `required-scope` (a string).
Supports hierarchical wildcards: `\"agent:*\"` covers `\"agent:workspaces\"`."
[token-scopes required-scope]
- (boolean
- (or (contains? token-scopes required-scope)
- (contains? token-scopes "*")
- (some (fn [token-scope]
- (and (str/ends-with? token-scope ":*")
- (str/starts-with? required-scope (subs token-scope 0 (dec (count token-scope))))))
- token-scopes))))
+ (api-scope/scope-matches? token-scopes required-scope))
(defn enforce-scope
"Returns a Ring middleware that checks `:token-scopes` on the request against `required-scope` (a string).
@@ -45,6 +39,10 @@
middleware knows scope enforcement already happened. This allows `enforce-scope` to be applied at the
namespace level while individual endpoints use `ensure-scopes-checked` as a safety net."
[required-scope]
+ ;; Dev-time warning only — fires at middleware construction (load time), not per-request.
+ ;; The middleware is returned regardless; this just surfaces unregistered scopes early.
+ (when (and config/is-dev? (not (api-scope/registered-scope? required-scope)))
+ (log/warnf "Unregistered scope in endpoint: %s" required-scope))
(fn [handler]
(fn [request respond raise]
(let [token-scopes (:token-scopes request)]
@@ -54,10 +52,11 @@
(handler (cond-> request
token-scopes (assoc :token-scopes-checked true))
respond raise)
- (respond {:status 403
- :headers {"Content-Type" "application/json"}
- :body {:error "unsupported_scope"
- :message (str "Token does not have required scope: " required-scope)}}))))))
+ (do (log/warnf "Scope check failed — required: %s, granted: %s" required-scope token-scopes)
+ (respond {:status 403
+ :headers {"Content-Type" "application/json"}
+ :body {:error "unsupported_scope"
+ :message "Insufficient scope for this operation."}})))))))
(defn ensure-scopes-checked
"Security middleware that prevents scoped authorization tokens from accessing endpoints that have not
diff --git a/src/metabase/api_scope/core.clj b/src/metabase/api_scope/core.clj
new file mode 100644
index 00000000000..5fd3adb0d4d
--- /dev/null
+++ b/src/metabase/api_scope/core.clj
@@ -0,0 +1,92 @@
+(ns metabase.api-scope.core
+ "Scope registry and matching for API authorization.
+
+ Provides a `defscope` macro that registers named scopes with translatable
+ descriptions, a `scope-matches?` function for hierarchical wildcard matching,
+ and a public API for enumerating registered scopes (for consent screens, admin UIs)."
+ (:require
+ [clojure.string :as str]))
+
+(set! *warn-on-reflection* true)
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Scope registry
+;;; ──────────────────────────────────────────────────────────────────
+
+(defonce ^:private scope-registry
+ (atom {}))
+
+(defn register-scope!
+ "Register a scope string with a description thunk. Called by [[defscope]]."
+ [scope-string description-fn scope-var]
+ (swap! scope-registry assoc scope-string
+ {:description description-fn
+ :var scope-var}))
+
+(defmacro defscope
+ "Define and register a scope. Creates a var whose value is the scope string and
+ registers it in the global scope registry with a translatable description.
+
+ (defscope agent-sql-create \"agent:sql:create\"
+ (deferred-tru \"Create SQL queries\"))"
+ [var-sym scope-string description]
+ `(do
+ (def ~var-sym ~scope-string)
+ (register-scope! ~scope-string (fn [] ~description) (var ~var-sym))))
+
+(defn registered-scope?
+ "Returns true if the given scope string has been registered via [[defscope]]."
+ [scope-string]
+ (contains? @scope-registry scope-string))
+
+(defn all-scopes
+ "Returns a vector of maps describing all registered scopes, suitable for consent
+ screens. Each map has `:scope` (string) and `:description` (localized string)."
+ []
+ (mapv (fn [[scope-str {:keys [description]}]]
+ {:scope scope-str :description (description)})
+ @scope-registry))
+
+(defn scope-description
+ "Returns the localized description for a registered scope string, or nil."
+ [scope-string]
+ (when-let [entry (get @scope-registry scope-string)]
+ ((:description entry))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Scope matching
+;;; ──────────────────────────────────────────────────────────────────
+
+(def unrestricted
+ "A scope set that satisfies any required scope. Use only when explicitly
+ granting full access (e.g. superuser context). This is distinct from
+ category wildcards like `\"agent:*\"`, which only cover scopes under
+ the `agent` prefix."
+ #{"*"})
+
+(defn scope-matches?
+ "Check if `granted-scopes` (a set of strings) satisfies `required-scope`
+ (a string). Supports hierarchical wildcards on the grant side:
+ `\"agent:sql:*\"` covers `\"agent:sql:create\"`.
+
+ Returns true when:
+ - `granted-scopes` contains `required-scope` exactly, or
+ - `granted-scopes` contains `\"*\"` (unrestricted), or
+ - `granted-scopes` contains a wildcard prefix that covers `required-scope`."
+ [granted-scopes required-scope]
+ (boolean
+ (or (contains? granted-scopes required-scope)
+ (contains? granted-scopes "*")
+ (some (fn [scope]
+ (and (str/ends-with? scope ":*")
+ (str/starts-with? required-scope
+ (subs scope 0 (dec (count scope))))))
+ granted-scopes))))
+
+(defn parse-scopes
+ "Parse a space-delimited OAuth scope string into a set of scope strings.
+ Returns nil if `scope-string` is nil, blank, or not a string."
+ [scope-string]
+ (when (string? scope-string)
+ (when-not (str/blank? scope-string)
+ (into #{} (str/split (str/trim scope-string) #"\s+")))))
diff --git a/src/metabase/api_scope/init.clj b/src/metabase/api_scope/init.clj
new file mode 100644
index 00000000000..7d936abe1bf
--- /dev/null
+++ b/src/metabase/api_scope/init.clj
@@ -0,0 +1,3 @@
+(ns metabase.api-scope.init
+ (:require
+ [metabase.api-scope.core]))
diff --git a/src/metabase/cmd/copy.clj b/src/metabase/cmd/copy.clj
index 51b99e22081..1f985c1cefb 100644
--- a/src/metabase/cmd/copy.clj
+++ b/src/metabase/cmd/copy.clj
@@ -135,7 +135,8 @@
:model/MetabotMessage
:model/MetabotPrompt]
(when config/ee-available?
- [:model/Sandbox
+ [:model/MetabotPermissions
+ :model/Sandbox
:model/Tenant
:model/ConnectionImpersonation])))
diff --git a/src/metabase/core/init.clj b/src/metabase/core/init.clj
index 9dd7a5a7ff4..090a4f4c40a 100644
--- a/src/metabase/core/init.clj
+++ b/src/metabase/core/init.clj
@@ -9,6 +9,7 @@
[metabase.actions.init]
[metabase.activity-feed.init]
[metabase.analytics.init]
+ [metabase.api-scope.init]
[metabase.api.init]
[metabase.app-db.init]
[metabase.appearance.init]
diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.clj
index 69e6bb03416..d0dcdf9f61e 100644
--- a/src/metabase/mcp/tools.clj
+++ b/src/metabase/mcp/tools.clj
@@ -5,6 +5,7 @@
[clojure.core.async :as a]
[clojure.string :as str]
[metabase.agent-api.api :as agent-api]
+ [metabase.api-scope.core :as api-scope]
[metabase.api.common :as api]
[metabase.api.macros.defendpoint.tools-manifest :as tools-manifest]
[metabase.api.macros.scope :as scope]
@@ -40,18 +41,13 @@
- nil token-scopes → always matches (internal callers)
- ::scope/unrestricted in token-scopes → always matches
- nil tool-scope → only matches nil or unrestricted token-scopes
- - wildcard scopes like \"agent:*\" match any tool scope starting with \"agent:\""
+ - Delegates wildcard/exact matching to [[api-scope/scope-matches?]]"
[token-scopes tool-scope]
(or (nil? token-scopes)
(contains? token-scopes ::scope/unrestricted)
- (when (some? tool-scope)
- (or (contains? token-scopes tool-scope)
- (some (fn [s]
- (when (string? s)
- (when-let [prefix (when (str/ends-with? s ":*")
- (subs s 0 (dec (count s))))]
- (str/starts-with? tool-scope prefix))))
- token-scopes)))))
+ (when (and (some? tool-scope)
+ (api-scope/scope-matches? token-scopes tool-scope))
+ true)))
(defn list-tools
"Return the tool definitions suitable for MCP `tools/list` responses.
@@ -189,14 +185,13 @@
(defn call-tool
"Dispatch an MCP `tools/call` request to the appropriate handler.
`token-scopes` from the original MCP session are propagated to the synthetic
- agent-api request so that scope restrictions are preserved.
- Returns MCP content maps (text-content on success, error-content on failure)."
+ agent-api request so that scope restrictions are enforced by the agent API's
+ `defendpoint` middleware.
+ Returns MCP content on success, or error content on failure."
[token-scopes tool-name arguments]
(if-let [tool-def (get (tool-index) tool-name)]
- (if-not (scope-matches? token-scopes (:scope tool-def))
- (error-content (str "Insufficient scope to call tool: " tool-name))
- (try
- (dispatch-via-agent-api tool-def arguments token-scopes)
- (catch Exception e
- (error-content (or (ex-message e) "Internal error")))))
+ (try
+ (dispatch-via-agent-api tool-def arguments token-scopes)
+ (catch Exception e
+ (error-content (or (ex-message e) "Internal error"))))
(error-content (str "Unknown tool: " tool-name))))
diff --git a/src/metabase/metabot/agent/core.clj b/src/metabase/metabot/agent/core.clj
index 8ced532870d..06c4c8dca76 100644
--- a/src/metabase/metabot/agent/core.clj
+++ b/src/metabase/metabot/agent/core.clj
@@ -4,6 +4,8 @@
[clojure.java.io :as io]
[clojure.string :as str]
[metabase.analytics.prometheus :as prometheus]
+ [metabase.api-scope.core :as api-scope]
+ [metabase.api.common :as api]
[metabase.config.core :as config]
[metabase.metabot.agent.analytics :as agent-analytics]
[metabase.metabot.agent.links :as links]
@@ -11,6 +13,7 @@
[metabase.metabot.agent.messages :as messages]
[metabase.metabot.agent.profiles :as profiles]
[metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.self :as self]
[metabase.metabot.settings :as metabot.settings]
[metabase.metabot.tools :as tools]
@@ -534,6 +537,27 @@
:version 1
:data debug-log})
+(def ^:private profile-id->required-permission
+ "Map from profile-id to the metabot permission that must be `:yes` for a user
+ to use that profile. Profiles not listed here have no profile-level permission gate."
+ {:sql :permission/metabot-sql-generation
+ :nlq :permission/metabot-nlq
+ :transforms_codegen :permission/metabot-sql-generation
+ :document-generate-content :permission/metabot-other-tools})
+
+(defn- check-metabot-access!
+ "Throw a 403 if the user's metabot permissions do not grant access to the
+ requested profile. First checks the base metabot on/off permission, then
+ the profile-specific permission."
+ [profile-id perms]
+ ;; Base metabot on/off check — blocks ALL profiles when metabot is disabled
+ (api/check (= :yes (:permission/metabot perms))
+ [403 "You do not have permission to use the AI assistant."])
+ ;; Profile-specific permission check
+ (when-let [required-perm (profile-id->required-permission profile-id)]
+ (api/check (= :yes (get perms required-perm))
+ [403 (format "You do not have permission to use the %s assistant." (name profile-id))])))
+
(mu/defn run-agent-loop
"Run agent loop, returning a reducible of parts.
@@ -557,7 +581,15 @@
debug? (:debug? opts)
labels {:profile-id (name profile-id)}
track-user-intent? (and (metabot.settings/llm-metabot-internal-tasks-enabled?)
- (some-> opts :tracking-opts :track-user-intent?))]
+ (some-> opts :tracking-opts :track-user-intent?))
+ perms (or scope/*current-user-metabot-permissions*
+ (if api/*is-superuser?*
+ scope/all-yes-permissions
+ (scope/resolve-user-permissions api/*current-user-id*)))
+ scopes (if api/*is-superuser?*
+ api-scope/unrestricted
+ (scope/user-metabot-perms->scopes perms))]
+ (check-metabot-access! profile-id perms)
(reify clojure.lang.IReduceInit
(reduce [_ rf init]
(with-span :info {:name :metabot.agent/run-agent-loop
@@ -565,7 +597,9 @@
:msg-count (count (:messages opts))}
(prometheus/inc! :metabase-metabot/agent-requests labels)
(let [start-ms (u/start-timer)]
- (binding [*debug-log* (when debug? (atom []))]
+ (binding [*debug-log* (when debug? (atom []))
+ scope/*current-user-scope* scopes
+ scope/*current-user-metabot-permissions* perms]
(try
(let [agent (init-agent opts)
_ (when track-user-intent?
diff --git a/src/metabase/metabot/agent/profiles.clj b/src/metabase/metabot/agent/profiles.clj
index ee1ecf7dbfe..161c156a9e7 100644
--- a/src/metabase/metabot/agent/profiles.clj
+++ b/src/metabase/metabot/agent/profiles.clj
@@ -9,6 +9,8 @@
(:require
[clojure.string :as str]
[malli.error :as me]
+ [metabase.api-scope.core :as api-scope]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.settings :as metabot.settings]
[metabase.metabot.tools :as tools]
[metabase.premium-features.core :as premium-features]
@@ -35,6 +37,11 @@
{:tool-var tool-var
:metadata (meta tool-var)
:errors (me/humanize (mu/explain tool-var-schema tool-var))})))
+ (when-let [required-scope (:scope (meta tool-var))]
+ (when-not (api-scope/registered-scope? required-scope)
+ (throw (ex-info (str "Tool has unregistered scope: " required-scope)
+ {:tool-var tool-var
+ :scope required-scope}))))
true)
(mu/defn ^:private register-profile!
@@ -214,6 +221,17 @@
(every? capabilities-set (:capabilities (meta tool-var))))
tool-vars)))
+(defn- filter-by-scope
+ "Filter tool vars by the current user's scope set.
+ Removes tools whose `:scope` metadata is not satisfied by `*current-user-scope*`.
+ Tools without `:scope` metadata pass through."
+ [tool-vars]
+ (filter (fn [tool-var]
+ (let [required-scope (:scope (meta tool-var))]
+ (or (nil? required-scope)
+ (api-scope/scope-matches? scope/*current-user-scope* required-scope))))
+ tool-vars))
+
(defn- ee-feature-available?
"Check if a tool's :ee-feature is available (or if the tool has no :ee-feature gate)."
[tool-var]
@@ -237,12 +255,14 @@
(assoc profile :model (metabot.settings/llm-metabot-provider))))
(defn get-tools-for-profile
- "Get tool registry filtered by profile configuration and user capabilities.
+ "Get tool registry filtered by profile configuration, user capabilities, and scope.
Filters out EE-only tools when the feature is not available, then filters by
- capabilities. Returns a map of tool-name -> tool-var."
+ capabilities, then filters by `*current-user-scope*`. Returns a map of
+ tool-name -> tool-var."
[profile-id capabilities]
(some-> (get-profile profile-id)
:tools
(->> (filter ee-feature-available?))
(filter-by-capabilities capabilities)
+ filter-by-scope
tool-map))
diff --git a/src/metabase/metabot/agent/prompts.clj b/src/metabase/metabot/agent/prompts.clj
index d79ff7d02a1..b576b6bd000 100644
--- a/src/metabase/metabot/agent/prompts.clj
+++ b/src/metabase/metabot/agent/prompts.clj
@@ -9,6 +9,8 @@
- Template caching for performance"
(:require
[clojure.java.io :as io]
+ [metabase.metabot.scope :as scope]
+ [metabase.metabot.settings :as metabot.settings]
[metabase.util.log :as log]
[selmer.parser :as selmer]))
@@ -221,19 +223,36 @@
(get context :viewing-context))
recent-views (or (get context :recent_views)
(get context :recent-views))
- template-context {:current_time current-time
+ perms (or scope/*current-user-metabot-permissions*
+ scope/perm-type-defaults)
+ has-sql? (= :yes (:permission/metabot-sql-generation perms))
+ has-nlq? (= :yes (:permission/metabot-nlq perms))
+ template-context {:metabot_name (metabot.settings/metabot-name)
+ :current_time current-time
:current_user_info current-user-info
:first_day_of_week first-day-of-week
:sql_dialect sql-dialect
:sql_dialect_instructions dialect-instructions
:tool_instructions tool-instructions
:viewing_context viewing-context
- :recent_views recent-views}]
+ :recent_views recent-views
+ :has_sql_generation has-sql?
+ :has_nlq has-nlq?
+ :has_query_tools (or has-sql? has-nlq?)
+ :has_other_tools (= :yes (:permission/metabot-other-tools perms))
+ :custom_instructions (not-empty
+ (case template-name
+ "natural-language-querying-only.selmer"
+ (metabot.settings/metabot-nlq-system-prompt)
+ "sql-querying-only.selmer"
+ (metabot.settings/metabot-sql-system-prompt)
+ ;; default: internal.selmer and any other templates
+ (metabot.settings/metabot-chat-system-prompt)))}]
(render-system-prompt template template-context))
;; Fallback if template not found
(do
(log/error "System prompt template not found:" template-name)
- "You are Metabot, a data analysis assistant for Metabase."))))
+ (str "You are " (metabot.settings/metabot-name) ", a data analysis assistant for Metabase.")))))
(defn inject-context
"Prepends a formatted context to a string, message."
diff --git a/src/metabase/metabot/agent/user_context.clj b/src/metabase/metabot/agent/user_context.clj
index 5c2bdd2866e..0deebdf4b2f 100644
--- a/src/metabase/metabot/agent/user_context.clj
+++ b/src/metabase/metabot/agent/user_context.clj
@@ -166,7 +166,7 @@
(str id)
(str/join ", " (map-indexed (fn [idx _] (str id "-" idx)) chart_configs)))))
-(defn format-native-query
+(defn- format-native-query
"Format viewing `item`"
[item]
(assert (lib/native-only-query? (:query item))
diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.clj
index f8c9948efdf..a25bda6a537 100644
--- a/src/metabase/metabot/api.clj
+++ b/src/metabase/metabot/api.clj
@@ -12,6 +12,7 @@
[metabase.metabot.agent.core :as agent]
[metabase.metabot.api.document]
[metabase.metabot.api.metabot]
+ [metabase.metabot.api.permissions]
[metabase.metabot.config :as metabot.config]
[metabase.metabot.context :as metabot.context]
[metabase.metabot.envelope :as metabot.envelope]
@@ -425,8 +426,9 @@
"`/api/metabot` routes."
(handlers/routes
(handlers/route-map-handler
- {"/metabot" metabase.metabot.api.metabot/routes
- "/document" metabase.metabot.api.document/routes
+ {"/metabot" metabase.metabot.api.metabot/routes
+ "/permissions" metabase.metabot.api.permissions/routes
+ "/document" metabase.metabot.api.document/routes
;; premium check happens in the route so we still ack events to prevent slack retrying
"/slack" metabase.slackbot.api/routes})
(api.macros/ns-handler *ns* +auth)))
diff --git a/src/metabase/metabot/api/permissions.clj b/src/metabase/metabot/api/permissions.clj
new file mode 100644
index 00000000000..1df0d5d2594
--- /dev/null
+++ b/src/metabase/metabot/api/permissions.clj
@@ -0,0 +1,35 @@
+(ns metabase.metabot.api.permissions
+ "`/api/metabot/permissions` routes"
+ (:require
+ [metabase.api.common :as api]
+ [metabase.api.macros :as api.macros]
+ [metabase.api.routes.common :refer [+auth]]
+ [metabase.metabot.scope :as scope]))
+
+(defn- simplify-permissions
+ "Strip the namespace from permission keywords for a flatter JSON response.
+ e.g. {:permission/metabot :yes} → {:metabot :yes}"
+ [perms]
+ (into {} (map (fn [[k v]] [(keyword (name k)) v])) perms))
+
+(def ^:private user-permissions-response-schema
+ [:map
+ [:permissions
+ [:map
+ [:metabot [:enum :yes :no]]
+ [:metabot-sql-generation [:enum :yes :no]]
+ [:metabot-nlq [:enum :yes :no]]
+ [:metabot-other-tools [:enum :yes :no]]]]])
+
+(api.macros/defendpoint :get "/user-permissions" :- user-permissions-response-schema
+ "Return the current user's resolved metabot permissions, taking the most
+ permissive value across all their groups."
+ []
+ {:permissions (simplify-permissions
+ (if api/*is-superuser?*
+ scope/all-yes-permissions
+ (scope/resolve-user-permissions api/*current-user-id*)))})
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/metabot/permissions` routes."
+ (api.macros/ns-handler *ns* +auth))
diff --git a/src/metabase/metabot/core.clj b/src/metabase/metabot/core.clj
index 1e22e3c21bb..8f0abfb7173 100644
--- a/src/metabase/metabot/core.clj
+++ b/src/metabase/metabot/core.clj
@@ -2,11 +2,18 @@
"API namespace for the `metabase.metabot` module."
(:require
[metabase.metabot.api]
+ [metabase.metabot.scope]
[potemkin :as p]))
(p/import-vars
[metabase.metabot.api
- routes])
+ routes]
+ [metabase.metabot.scope
+ agent-metric-read
+ agent-query-construct
+ agent-query-execute
+ agent-search
+ agent-table-read])
;; TODO: Port analyze-chart to use the native LLM infrastructure
;; instead of the deleted `metabase.metabot.client`.
diff --git a/src/metabase/metabot/init.clj b/src/metabase/metabot/init.clj
index 779cd86bce0..45d5d592ac3 100644
--- a/src/metabase/metabot/init.clj
+++ b/src/metabase/metabot/init.clj
@@ -1,4 +1,5 @@
(ns metabase.metabot.init
(:require
+ [metabase.metabot.scope]
[metabase.metabot.settings]
[metabase.metabot.task.suggested-prompts-generator]))
diff --git a/src/metabase/metabot/scope.clj b/src/metabase/metabot/scope.clj
new file mode 100644
index 00000000000..74f256ca2f8
--- /dev/null
+++ b/src/metabase/metabot/scope.clj
@@ -0,0 +1,194 @@
+(ns metabase.metabot.scope
+ "Metabot-specific scope declarations and permission-to-scope mapping.
+
+ Generic scope infrastructure (registry, matching, `defscope`) lives in
+ [[metabase.api-scope.core]]. This namespace declares the concrete `agent:*`
+ scopes used by metabot tools and maps metabot permission types to wildcard
+ scope grants."
+ (:require
+ [metabase.api-scope.core :as api-scope]
+ [metabase.premium-features.core :refer [defenterprise]]
+ [metabase.util.i18n :refer [deferred-tru]]))
+
+(set! *warn-on-reflection* true)
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Scope declarations
+;;; ──────────────────────────────────────────────────────────────────
+
+;; SQL
+(api-scope/defscope agent-sql-create "agent:sql:create"
+ (deferred-tru "Create SQL queries"))
+(api-scope/defscope agent-sql-edit "agent:sql:edit"
+ (deferred-tru "Edit SQL queries"))
+(api-scope/defscope agent-sql-read "agent:sql:read"
+ (deferred-tru "Read and clarify SQL queries"))
+
+;; Notebook / Query
+(api-scope/defscope agent-notebook-create "agent:notebook:create"
+ (deferred-tru "Create notebook queries"))
+(api-scope/defscope agent-query "agent:query"
+ (deferred-tru "Construct and execute queries"))
+(api-scope/defscope agent-query-construct "agent:query:construct"
+ (deferred-tru "Construct queries"))
+(api-scope/defscope agent-query-execute "agent:query:execute"
+ (deferred-tru "Execute queries"))
+
+;; Transforms
+(api-scope/defscope agent-transforms-read "agent:transforms:read"
+ (deferred-tru "View transforms"))
+(api-scope/defscope agent-transforms-write "agent:transforms:write"
+ (deferred-tru "Create and edit transforms"))
+
+;; Snippets
+(api-scope/defscope agent-snippets-read "agent:snippets:read"
+ (deferred-tru "View SQL snippets"))
+
+;; Dashboard
+(api-scope/defscope agent-dashboard-create "agent:dashboard:create"
+ (deferred-tru "Create dashboards"))
+(api-scope/defscope agent-dashboard-subscribe "agent:dashboard:subscribe"
+ (deferred-tru "Subscribe to dashboard alerts"))
+
+;; Document
+(api-scope/defscope agent-document-read "agent:document:read"
+ (deferred-tru "View documents"))
+(api-scope/defscope agent-document-create "agent:document:create"
+ (deferred-tru "Create documents"))
+
+;; Visualization
+(api-scope/defscope agent-viz-read "agent:viz:read"
+ (deferred-tru "Analyze charts and visualizations"))
+(api-scope/defscope agent-viz-create "agent:viz:create"
+ (deferred-tru "Create charts and visualizations"))
+(api-scope/defscope agent-viz-edit "agent:viz:edit"
+ (deferred-tru "Edit charts and visualizations"))
+(api-scope/defscope agent-viz-navigate "agent:viz:navigate"
+ (deferred-tru "Navigate to visualizations"))
+
+;; Alert
+(api-scope/defscope agent-alert-create "agent:alert:create"
+ (deferred-tru "Create alerts"))
+
+;; Search
+(api-scope/defscope agent-search "agent:search"
+ (deferred-tru "Search for content"))
+
+;; Metadata
+(api-scope/defscope agent-metadata-read "agent:metadata:read"
+ (deferred-tru "View database metadata"))
+
+;; Resource
+(api-scope/defscope agent-resource-read "agent:resource:read"
+ (deferred-tru "View resources"))
+
+;; Todo
+(api-scope/defscope agent-todo-read "agent:todo:read"
+ (deferred-tru "View todos"))
+(api-scope/defscope agent-todo-write "agent:todo:write"
+ (deferred-tru "Create and edit todos"))
+
+;; Table
+(api-scope/defscope agent-table-read "agent:table:read"
+ (deferred-tru "View table metadata and field values"))
+
+;; Metric
+(api-scope/defscope agent-metric-read "agent:metric:read"
+ (deferred-tru "View metric definitions"))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Metabot permission type definitions
+;;; ──────────────────────────────────────────────────────────────────
+
+(def metabot-permissions
+ "Metabot permission definitions. Values are ordered from most permissive to least permissive."
+ {:permission/metabot {:values [:yes :no]}
+ :permission/metabot-sql-generation {:values [:yes :no]}
+ :permission/metabot-nlq {:values [:yes :no]}
+ :permission/metabot-other-tools {:values [:yes :no]}})
+
+(def perm-types
+ "The set of defined metabot permission types."
+ (set (keys metabot-permissions)))
+
+(def perm-type-defaults
+ "Default values for each metabot permission type."
+ {:permission/metabot :no
+ :permission/metabot-sql-generation :no
+ :permission/metabot-nlq :no
+ :permission/metabot-other-tools :no})
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Metabot-specific scope state
+;;; ──────────────────────────────────────────────────────────────────
+
+(def ^:dynamic *current-user-scope*
+ "Set of scope strings granted to the current user. Defaults to `#{}` (no
+ permissions granted). Bind this in the request path once scope resolution
+ is wired up."
+ #{})
+
+(def ^:dynamic *current-user-metabot-permissions*
+ "Map of metabot permission type to value for the current user.
+ e.g. `{:permission/metabot-sql-generation :yes, :permission/metabot-nlq :no, ...}`.
+ Bind in the request path alongside `*current-user-scope*`. When nil,
+ consumers should fall back to `perm-type-defaults`."
+ nil)
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Permission → Scope mapping
+;;; ──────────────────────────────────────────────────────────────────
+
+(def ^:private perm-type->scopes
+ "Map from metabot permission type to the wildcard scope strings granted when
+ that permission is `:yes`."
+ {:permission/metabot-sql-generation #{"agent:sql:*" "agent:transforms:*" "agent:snippets:*"}
+ :permission/metabot-nlq #{"agent:notebook:*" "agent:query:*" "agent:table:*" "agent:metric:*"}
+ :permission/metabot-other-tools #{"agent:viz:*" "agent:dashboard:*" "agent:document:*" "agent:alert:*"}})
+
+(def always-granted-scopes
+ "Scopes granted to every user regardless of permissions."
+ #{"agent:search" "agent:resource:*" "agent:todo:*" "agent:metadata:*"})
+
+(def all-yes-permissions
+ "Permissions map granting all permissions. Used for superuser context."
+ {:permission/metabot :yes
+ :permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :yes
+ :permission/metabot-other-tools :yes})
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Permission resolution
+;;; ──────────────────────────────────────────────────────────────────
+
+(defn most-permissive-value
+ "Given a perm type and a collection of values from different groups,
+ return the most permissive value. Values are ordered most→least permissive
+ in `metabot-permissions`."
+ [perm-type values]
+ (let [ordering (get-in metabot-permissions [perm-type :values])
+ rank (into {} (map-indexed (fn [i v] [v i]) ordering))]
+ ;; Lowest index = most permissive
+ (first (sort-by #(get rank % Integer/MAX_VALUE) values))))
+
+(defenterprise resolve-user-permissions
+ "Resolve the effective metabot permissions for a user by taking the most
+ permissive value across all their groups. Returns a map of perm-type → value,
+ with defaults filled in for any unset permission types.
+ OSS implementation returns defaults for all users."
+ metabase-enterprise.metabot.permissions
+ [_user-id]
+ all-yes-permissions)
+
+(defn user-metabot-perms->scopes
+ "Convert a resolved metabot permissions map into a set of scope strings.
+ Maps `:yes` permissions to the corresponding wildcard scope sets and always
+ includes `always-granted-scopes`."
+ [perms]
+ (reduce-kv
+ (fn [acc perm-type perm-value]
+ (if (and (= :yes perm-value) (contains? perm-type->scopes perm-type))
+ (into acc (get perm-type->scopes perm-type))
+ acc))
+ always-granted-scopes
+ (or perms perm-type-defaults)))
diff --git a/src/metabase/metabot/settings.clj b/src/metabase/metabot/settings.clj
index 444f037743b..31f7e23444f 100644
--- a/src/metabase/metabot/settings.clj
+++ b/src/metabase/metabot/settings.clj
@@ -21,6 +21,66 @@
:export? true
:doc false)
+(defsetting metabot-name
+ (deferred-tru "The display name for Metabot.")
+ :type :string
+ :default "Metabot"
+ :visibility :public
+ :encryption :no
+ :export? true
+ :feature :ai-controls
+ :doc false)
+
+(defsetting metabot-icon
+ (deferred-tru "The icon for Metabot.")
+ :type :string
+ :default "metabot"
+ :visibility :public
+ :encryption :no
+ :export? true
+ :feature :ai-controls
+ :doc false)
+
+(defsetting metabot-show-illustrations
+ (deferred-tru "Whether to show Metabot illustrations in the UI.")
+ :type :boolean
+ :default true
+ :visibility :public
+ :encryption :no
+ :export? true
+ :feature :ai-controls
+ :doc false)
+
+(defsetting metabot-chat-system-prompt
+ (deferred-tru "Custom system prompt for the Metabot chat (sidebar AI chat) experience.")
+ :type :string
+ :default ""
+ :visibility :admin
+ :encryption :no
+ :export? true
+ :feature :ai-controls
+ :doc false)
+
+(defsetting metabot-nlq-system-prompt
+ (deferred-tru "Custom system prompt for the natural language query (AI exploration) experience.")
+ :type :string
+ :default ""
+ :visibility :admin
+ :encryption :no
+ :export? true
+ :feature :ai-controls
+ :doc false)
+
+(defsetting metabot-sql-system-prompt
+ (deferred-tru "Custom system prompt for the SQL generation experience.")
+ :type :string
+ :default ""
+ :visibility :admin
+ :encryption :no
+ :export? true
+ :feature :ai-controls
+ :doc false)
+
(defsetting embedded-metabot-enabled?
(deferred-tru "Whether Metabot is enabled for embedding.")
:type :boolean
diff --git a/src/metabase/metabot/tools.clj b/src/metabase/metabot/tools.clj
index 442cf55a70c..fa6bc8c2006 100644
--- a/src/metabase/metabot/tools.clj
+++ b/src/metabase/metabot/tools.clj
@@ -6,6 +6,8 @@
`:capabilities`, `:prompt`, `:decode`, and `:system-instructions`. The var itself
is a function that takes the tool arguments and returns a result map."
(:require
+ [metabase.api-scope.core :as api-scope]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.analyze-chart :as tools.analyze-chart]
[metabase.metabot.tools.autogen-dashboard :as tools.autogen-dashboard]
[metabase.metabot.tools.charts :as tools.charts]
@@ -26,6 +28,7 @@
[metabase.metabot.tools.subscriptions :as tools.subscriptions]
[metabase.metabot.tools.todo :as tools.todo]
[metabase.metabot.tools.transforms :as tools.transforms]
+ [metabase.util.log :as log]
[potemkin :as p]))
(set! *warn-on-reflection* true)
@@ -96,6 +99,18 @@
"document_schema_collect" "document_construct_sql_chart" "document_construct_model_chart"
"create_alert" "create_dashboard_subscription" "static_viz"})
+(defn- wrap-with-scope-check
+ "Wrap a tool function with a scope check. Returns a function that checks
+ `*current-user-scope*` against `required-scope` before calling `f`.
+ Returns a denial message if the scope is not satisfied."
+ [f tool-name required-scope]
+ (fn [args]
+ (if (api-scope/scope-matches? scope/*current-user-scope* required-scope)
+ (f args)
+ (do (log/warnf "Scope check failed for tool %s — required: %s, granted: %s"
+ tool-name required-scope scope/*current-user-scope*)
+ {:output "You do not have permission to use this tool."}))))
+
(defn wrap-tools-with-state
"Wrap state-dependent tools with access to the memory atom.
Tools in `state-dependent-tools` will have access to the memory atom
@@ -111,22 +126,28 @@
[tools memory-atom metabot-id]
(reduce-kv
(fn [acc tool-name tool-var]
- (let [m (meta tool-var)
- tool-def {:tool-name (:tool-name m)
- :doc (:doc m)
- :schema (:schema m)
- :prompt (:prompt m)
- :decode (:decode m)
- :system-instructions (:system-instructions m)
- :capabilities (:capabilities m)
- :fn (if (contains? state-dependent-tools tool-name)
- (fn [args]
- (binding [shared/*memory-atom* memory-atom
- shared/*metabot-id* metabot-id]
- (tool-var args)))
- (fn [args]
- (binding [shared/*metabot-id* metabot-id]
- (tool-var args))))}]
+ (let [m (meta tool-var)
+ base-fn (if (contains? state-dependent-tools tool-name)
+ (fn [args]
+ (binding [shared/*memory-atom* memory-atom
+ shared/*metabot-id* metabot-id]
+ (tool-var args)))
+ (fn [args]
+ (binding [shared/*metabot-id* metabot-id]
+ (tool-var args))))
+ tool-scope (:scope m)
+ tool-fn (if tool-scope
+ (wrap-with-scope-check base-fn tool-name tool-scope)
+ base-fn)
+ tool-def {:tool-name (:tool-name m)
+ :doc (:doc m)
+ :schema (:schema m)
+ :prompt (:prompt m)
+ :decode (:decode m)
+ :system-instructions (:system-instructions m)
+ :capabilities (:capabilities m)
+ :scope (:scope m)
+ :fn tool-fn}]
(assoc acc tool-name tool-def)))
{}
tools))
diff --git a/src/metabase/metabot/tools/analyze_chart.clj b/src/metabase/metabot/tools/analyze_chart.clj
index 74eb2e50885..0312d62693d 100644
--- a/src/metabase/metabot/tools/analyze_chart.clj
+++ b/src/metabase/metabot/tools/analyze_chart.clj
@@ -5,6 +5,7 @@
series data in chart_configs, which is seeded into agent memory during
initialization. This avoids re-executing queries."
(:require
+ [metabase.metabot.scope :as scope]
[metabase.metabot.stats.core :as stats.core]
[metabase.metabot.stats.repr :as stats.repr]
[metabase.metabot.tools.shared :as shared]
@@ -50,7 +51,8 @@ Do not use headers (##). Do not list statistics. Do not analyze series separatel
stringify-series-keys))
(mu/defn ^{:tool-name "analyze_chart"
- :prompt "analyze_chart"}
+ :prompt "analyze_chart"
+ :scope scope/agent-viz-read}
analyze-chart-tool
"Compute statistics and generate analysis context for a chart.
Use this to analyze trends, outliers, volatility, and patterns in chart data.
diff --git a/src/metabase/metabot/tools/autogen_dashboard.clj b/src/metabase/metabot/tools/autogen_dashboard.clj
index 08b9848e694..0bd094518c8 100644
--- a/src/metabase/metabot/tools/autogen_dashboard.clj
+++ b/src/metabase/metabot/tools/autogen_dashboard.clj
@@ -2,6 +2,7 @@
"Autogenerated dashboard tool wrappers."
(:require
[clojure.string :as str]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.shared :as shared]
[metabase.util.log :as log]
[metabase.util.malli :as mu]
@@ -125,7 +126,8 @@
[:query_id {:optional true} [:maybe :string]]
[:report_id {:optional true} [:maybe :int]]]]])
-(mu/defn ^{:tool-name "create_autogenerated_dashboard"}
+(mu/defn ^{:tool-name "create_autogenerated_dashboard"
+ :scope scope/agent-dashboard-create}
create-autogenerated-dashboard-tool
"Create an automatically generated dashboard using Metabase's X-ray feature.
diff --git a/src/metabase/metabot/tools/charts.clj b/src/metabase/metabot/tools/charts.clj
index 8a1aa233ec5..2c198d32201 100644
--- a/src/metabase/metabot/tools/charts.clj
+++ b/src/metabase/metabot/tools/charts.clj
@@ -4,6 +4,7 @@
[medley.core :as m]
[metabase.metabot.agent.links :as links]
[metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.charts.create :as create-chart-tools]
[metabase.metabot.tools.charts.edit :as edit-chart-tools]
[metabase.metabot.tools.shared :as shared]
@@ -32,7 +33,8 @@
[:viz_settings [:map {:closed true}
[:chart_type chart-type-enum]]]])
-(mu/defn ^{:tool-name "create_chart"}
+(mu/defn ^{:tool-name "create_chart"
+ :scope scope/agent-viz-create}
create-chart-tool
"Create a chart from a query.
@@ -60,7 +62,8 @@
[:new_viz_settings [:map {:closed true}
[:chart_type chart-type-enum]]]])
-(mu/defn ^{:tool-name "edit_chart"}
+(mu/defn ^{:tool-name "edit_chart"
+ :scope scope/agent-viz-edit}
edit-chart-tool
"Edit an existing chart's visualization type.
diff --git a/src/metabase/metabot/tools/clarification.clj b/src/metabase/metabot/tools/clarification.clj
index deec472b5bb..8ec2416953f 100644
--- a/src/metabase/metabot/tools/clarification.clj
+++ b/src/metabase/metabot/tools/clarification.clj
@@ -2,6 +2,7 @@
"Clarification tool wrappers."
(:require
[clojure.string :as str]
+ [metabase.metabot.scope :as scope]
[metabase.util.log :as log]
[metabase.util.malli :as mu]))
@@ -36,7 +37,8 @@
(when (seq options)
(str "\n\nOptions:\n" (str/join "\n" (map #(str "- " %) options))))))
-(mu/defn ^{:tool-name "ask_for_sql_clarification"}
+(mu/defn ^{:tool-name "ask_for_sql_clarification"
+ :scope scope/agent-sql-read}
ask-for-sql-clarification-tool
"Ask the user for clarification about their SQL query request.
diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.clj
index 113f71028ba..9f564cd4d7a 100644
--- a/src/metabase/metabot/tools/construct.clj
+++ b/src/metabase/metabot/tools/construct.clj
@@ -6,6 +6,7 @@
[malli.transform :as mtx]
[metabase.lib.core :as lib]
[metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tmpl :as te]
[metabase.metabot.tools.charts.create :as create-chart-tools]
[metabase.metabot.tools.filters :as filter-tools]
@@ -317,7 +318,8 @@
{:output (str "Unsupported query_type: " query-type)})))
(mu/defn ^{:tool-name "construct_notebook_query"
- :decode decode-tool-args}
+ :decode decode-tool-args
+ :scope scope/agent-notebook-create}
construct-notebook-query-tool
"Construct and visualize a notebook query from a metric, model, or table."
[{:keys [_reasoning query visualization]} :- construct-notebook-query-args-schema]
diff --git a/src/metabase/metabot/tools/create_alert.clj b/src/metabase/metabot/tools/create_alert.clj
index e05af92a550..83ae144cea5 100644
--- a/src/metabase/metabot/tools/create_alert.clj
+++ b/src/metabase/metabot/tools/create_alert.clj
@@ -5,6 +5,7 @@
[clojure.set :as set]
[metabase.api.common :as api]
[metabase.channel.settings :as channel.settings]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.util :as metabot.tools.u]
[metabase.notification.api :as notification.api]
@@ -138,6 +139,7 @@ NEVER tell the user you have created an alert without actually calling the creat
[:send_once {:optional true :default false} :boolean]])
(mu/defn ^{:tool-name "create_alert"
+ :scope scope/agent-alert-create
:system-instructions create-alert-system-instructions}
create-alert-tool
"Create an alert based on a saved question's results on a recurring schedule."
diff --git a/src/metabase/metabot/tools/create_dashboard_subscription.clj b/src/metabase/metabot/tools/create_dashboard_subscription.clj
index 3633c3a9ce5..fabea535c63 100644
--- a/src/metabase/metabot/tools/create_dashboard_subscription.clj
+++ b/src/metabase/metabot/tools/create_dashboard_subscription.clj
@@ -3,6 +3,7 @@
[clojure.set :as set]
[metabase.api.common :as api]
[metabase.channel.settings :as channel.settings]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.create-alert :as tools.create-alert]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.util :as metabot.tools.u]
@@ -96,6 +97,7 @@ Before calling the tool, ensure you have ALL of the following:
If any required information is missing, ask the user for it rather than assuming or fabricating values.")
(mu/defn ^{:tool-name "create_dashboard_subscription"
+ :scope scope/agent-dashboard-subscribe
:system-instructions create-dashboard-subscription-system-instructions}
slackbot-create-dashboard-subscription-tool
"Create a recurring subscription that delivers a dashboard's contents to a Slack channel."
diff --git a/src/metabase/metabot/tools/document.clj b/src/metabase/metabot/tools/document.clj
index 1844b25072c..d20dea98d08 100644
--- a/src/metabase/metabot/tools/document.clj
+++ b/src/metabase/metabot/tools/document.clj
@@ -1,6 +1,7 @@
(ns metabase.metabot.tools.document
"Document-generation specific tool wrappers."
(:require
+ [metabase.metabot.scope :as scope]
[metabase.metabot.table-utils :as table-utils]
[metabase.metabot.tools.construct :as construct-tools]
[metabase.metabot.tools.shared :as shared]
@@ -82,7 +83,8 @@
(catch Exception e
(ex-message e))))
-(mu/defn ^{:tool-name "document_schema_collect"}
+(mu/defn ^{:tool-name "document_schema_collect"
+ :scope scope/agent-document-read}
document-schema-collect-tool
"Collects the schema of a database in order to construct a SQL query.
@@ -135,7 +137,8 @@
[:viz_settings [:map {:closed true}
[:chart_type chart-type-enum]]]])
-(mu/defn ^{:tool-name "document_construct_sql_chart"}
+(mu/defn ^{:tool-name "document_construct_sql_chart"
+ :scope scope/agent-document-create}
document-construct-sql-chart-tool
"Construct SQL-backed chart draft payload for document insertion."
[{:keys [database_id name description analysis approach sql viz_settings]} :- sql-chart-schema]
@@ -184,7 +187,8 @@
[:viz_settings [:map {:closed true}
[:chart_type chart-type-enum]]]])
-(mu/defn ^{:tool-name "document_construct_model_chart"}
+(mu/defn ^{:tool-name "document_construct_model_chart"
+ :scope scope/agent-document-create}
document-construct-model-chart-tool
"Construct notebook/model-backed chart draft payload for document insertion."
[{:keys [name description query viz_settings]} :- model-chart-schema]
diff --git a/src/metabase/metabot/tools/metadata.clj b/src/metabase/metabot/tools/metadata.clj
index 0e698627c00..20f7be64875 100644
--- a/src/metabase/metabot/tools/metadata.clj
+++ b/src/metabase/metabot/tools/metadata.clj
@@ -3,6 +3,7 @@
(:require
[clojure.string :as str]
[medley.core :as m]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.entity-details :as entity-details-tools]
[metabase.metabot.tools.field-stats :as field-stats-tools]
[metabase.metabot.tools.shared :as shared]
@@ -133,7 +134,8 @@
[result format-fn]
(m/assoc-some result :output (some-> result :structured-output format-fn)))
-(mu/defn ^{:tool-name "list_available_data_sources"}
+(mu/defn ^{:tool-name "list_available_data_sources"
+ :scope scope/agent-metadata-read}
list-available-data-sources-tool
"List all data sources (metrics and models) available to the metabot instance."
[_args :- [:map {:closed true}]]
@@ -150,7 +152,8 @@
[:model_ids [:sequential :int]]
[:metric_ids [:sequential :int]]])
-(mu/defn ^{:tool-name "list_available_fields"}
+(mu/defn ^{:tool-name "list_available_fields"
+ :scope scope/agent-metadata-read}
list-available-fields-tool
"Retrieve metadata for tables, models, and metrics."
[{:keys [table_ids model_ids metric_ids]} :- list-available-fields-schema]
@@ -166,7 +169,8 @@
[:source_id :int]
[:field_id :string]])
-(mu/defn ^{:tool-name "get_field_values"}
+(mu/defn ^{:tool-name "get_field_values"
+ :scope scope/agent-metadata-read}
get-field-values-tool
"Return metadata for a given field of a given data source."
[{:keys [data_source source_id field_id]} :- get-field-values-schema]
diff --git a/src/metabase/metabot/tools/navigation.clj b/src/metabase/metabot/tools/navigation.clj
index 2a2fe992479..b619426a6fd 100644
--- a/src/metabase/metabot/tools/navigation.clj
+++ b/src/metabase/metabot/tools/navigation.clj
@@ -3,6 +3,7 @@
(:require
[buddy.core.codecs :as codecs]
[metabase.metabot.agent.links :as links]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.shared :as shared]
[metabase.util.json :as json]
[metabase.util.log :as log]
@@ -146,6 +147,7 @@
[:chart_id :string]]]]])
(mu/defn ^{:tool-name "navigate_user"
+ :scope scope/agent-viz-navigate
:capabilities #{:frontend-navigate-user-v1}}
navigate-user-tool
"Navigate the user to a specific page or entity in Metabase.
diff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.clj
index 9580f63e972..a08a2696778 100644
--- a/src/metabase/metabot/tools/resources.clj
+++ b/src/metabase/metabot/tools/resources.clj
@@ -19,6 +19,7 @@
- metabase://dashboard/{id} - Dashboard details"
(:require
[clojure.string :as str]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.entity-details :as entity-details]
[metabase.metabot.tools.field-stats :as field-stats]
[metabase.metabot.tools.shared.instructions :as instructions]
@@ -277,7 +278,8 @@
{:resources resources
:output formatted}))
-(mu/defn ^{:tool-name "read_resource"}
+(mu/defn ^{:tool-name "read_resource"
+ :scope scope/agent-resource-read}
read-resource-tool
"Read detailed information about Metabase resources via URI patterns.
diff --git a/src/metabase/metabot/tools/search.clj b/src/metabase/metabot/tools/search.clj
index b675b71f38b..55084b45d17 100644
--- a/src/metabase/metabot/tools/search.clj
+++ b/src/metabase/metabot/tools/search.clj
@@ -6,6 +6,7 @@
[medley.core :as m]
[metabase.api.common :as api]
[metabase.metabot.config :as metabot.config]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tmpl :as te]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.shared.instructions :as instructions]
@@ -297,7 +298,8 @@
[:entity_types {:optional true}
[:maybe [:sequential [:enum "table" "model" "metric" "dashboard" "question"]]]]])
-(mu/defn ^{:tool-name "search"}
+(mu/defn ^{:tool-name "search"
+ :scope scope/agent-search}
search-tool
"Search for tables, models, metrics, dashboards, and saved questions."
[args :- search-schema]
@@ -312,7 +314,8 @@
[:maybe [:sequential [:enum "table" "model"]]]]])
(mu/defn ^{:tool-name "search"
- :prompt "sql_search.md"}
+ :prompt "sql_search.md"
+ :scope scope/agent-search}
sql-search-tool
"Search for SQL-queryable data sources (tables and models) within a database."
[{:keys [database_id] :as args} :- sql-search-schema]
@@ -326,7 +329,8 @@
[:maybe [:sequential [:enum "model" "metric" "table"]]]]])
(mu/defn ^{:tool-name "search"
- :prompt "nql_search.md"}
+ :prompt "nlq_search.md"
+ :scope scope/agent-search}
nlq-search-tool
"Search for NLQ-queryable data sources (models, metrics, tables)."
[args :- nlq-search-schema]
@@ -341,7 +345,8 @@
[:maybe [:sequential [:enum "table" "model" "transform"]]]]])
(mu/defn ^{:tool-name "search"
- :prompt "transform_search"}
+ :prompt "transform_search"
+ :scope scope/agent-search}
transform-search-tool
"Search for transforms, tables, and models."
[{:keys [search_native_query] :as args} :- transform-search-schema]
diff --git a/src/metabase/metabot/tools/shared/instructions.clj b/src/metabase/metabot/tools/shared/instructions.clj
index 099113e1ad6..6d767dcdf82 100644
--- a/src/metabase/metabot/tools/shared/instructions.clj
+++ b/src/metabase/metabot/tools/shared/instructions.clj
@@ -20,7 +20,7 @@ Examples: [Customer Metrics](metabase://metric/42), [Sales Dashboard](metabase:/
(def entity-metadata-instructions
"Instructions for LLM when processing entity metadata (tables, models, metrics)."
"The data above contains the metadata for the requested tables, models, and metrics.
-Metabot needs to:
+The assistant needs to:
- Use this metadata to understand the structure of the data
- Handle ambiguous field names by asking clarifying questions if necessary.
- Always check the actual field values before applying filters to avoid empty results.")
@@ -30,7 +30,7 @@ Metabot needs to:
"The field values above are sample data (like df.sample(n).describe() in pandas) - a
statistical snapshot of a subset of rows, not the complete dataset.
-Metabot needs to:
+The assistant needs to:
- Use these samples to understand FORMAT patterns: how values are structured (codes vs names,
capitalization, date formats, numeric encodings)
- Understand that samples show rough ranges but not all possible values - the full dataset may
@@ -66,7 +66,7 @@ Reference items using: [name](metabase://type/id)")
"Generate instructions for a newly created SQL query, embedding the query ID
in the link template. Matches Python CreateSQLQueryToolV2._create_result."
[query-id]
- (str "Metabot needs to:\n"
+ (str "The assistant needs to:\n"
"- Remember you cannot view the results directly yourself\n"
"- Always provide a direct link using `[Link text](metabase://query/" query-id ")` "
"so the user can open it themselves\n"
diff --git a/src/metabase/metabot/tools/slackbot_query.clj b/src/metabase/metabot/tools/slackbot_query.clj
index 0e6716c0845..317667cdb47 100644
--- a/src/metabase/metabot/tools/slackbot_query.clj
+++ b/src/metabase/metabot/tools/slackbot_query.clj
@@ -4,6 +4,7 @@
instead of creating charts. Does not save or navigate."
(:require
[metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.construct :as construct]
[metabase.util.log :as log]
[metabase.util.malli :as mu]))
@@ -19,7 +20,8 @@
:description "Visualization type for displaying the query results in Slack. Required in practice whenever the user asks for a chart or graph, and it must match any requested chart type. Valid values: 'table', 'bar', 'line', 'pie', 'area', 'row', 'scatter', 'funnel'. Use requested chart types like 'line', 'bar', 'area', 'pie', 'scatter', 'funnel', 'row', or 'table' when they fit the query. Omitting this field falls back to Metabase's default table display, so do not omit it for chart or graph requests. Only omit it when you intentionally want a plain table and the user did not request a chart type."}
[:maybe [:enum "table" "bar" "line" "pie" "area" "row" "scatter" "funnel"]]]])
-(mu/defn ^{:tool-name "construct_notebook_query"}
+(mu/defn ^{:tool-name "construct_notebook_query"
+ :scope scope/agent-notebook-create}
slackbot-construct-notebook-query-tool
"Construct a notebook query from a metric, model, or table. The query results will be rendered as a visualization in Slack."
[{:keys [_reasoning query title display]} :- slackbot-query-schema]
diff --git a/src/metabase/metabot/tools/snippets.clj b/src/metabase/metabot/tools/snippets.clj
index d1daf33f366..b071dd2dc57 100644
--- a/src/metabase/metabot/tools/snippets.clj
+++ b/src/metabase/metabot/tools/snippets.clj
@@ -1,6 +1,7 @@
(ns metabase.metabot.tools.snippets
(:require
[clojure.string :as str]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.util :as metabot.tools.u]
[metabase.native-query-snippets.core :as snippets]
[metabase.util.malli :as mu]))
@@ -55,6 +56,7 @@
result))
(mu/defn ^{:tool-name "list_snippets"
+ :scope scope/agent-snippets-read
:capabilities #{:feature-snippets}}
list-snippets-tool
"List all SQL snippets available in the Metabase instance.
@@ -66,6 +68,7 @@
(add-output (get-snippets {}) format-snippet-list-output))
(mu/defn ^{:tool-name "get_snippet_details"
+ :scope scope/agent-snippets-read
:capabilities #{:feature-snippets}}
get-snippet-details-tool
"Get the full details of a SQL snippet including its content.
diff --git a/src/metabase/metabot/tools/sql.clj b/src/metabase/metabot/tools/sql.clj
index 4f198fac2cf..2897644c812 100644
--- a/src/metabase/metabot/tools/sql.clj
+++ b/src/metabase/metabot/tools/sql.clj
@@ -2,6 +2,7 @@
"SQL tool wrappers."
(:require
[metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tmpl :as te]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.shared.instructions :as instructions]
@@ -79,6 +80,7 @@
[:sql_query :string]])
(mu/defn ^{:tool-name "create_sql_query"
+ :scope scope/agent-sql-create
:capabilities #{:permission-write-sql-queries}}
create-sql-query-tool
"Create a new SQL query."
@@ -108,6 +110,7 @@
{:output (str "Failed to create SQL query: " (or (ex-message e) "Unknown error"))}))))
(mu/defn ^{:tool-name "create_sql_query"
+ :scope scope/agent-sql-create
:capabilities #{:permission-write-sql-queries}}
create-sql-query-code-edit-tool
"Create a new SQL query and update the code editor buffer."
@@ -146,6 +149,7 @@
[:replace_all {:optional true} [:maybe :boolean]]]]]])
(mu/defn ^{:tool-name "edit_sql_query"
+ :scope scope/agent-sql-edit
:capabilities #{:permission-write-sql-queries}}
edit-sql-query-tool
"Edit an existing SQL query using structured edits."
@@ -177,6 +181,7 @@
{:output (str "Failed to edit SQL query: " (or (ex-message e) "Unknown error"))}))))
(mu/defn ^{:tool-name "edit_sql_query"
+ :scope scope/agent-sql-edit
:capabilities #{:permission-write-sql-queries}}
edit-sql-query-code-edit-tool
"Edit an existing SQL query and update the code editor buffer."
@@ -214,6 +219,7 @@
[:new_query :string]])
(mu/defn ^{:tool-name "replace_sql_query"
+ :scope scope/agent-sql-edit
:capabilities #{:permission-write-sql-queries}}
replace-sql-query-tool
"Replace the SQL content of an existing query entirely."
@@ -245,6 +251,7 @@
{:output (str "Failed to replace SQL query: " (or (ex-message e) "Unknown error"))}))))
(mu/defn ^{:tool-name "replace_sql_query"
+ :scope scope/agent-sql-edit
:capabilities #{:permission-write-sql-queries}}
replace-sql-query-code-edit-tool
"Replace an SQL query and update the code editor buffer."
diff --git a/src/metabase/metabot/tools/static_viz.clj b/src/metabase/metabot/tools/static_viz.clj
index 9d28d81f3bf..24bf498f1a1 100644
--- a/src/metabase/metabot/tools/static_viz.clj
+++ b/src/metabase/metabot/tools/static_viz.clj
@@ -3,11 +3,13 @@
Renders existing saved questions/metrics as PNG images in Slack."
(:require
[metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.scope :as scope]
[metabase.util.malli :as mu]))
(set! *warn-on-reflection* true)
-(mu/defn ^{:tool-name "static_viz"}
+(mu/defn ^{:tool-name "static_viz"
+ :scope scope/agent-viz-create}
static-viz-tool
"Generate a static visualization (PNG image) of a saved question or metric. The visualization will be posted as a separate follow-up message in the thread."
[{:keys [entity_id]} :- [:map {:closed true}
diff --git a/src/metabase/metabot/tools/subscriptions.clj b/src/metabase/metabot/tools/subscriptions.clj
index a039ef68955..bbcc8ec96cf 100644
--- a/src/metabase/metabot/tools/subscriptions.clj
+++ b/src/metabase/metabot/tools/subscriptions.clj
@@ -4,6 +4,7 @@
[clojure.set :as set]
[metabase.api.common :as api]
[metabase.channel.settings :as channel.settings]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.create-alert :as tools.create-alert]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.util :as metabot.tools.u]
@@ -99,6 +100,7 @@ Before calling the tool, ensure you have ALL of the following:
If any required information is missing, ask the user for it rather than assuming or fabricating values.")
(mu/defn ^{:tool-name "create_dashboard_subscription"
+ :scope scope/agent-dashboard-subscribe
:system-instructions create-dashboard-subscription-system-instructions}
slackbot-create-dashboard-subscription-tool
"Create a recurring subscription that delivers a dashboard's contents to a Slack channel."
@@ -132,7 +134,8 @@ If any required information is missing, ask the user for it rather than assuming
[:day_of_week {:optional true} [:maybe :string]]
[:day_of_month {:optional true} [:maybe :string]]]]])
-(mu/defn ^{:tool-name "create_dashboard_subscription"}
+(mu/defn ^{:tool-name "create_dashboard_subscription"
+ :scope scope/agent-dashboard-subscribe}
create-dashboard-subscription-tool
"Create a dashboard subscription to send regular updates via email or Slack.
diff --git a/src/metabase/metabot/tools/todo.clj b/src/metabase/metabot/tools/todo.clj
index c27e1091a56..28345f3a5a6 100644
--- a/src/metabase/metabot/tools/todo.clj
+++ b/src/metabase/metabot/tools/todo.clj
@@ -4,6 +4,7 @@
(:require
[clojure.string :as str]
[metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.shared :as shared]
[metabase.util.log :as log]
[metabase.util.malli :as mu]))
@@ -108,7 +109,8 @@
[:status [:enum "pending" "in_progress" "completed" "cancelled"]]
[:priority [:enum "high" "medium" "low"]]]]]])
-(mu/defn ^{:tool-name "todo_write"}
+(mu/defn ^{:tool-name "todo_write"
+ :scope scope/agent-todo-write}
todo-write-tool
"Create and manage a structured task list.
Write or update the todo list with tasks for tracking progress.
@@ -129,7 +131,8 @@
{:output (ex-message e)}
{:output (str "Failed to update todo list: " (or (ex-message e) "Unknown error"))}))))
-(mu/defn ^{:tool-name "todo_read"}
+(mu/defn ^{:tool-name "todo_read"
+ :scope scope/agent-todo-read}
todo-read-tool
"Read the current todo list from memory.
Returns the list of todos that have been created during this conversation."
diff --git a/src/metabase/metabot/tools/transforms.clj b/src/metabase/metabot/tools/transforms.clj
index b8e7d7472a6..5ca34b6af93 100644
--- a/src/metabase/metabot/tools/transforms.clj
+++ b/src/metabase/metabot/tools/transforms.clj
@@ -3,6 +3,7 @@
SQL transform tools are implemented directly in OSS.
Python transform tools use defenterprise (return nil/error in OSS, real impl in EE)."
(:require
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.dependencies :as deps]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.transforms.write :as transforms-write-tools]
@@ -79,7 +80,8 @@
;;; Tool definitions
;;; ──────────────────────────────────────────────────────────────────
-(mu/defn ^{:tool-name "get_transform_details"}
+(mu/defn ^{:tool-name "get_transform_details"
+ :scope scope/agent-transforms-read}
get-transform-details-tool
"Get information about a transform."
[{:keys [transform_id]} :- [:map {:closed true} [:transform_id :int]]]
@@ -94,6 +96,7 @@
(defenterprise ^{:tool-name "get_transform_python_library_details"
:schema [:=> [:cat python-lib-schema] :map]
+ :scope scope/agent-transforms-read
:ee-feature :transforms}
get-transform-python-library-details-tool
"Get Python library details. EE-only; returns an error in OSS."
@@ -147,6 +150,7 @@
[:maybe :string]]])
(mu/defn ^{:tool-name "write_transform_sql"
+ :scope scope/agent-transforms-write
:capabilities #{:feature-transforms :permission-write-transforms}}
write-transform-sql-tool
"Write new SQL queries or edit existing queries for transforms.
@@ -252,6 +256,7 @@
(defenterprise ^{:tool-name "write_transform_python"
:schema [:=> [:cat write-transform-python-schema] :map]
+ :scope scope/agent-transforms-write
:capabilities #{:feature-transforms :feature-transforms-python :permission-write-transforms}
:ee-feature :transforms}
write-transform-python-tool
diff --git a/src/metabase/models/resolution.clj b/src/metabase/models/resolution.clj
index 9cb8ac433c6..154d141474b 100644
--- a/src/metabase/models/resolution.clj
+++ b/src/metabase/models/resolution.clj
@@ -57,6 +57,7 @@
:model/Metabot metabase.metabot.models.metabot
:model/MetabotConversation metabase.metabot.models.metabot-conversation
:model/MetabotMessage metabase.metabot.models.metabot-message
+ :model/MetabotPermissions metabase-enterprise.metabot.models.metabot-permissions
:model/MetabotPrompt metabase.metabot.models.metabot-prompt
:model/ModelIndex metabase.indexed-entities.models.model-index
:model/ModelIndexValue metabase.indexed-entities.models.model-index
diff --git a/src/metabase/premium_features/core.clj b/src/metabase/premium_features/core.clj
index 2345afd5e23..6f8e13850c8 100644
--- a/src/metabase/premium_features/core.clj
+++ b/src/metabase/premium_features/core.clj
@@ -41,6 +41,7 @@
define-premium-feature
development-mode?
enable-tenants?
+ enable-ai-controls?
enable-advanced-permissions?
enable-any-sso?
enable-audit-app?
diff --git a/src/metabase/premium_features/settings.clj b/src/metabase/premium_features/settings.clj
index e3c8478018e..1034c1f23ab 100644
--- a/src/metabase/premium_features/settings.clj
+++ b/src/metabase/premium_features/settings.clj
@@ -304,6 +304,10 @@
"Should we allow admins to configure separate write connection credentials?"
:writable-connection)
+(define-premium-feature ^{:added "0.61.0"} enable-ai-controls?
+ "Should we enable AI controls (metabot permissions, scope management)?"
+ :ai-controls)
+
(defn- -token-features []
{:advanced_permissions (enable-advanced-permissions?)
:attached_dwh (has-attached-dwh?)
@@ -352,7 +356,8 @@
:upload_management (enable-upload-management?)
:whitelabel (enable-whitelabeling?)
:workspaces (enable-workspaces?)
- :writable_connection (enable-writable-connection?)})
+ :writable_connection (enable-writable-connection?)
+ :ai_controls (enable-ai-controls?)})
(defsetting token-features
"Features registered for this instance's token"
diff --git a/src/metabase/slackbot/config.clj b/src/metabase/slackbot/config.clj
index 01a3489bfb1..9faae814d53 100644
--- a/src/metabase/slackbot/config.clj
+++ b/src/metabase/slackbot/config.clj
@@ -2,6 +2,7 @@
"Configuration, manifest, and validation helpers for slackbot."
(:require
[metabase.channel.settings :as channel.settings]
+ [metabase.metabot.settings :as metabot.settings]
[metabase.slackbot.client :as slackbot.client]
[metabase.slackbot.settings :as slackbot.settings]
[metabase.sso.settings :as sso-settings]
@@ -13,52 +14,53 @@
(defn build-slack-manifest
"Build the full Metabot Slack app manifest for the given base URL."
[base-url]
- {:display_information {:name "Metabot"
- :description "Your AI-powered data assistant"
- :background_color "#509EE3"}
- :features {:app_home {:home_tab_enabled false
- :messages_tab_enabled true
- :messages_tab_read_only_enabled false}
- :bot_user {:display_name "Metabot"
- :always_online false}
- :assistant_view {:assistant_description "Your AI-powered data assistant"}
- :slash_commands [{:command "/metabot"
- :url (str base-url "/api/metabot/slack/commands")
- :description "Issue a Metabot command"
- :should_escape false}]}
- :oauth_config {:redirect_urls [(str base-url "/auth/sso/slack-connect/callback")]
- :scopes {:bot ["app_mentions:read"
- "assistant:write"
- "channels:history"
- "chat:write"
- "chat:write.customize"
- "chat:write.public"
- "channels:join"
- "channels:read"
- "commands"
- "groups:read"
- "groups:history"
- "im:history"
- "im:read"
- "files:read"
- "files:write"
- "mpim:read"
- "reactions:read"
- "reactions:write"
- "users:read"]}}
- :settings {:event_subscriptions {:request_url (str base-url "/api/metabot/slack/events")
- :bot_events ["app_home_opened"
- "app_mention"
- "message.channels"
- "message.im"
- "reaction_added"
- "assistant_thread_started"
- "assistant_thread_context_changed"]}
- :interactivity {:is_enabled true
- :request_url (str base-url "/api/metabot/slack/interactive")}
- :org_deploy_enabled true
- :socket_mode_enabled false
- :token_rotation_enabled false}})
+ (let [bot-name (metabot.settings/metabot-name)]
+ {:display_information {:name bot-name
+ :description "Your AI-powered data assistant"
+ :background_color "#509EE3"}
+ :features {:app_home {:home_tab_enabled false
+ :messages_tab_enabled true
+ :messages_tab_read_only_enabled false}
+ :bot_user {:display_name bot-name
+ :always_online false}
+ :assistant_view {:assistant_description "Your AI-powered data assistant"}
+ :slash_commands [{:command "/metabot"
+ :url (str base-url "/api/metabot/slack/commands")
+ :description (str "Issue a " bot-name " command")
+ :should_escape false}]}
+ :oauth_config {:redirect_urls [(str base-url "/auth/sso/slack-connect/callback")]
+ :scopes {:bot ["app_mentions:read"
+ "assistant:write"
+ "channels:history"
+ "chat:write"
+ "chat:write.customize"
+ "chat:write.public"
+ "channels:join"
+ "channels:read"
+ "commands"
+ "groups:read"
+ "groups:history"
+ "im:history"
+ "im:read"
+ "files:read"
+ "files:write"
+ "mpim:read"
+ "reactions:read"
+ "reactions:write"
+ "users:read"]}}
+ :settings {:event_subscriptions {:request_url (str base-url "/api/metabot/slack/events")
+ :bot_events ["app_home_opened"
+ "app_mention"
+ "message.channels"
+ "message.im"
+ "reaction_added"
+ "assistant_thread_started"
+ "assistant_thread_context_changed"]}
+ :interactivity {:is_enabled true
+ :request_url (str base-url "/api/metabot/slack/interactive")}
+ :org_deploy_enabled true
+ :socket_mode_enabled false
+ :token_rotation_enabled false}}))
(defn setup-complete?
"Returns true if all required Slack settings are configured to process events."
diff --git a/test/metabase/cmd/compare_h2_dbs_test_util.clj b/test/metabase/cmd/compare_h2_dbs_test_util.clj
index ae89ee02c4f..d8589644aba 100644
--- a/test/metabase/cmd/compare_h2_dbs_test_util.clj
+++ b/test/metabase/cmd/compare_h2_dbs_test_util.clj
@@ -38,7 +38,9 @@
"QUERY"
"QUERY_QUERYEXECUTION"
"QUERY_CACHE"
- "TASK_HISTORY"})
+ "TASK_HISTORY"
+ ;; EE-only table populated by migration but only dumped when EE is available
+ "METABOT_PERMISSIONS"})
(defn- table-names
"Return a sorted collection of all non-system table names."
diff --git a/test/metabase/cmd/copy_test.clj b/test/metabase/cmd/copy_test.clj
index 8d00c0473c4..e79bb430886 100644
--- a/test/metabase/cmd/copy_test.clj
+++ b/test/metabase/cmd/copy_test.clj
@@ -35,6 +35,8 @@
:model/DashboardFavorite
:model/DatabaseRouter
:model/Dependency
+ :model/MetabotGroupLimit
+ :model/MetabotInstanceLimit
:model/PythonLibrary
:model/PremiumFeaturesCache
:model/Query
diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.clj
index 346e07d97dd..b1183bb3cce 100644
--- a/test/metabase/mcp/api_test.clj
+++ b/test/metabase/mcp/api_test.clj
@@ -481,9 +481,8 @@
(let [result (mt/with-current-user (mt/user->id :crowberto)
(mcp.tools/call-tool #{"agent:search"} "get_table" {:id (mt/id :orders)}))]
(is (=? {:isError true} result))
- (is (= "Insufficient scope to call tool: get_table"
- (-> result :content first :text))
- "Error must not leak the required scope name")))
+ (is (str/includes? (-> result :content first :text) "Insufficient scope")
+ "Scope enforcement error from defendpoint middleware")))
(testing "tool call with matching scope is not rejected by scope enforcement"
(let [result (mt/with-current-user (mt/user->id :crowberto)
(mcp.tools/call-tool #{"agent:table:read"} "get_table" {:id (mt/id :orders)}))]
@@ -492,9 +491,8 @@
(let [result (mt/with-current-user (mt/user->id :crowberto)
(mcp.tools/call-tool #{} "get_table" {:id (mt/id :orders)}))]
(is (=? {:isError true} result))
- (is (= "Insufficient scope to call tool: get_table"
- (-> result :content first :text))
- "Error must not leak the required scope name"))))
+ (is (str/includes? (-> result :content first :text) "Insufficient scope")
+ "Scope enforcement error from defendpoint middleware"))))
(deftest agent-api-preserves-token-scopes-test
(testing "scoped token restrictions are enforced by the Agent API layer (defense-in-depth)"
diff --git a/test/metabase/metabot/agent/core_test.clj b/test/metabase/metabot/agent/core_test.clj
index cc03d387d9e..91421da078d 100644
--- a/test/metabase/metabot/agent/core_test.clj
+++ b/test/metabase/metabot/agent/core_test.clj
@@ -34,9 +34,11 @@
:fn test-search-tool}})
(defn- run-agent-loop!
- "run-agent-loop for side effects, discarding results"
+ "run-agent-loop for side effects, discarding results.
+ Runs as admin so the base metabot permission check passes."
[opts]
- (reduce (fn [_ _]) nil (agent/run-agent-loop opts)))
+ (mt/as-admin
+ (reduce (fn [_ _]) nil (agent/run-agent-loop opts))))
(deftest has-tool-calls-test
(testing "detects tool calls in parts"
@@ -67,71 +69,72 @@
(is (not (#'agent/should-continue? 0 max-iter []))))))
(deftest run-agent-loop-with-mock-test
- (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
- (testing "runs agent loop with mocked LLM returning text"
- (with-redefs [openrouter/openrouter (fn [_]
- (mut/mock-llm-response
- [{:type :text :text "Hello"}]))]
- (let [result (into [] (agent/run-agent-loop
- {:messages [{:role :user :content "Hi"}]
- :state {}
- :profile-id :embedding_next
- :context {}}))]
- ;; Should get parts + state data
- ;; Note: :finish is not emitted as a part; it's handled by aisdk-line-xf completion
- (is (pos? (count result)))
- ;; Should have state data (final part)
- (is (some #(= :data (:type %)) result)))))
-
- (testing "sql profile requests required tool choice"
- (let [captured (atom nil)]
- (with-redefs [self/call-llm (fn [_model _system _parts _tools _tracking-opts llm-opts]
- (reset! captured llm-opts)
- (mut/mock-llm-response
- [{:type :text :text "Hello"}]))]
- (into [] (agent/run-agent-loop
- {:messages [{:role :user :content "Hi"}]
- :state {}
- :profile-id :sql
- :context {}}))
- (is (= {:tool-choice "required"} @captured)))))
-
- (testing "runs agent loop with tool execution"
- (let [call-count (atom 0)]
+ (mt/as-admin
+ (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
+ (testing "runs agent loop with mocked LLM returning text"
(with-redefs [openrouter/openrouter (fn [_]
- ;; First call returns tool-input, second returns text
- (let [n (swap! call-count inc)]
- (if (= 1 n)
- (mut/mock-llm-response
- [{:type :tool-input
- :id "t1"
- :function "search"
- :arguments {:query "test"}}])
- (mut/mock-llm-response
- [{:type :text :text "Found results"}]))))]
+ (mut/mock-llm-response
+ [{:type :text :text "Hello"}]))]
(let [result (into [] (agent/run-agent-loop
- {:messages [{:role :user :content "Search for test"}]
+ {:messages [{:role :user :content "Hi"}]
:state {}
:profile-id :embedding_next
:context {}}))]
- ;; Should complete successfully
+ ;; Should get parts + state data
+ ;; Note: :finish is not emitted as a part; it's handled by aisdk-line-xf completion
(is (pos? (count result)))
- ;; Should have state data (final part)
- (is (some #(= :data (:type %)) result))
- ;; Should have tool-related parts
- (is (some #(= :tool-input (:type %)) result))))))
-
- (testing "handles errors gracefully"
- (with-redefs [openrouter/openrouter (fn [_]
- (throw (ex-info "Mock error" {})))]
- (let [result (mt/with-log-level [metabase.metabot.agent.core :fatal]
- (into [] (agent/run-agent-loop
- {:messages [{:role :user :content "Hi"}]
- :state {}
- :profile-id :embedding_next
- :context {}})))]
- ;; Should get error message
- (is (some #(= :error (:type %)) result)))))))
+ ;; Should have state data (final part)
+ (is (some #(= :data (:type %)) result)))))
+
+ (testing "sql profile requests required tool choice"
+ (let [captured (atom nil)]
+ (with-redefs [self/call-llm (fn [_model _system _parts _tools _tracking-opts llm-opts]
+ (reset! captured llm-opts)
+ (mut/mock-llm-response
+ [{:type :text :text "Hello"}]))]
+ (into [] (agent/run-agent-loop
+ {:messages [{:role :user :content "Hi"}]
+ :state {}
+ :profile-id :sql
+ :context {}}))
+ (is (= {:tool-choice "required"} @captured)))))
+
+ (testing "runs agent loop with tool execution"
+ (let [call-count (atom 0)]
+ (with-redefs [openrouter/openrouter (fn [_]
+ ;; First call returns tool-input, second returns text
+ (let [n (swap! call-count inc)]
+ (if (= 1 n)
+ (mut/mock-llm-response
+ [{:type :tool-input
+ :id "t1"
+ :function "search"
+ :arguments {:query "test"}}])
+ (mut/mock-llm-response
+ [{:type :text :text "Found results"}]))))]
+ (let [result (into [] (agent/run-agent-loop
+ {:messages [{:role :user :content "Search for test"}]
+ :state {}
+ :profile-id :embedding_next
+ :context {}}))]
+ ;; Should complete successfully
+ (is (pos? (count result)))
+ ;; Should have state data (final part)
+ (is (some #(= :data (:type %)) result))
+ ;; Should have tool-related parts
+ (is (some #(= :tool-input (:type %)) result))))))
+
+ (testing "handles errors gracefully"
+ (with-redefs [openrouter/openrouter (fn [_]
+ (throw (ex-info "Mock error" {})))]
+ (let [result (mt/with-log-level [metabase.metabot.agent.core :fatal]
+ (into [] (agent/run-agent-loop
+ {:messages [{:role :user :content "Hi"}]
+ :state {}
+ :profile-id :embedding_next
+ :context {}})))]
+ ;; Should get error message
+ (is (some #(= :error (:type %)) result))))))))
;; Note: build-messages-for-llm is now internal to call-llm
;; Message building is tested via messages_test.clj
@@ -162,24 +165,25 @@
;; Here we test the full agent loop behavior.
(deftest integration-run-agent-loop-test
- (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
- (testing "runs full agent loop without external calls"
- (with-redefs [openrouter/openrouter (fn [_]
- (mut/mock-llm-response
- [{:type :text :text "Test response"}]))]
- (let [result (into [] (agent/run-agent-loop
- {:messages [{:role :user :content "Hello"}]
- :state {}
- :profile-id :embedding_next
- :context {}}))]
- ;; Verify basic structure
- (is (pos? (count result)))
- ;; Should have text part
- (is (some #(= :text (:type %)) result))
- ;; Should have state data part (finish is handled by aisdk-line-xf, not emitted as part)
- (is (some #(and (= :data (:type %))
- (map? (:data %)))
- result)))))))
+ (mt/as-admin
+ (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
+ (testing "runs full agent loop without external calls"
+ (with-redefs [openrouter/openrouter (fn [_]
+ (mut/mock-llm-response
+ [{:type :text :text "Test response"}]))]
+ (let [result (into [] (agent/run-agent-loop
+ {:messages [{:role :user :content "Hello"}]
+ :state {}
+ :profile-id :embedding_next
+ :context {}}))]
+ ;; Verify basic structure
+ (is (pos? (count result)))
+ ;; Should have text part
+ (is (some #(= :text (:type %)) result))
+ ;; Should have state data part (finish is handled by aisdk-line-xf, not emitted as part)
+ (is (some #(and (= :data (:type %))
+ (map? (:data %)))
+ result))))))))
;;; Query and Chart extraction tests
@@ -273,8 +277,9 @@
(mut/mock-llm-response [{:type :text :text ""}]))))))
(deftest integration-search-query-chart-flow-test
- (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
- (testing "Scenario 1: Search → Query → Chart (multi-turn happy path)"
+ (mt/as-admin
+ (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
+ (testing "Scenario 1: Search → Query → Chart (multi-turn happy path)"
;; User asks: "Show me the first 10 orders"
;; - Iteration 1: LLM calls search tool to find orders table
;; - Iteration 2: LLM calls construct_notebook_query to create a raw query
@@ -283,186 +288,188 @@
;; We use real tools with only the search backend and LLM mocked.
;; The construct_notebook_query tool runs real query construction against test DB.
;; We use a simple "raw" query type that doesn't require field IDs.
- (mt/with-current-user (mt/user->id :crowberto)
- (let [orders-table-id (mt/id :orders)
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [orders-table-id (mt/id :orders)
;; Track LLM calls
- llm-call-count (atom 0)
+ llm-call-count (atom 0)
;; Scripted LLM responses - uses real table ID from test DB
- llm-responses
- [;; Iteration 1: Search for orders table
- [{:type :start :id "msg-1"}
- {:type :tool-input
- :id "call-search-1"
- :function "search"
- :arguments {:semantic_queries ["orders table"]
- :keyword_queries ["orders"]
- :entity_types ["table"]}}
- {:type :usage :usage {:promptTokens 100 :completionTokens 20} :model "test" :id "msg-1"}]
+ llm-responses
+ [;; Iteration 1: Search for orders table
+ [{:type :start :id "msg-1"}
+ {:type :tool-input
+ :id "call-search-1"
+ :function "search"
+ :arguments {:semantic_queries ["orders table"]
+ :keyword_queries ["orders"]
+ :entity_types ["table"]}}
+ {:type :usage :usage {:promptTokens 100 :completionTokens 20} :model "test" :id "msg-1"}]
;; Iteration 2: Construct a simple raw query (no fields/aggregations = select all)
- [{:type :start :id "msg-2"}
- {:type :tool-input
- :id "call-construct-1"
- :function "construct_notebook_query"
- :arguments {:reasoning "User wants to see orders"
- :query {:query_type "raw"
- :source {:table_id orders-table-id}
- :filters []
- :fields []
- :order_by []
- :limit 10}
- :visualization {:chart_type "table"}}}
- {:type :usage :usage {:promptTokens 200 :completionTokens 30} :model "test" :id "msg-2"}]
+ [{:type :start :id "msg-2"}
+ {:type :tool-input
+ :id "call-construct-1"
+ :function "construct_notebook_query"
+ :arguments {:reasoning "User wants to see orders"
+ :query {:query_type "raw"
+ :source {:table_id orders-table-id}
+ :filters []
+ :fields []
+ :order_by []
+ :limit 10}
+ :visualization {:chart_type "table"}}}
+ {:type :usage :usage {:promptTokens 200 :completionTokens 30} :model "test" :id "msg-2"}]
;; Iteration 3: Final text response
- [{:type :start :id "msg-3"}
- {:type :text
- :text "Here are the first 10 orders from the orders table."}
- {:type :usage :usage {:promptTokens 300 :completionTokens 10} :model "test" :id "msg-3"}]]]
+ [{:type :start :id "msg-3"}
+ {:type :text
+ :text "Here are the first 10 orders from the orders table."}
+ {:type :usage :usage {:promptTokens 300 :completionTokens 10} :model "test" :id "msg-3"}]]]
;; Mock only openrouter/openrouter (LLM) and metabot-search/search (search backend)
;; Everything else runs real code
- (with-redefs [openrouter/openrouter (fn [_opts]
- (let [n (swap! llm-call-count inc)]
- (mut/mock-llm-response (get llm-responses (dec n) []))))
- metabot-search/search (fn [_args]
- [{:id orders-table-id
- :type "table"
- :name "orders"
- :display_name "Orders"
- :description "This is a confirmed order for a product from a user."
- :database_id (mt/id)}])]
- (testing "Should successfully go through 3 iterations"
- (is (=? [{:type :start}
- {:type :tool-input :function "search"}
+ (with-redefs [openrouter/openrouter (fn [_opts]
+ (let [n (swap! llm-call-count inc)]
+ (mut/mock-llm-response (get llm-responses (dec n) []))))
+ metabot-search/search (fn [_args]
+ [{:id orders-table-id
+ :type "table"
+ :name "orders"
+ :display_name "Orders"
+ :description "This is a confirmed order for a product from a user."
+ :database_id (mt/id)}])]
+ (testing "Should successfully go through 3 iterations"
+ (is (=? [{:type :start}
+ {:type :tool-input :function "search"}
;; Cumulative usage after iteration 1: 100 prompt, 20 completion
- {:type :usage :usage {:promptTokens 100 :completionTokens 20}}
- {:type :tool-output
- :function "search"
- :result {:structured-output {:total_count 1}}}
- {:type :start}
- {:type :tool-input :function "construct_notebook_query"}
+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}}
+ {:type :tool-output
+ :function "search"
+ :result {:structured-output {:total_count 1}}}
+ {:type :start}
+ {:type :tool-input :function "construct_notebook_query"}
;; Cumulative usage after iteration 2: 100+200=300 prompt, 20+30=50 completion
- {:type :usage :usage {:promptTokens 300 :completionTokens 50}}
+ {:type :usage :usage {:promptTokens 300 :completionTokens 50}}
;; references real db id
- {:type :tool-output
- :function "construct_notebook_query"
- :result {:structured-output {:query {:database (mt/id)}}}}
- {:type :data :data-type "navigate_to"}
- {:type :start}
+ {:type :tool-output
+ :function "construct_notebook_query"
+ :result {:structured-output {:query {:database (mt/id)}}}}
+ {:type :data :data-type "navigate_to"}
+ {:type :start}
;; has final text part
- {:type :text}
+ {:type :text}
;; Cumulative usage after iteration 3: 300+300=600 prompt, 50+10=60 completion
- {:type :usage :usage {:promptTokens 600 :completionTokens 60}}
- {:type :data
- :data-type "state"
- :data {:queries map?
- :charts map?}}]
- (mt/with-log-level [metabase.metabot.agent.core :warn]
- (into [] (#'api/combine-text-parts-xf)
- (agent/run-agent-loop
- {:messages [{:role :user
- :content "Show me the first 10 orders"}]
- :state {}
- :profile-id :internal
- :context {}}))))))
- (testing "should complete 3 LLM iterations"
- (is (= 3 @llm-call-count)
- "Should have exactly 3 LLM calls (search, construct, final text)"))))))))
+ {:type :usage :usage {:promptTokens 600 :completionTokens 60}}
+ {:type :data
+ :data-type "state"
+ :data {:queries map?
+ :charts map?}}]
+ (mt/with-log-level [metabase.metabot.agent.core :warn]
+ (into [] (#'api/combine-text-parts-xf)
+ (agent/run-agent-loop
+ {:messages [{:role :user
+ :content "Show me the first 10 orders"}]
+ :state {}
+ :profile-id :internal
+ :context {}}))))))
+ (testing "should complete 3 LLM iterations"
+ (is (= 3 @llm-call-count)
+ "Should have exactly 3 LLM calls (search, construct, final text)")))))))))
(deftest cumulative-usage-test
- (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
- (testing "usage parts are cumulative across agent loop iterations"
- (let [call-count (atom 0)]
- (with-redefs [openrouter/openrouter
- (fn [_]
- (let [n (swap! call-count inc)]
- (case (int n)
+ (mt/as-admin
+ (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
+ (testing "usage parts are cumulative across agent loop iterations"
+ (let [call-count (atom 0)]
+ (with-redefs [openrouter/openrouter
+ (fn [_]
+ (let [n (swap! call-count inc)]
+ (case (int n)
;; Iteration 1: tool call with usage
- 1 (mut/mock-llm-response
- [{:type :start :id "msg-1"}
- {:type :tool-input
- :id "t1"
- :function "search"
- :arguments {:query "test"}}
- {:type :usage :usage {:promptTokens 100 :completionTokens 20}
- :model "gpt-4" :id "msg-1"}])
+ 1 (mut/mock-llm-response
+ [{:type :start :id "msg-1"}
+ {:type :tool-input
+ :id "t1"
+ :function "search"
+ :arguments {:query "test"}}
+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}
+ :model "gpt-4" :id "msg-1"}])
;; Iteration 2: text response with usage
- (mut/mock-llm-response
- [{:type :start :id "msg-2"}
- {:type :text :text "Done"}
- {:type :usage :usage {:promptTokens 150 :completionTokens 30}
- :model "gpt-4" :id "msg-2"}]))))]
- (let [result (mt/with-log-level [metabase.metabot.agent.core :warn]
- (into [] (agent/run-agent-loop
- {:messages [{:role :user :content "test"}]
- :state {}
- :profile-id :embedding_next
- :context {}})))
- usages (filterv #(= :usage (:type %)) result)]
- (testing "should have two usage parts (one per iteration)"
- (is (= 2 (count usages))))
- (testing "first usage is from iteration 1 only"
- (is (= {:promptTokens 100 :completionTokens 20}
- (:usage (first usages)))))
- (testing "second usage is cumulative (iteration 1 + 2)"
- (is (= {:promptTokens 250 :completionTokens 50}
- (:usage (second usages)))))))))
-
- (testing "cumulative usage works across multiple models"
- (let [call-count (atom 0)]
- (with-redefs [openrouter/openrouter
- (fn [_]
- (let [n (swap! call-count inc)]
- (case (int n)
- 1 (mut/mock-llm-response
- [{:type :start :id "msg-1"}
- {:type :tool-input
- :id "t1"
- :function "search"
- :arguments {:query "test"}}
- {:type :usage :usage {:promptTokens 100 :completionTokens 20}
- :model "model-a" :id "msg-1"}])
- (mut/mock-llm-response
- [{:type :start :id "msg-2"}
- {:type :text :text "Done"}
- {:type :usage :usage {:promptTokens 200 :completionTokens 40}
- :model "model-b" :id "msg-2"}]))))]
- (let [result (mt/with-log-level [metabase.metabot.agent.core :warn]
- (into [] (agent/run-agent-loop
- {:messages [{:role :user :content "test"}]
- :state {}
- :profile-id :embedding_next
- :context {}})))
- usages (filterv #(= :usage (:type %)) result)]
- (testing "different models accumulate independently"
- (is (= "model-a" (:model (first usages))))
- (is (= {:promptTokens 100 :completionTokens 20}
- (:usage (first usages))))
- (is (= "model-b" (:model (second usages))))
- (is (= {:promptTokens 200 :completionTokens 40}
- (:usage (second usages)))))))))))
+ (mut/mock-llm-response
+ [{:type :start :id "msg-2"}
+ {:type :text :text "Done"}
+ {:type :usage :usage {:promptTokens 150 :completionTokens 30}
+ :model "gpt-4" :id "msg-2"}]))))]
+ (let [result (mt/with-log-level [metabase.metabot.agent.core :warn]
+ (into [] (agent/run-agent-loop
+ {:messages [{:role :user :content "test"}]
+ :state {}
+ :profile-id :embedding_next
+ :context {}})))
+ usages (filterv #(= :usage (:type %)) result)]
+ (testing "should have two usage parts (one per iteration)"
+ (is (= 2 (count usages))))
+ (testing "first usage is from iteration 1 only"
+ (is (= {:promptTokens 100 :completionTokens 20}
+ (:usage (first usages)))))
+ (testing "second usage is cumulative (iteration 1 + 2)"
+ (is (= {:promptTokens 250 :completionTokens 50}
+ (:usage (second usages)))))))))
+
+ (testing "cumulative usage works across multiple models"
+ (let [call-count (atom 0)]
+ (with-redefs [openrouter/openrouter
+ (fn [_]
+ (let [n (swap! call-count inc)]
+ (case (int n)
+ 1 (mut/mock-llm-response
+ [{:type :start :id "msg-1"}
+ {:type :tool-input
+ :id "t1"
+ :function "search"
+ :arguments {:query "test"}}
+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}
+ :model "model-a" :id "msg-1"}])
+ (mut/mock-llm-response
+ [{:type :start :id "msg-2"}
+ {:type :text :text "Done"}
+ {:type :usage :usage {:promptTokens 200 :completionTokens 40}
+ :model "model-b" :id "msg-2"}]))))]
+ (let [result (mt/with-log-level [metabase.metabot.agent.core :warn]
+ (into [] (agent/run-agent-loop
+ {:messages [{:role :user :content "test"}]
+ :state {}
+ :profile-id :embedding_next
+ :context {}})))
+ usages (filterv #(= :usage (:type %)) result)]
+ (testing "different models accumulate independently"
+ (is (= "model-a" (:model (first usages))))
+ (is (= {:promptTokens 100 :completionTokens 20}
+ (:usage (first usages))))
+ (is (= "model-b" (:model (second usages))))
+ (is (= {:promptTokens 200 :completionTokens 40}
+ (:usage (second usages))))))))))))
(deftest run-agent-loop-retries-on-rate-limit-test
- (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
- (testing "agent loop retries when LLM returns 429 and then succeeds"
- (let [call-count (atom 0)]
- (with-redefs [self/retry-delay-ms (constantly 0)
- openrouter/openrouter (fn [_]
- (if (< (swap! call-count inc) 2)
- (throw (ex-info "Anthropic API has rate limited us"
- {:status 429 :api-error true}))
- (mut/mock-llm-response
- [{:type :text :text "Hello after retry"}])))]
- (is (=? [{:type :text :text "Hello after retry"}
- {:type :data :data-type "state"}]
- (mt/with-log-level [metabase.metabot.self :fatal]
- (into [] (#'api/combine-text-parts-xf)
- (agent/run-agent-loop
- {:messages [{:role :user :content "Hi"}]
- :state {}
- :profile-id :embedding_next
- :context {}}))))
- "Should get the response from the successful retry")
- (is (= 2 @call-count)
- "Should have called LLM twice (1 failure + 1 success"))))))
+ (mt/as-admin
+ (mt/with-temporary-setting-values [llm-metabot-provider test-provider]
+ (testing "agent loop retries when LLM returns 429 and then succeeds"
+ (let [call-count (atom 0)]
+ (with-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (fn [_]
+ (if (< (swap! call-count inc) 2)
+ (throw (ex-info "Anthropic API has rate limited us"
+ {:status 429 :api-error true}))
+ (mut/mock-llm-response
+ [{:type :text :text "Hello after retry"}])))]
+ (is (=? [{:type :text :text "Hello after retry"}
+ {:type :data :data-type "state"}]
+ (mt/with-log-level [metabase.metabot.self :fatal]
+ (into [] (#'api/combine-text-parts-xf)
+ (agent/run-agent-loop
+ {:messages [{:role :user :content "Hi"}]
+ :state {}
+ :profile-id :embedding_next
+ :context {}}))))
+ "Should get the response from the successful retry")
+ (is (= 2 @call-count)
+ "Should have called LLM twice (1 failure + 1 success")))))))
;;; ===================== Prometheus Metrics Tests =====================
@@ -806,3 +813,41 @@
(is (every? string? (keys chart-configs)))
(is (=? {chart-configs-key chart-config}
chart-configs)))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Profile permission checks
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest check-metabot-access-test
+ (let [check! #'agent/check-metabot-access!]
+ (testing "base metabot permission"
+ (testing "metabot :no blocks any profile"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"permission"
+ (check! :internal {:permission/metabot :no})))
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"permission"
+ (check! :sql {:permission/metabot :no})))
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"permission"
+ (check! :slackbot {:permission/metabot :no})))
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"permission"
+ (check! :embedding_next {:permission/metabot :no}))))
+ (testing "metabot :yes allows non-gated profiles"
+ (is (nil? (check! :internal {:permission/metabot :yes})))
+ (is (nil? (check! :slackbot {:permission/metabot :yes})))
+ (is (nil? (check! :embedding_next {:permission/metabot :yes})))))
+ (testing "profile-specific permissions (with metabot :yes)"
+ (testing "sql profile"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"permission"
+ (check! :sql {:permission/metabot :yes :permission/metabot-sql-generation :no})))
+ (is (check! :sql {:permission/metabot :yes :permission/metabot-sql-generation :yes})))
+ (testing "nlq profile"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"permission"
+ (check! :nlq {:permission/metabot :yes :permission/metabot-nlq :no})))
+ (is (check! :nlq {:permission/metabot :yes :permission/metabot-nlq :yes})))
+ (testing "transforms_codegen profile"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"permission"
+ (check! :transforms_codegen {:permission/metabot :yes :permission/metabot-sql-generation :no})))
+ (is (check! :transforms_codegen {:permission/metabot :yes :permission/metabot-sql-generation :yes})))
+ (testing "document-generate-content profile"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"permission"
+ (check! :document-generate-content {:permission/metabot :yes :permission/metabot-other-tools :no})))
+ (is (check! :document-generate-content {:permission/metabot :yes :permission/metabot-other-tools :yes}))))))
diff --git a/test/metabase/metabot/agent/profiles_test.clj b/test/metabase/metabot/agent/profiles_test.clj
index 101ce274e6a..8efcb033d3b 100644
--- a/test/metabase/metabot/agent/profiles_test.clj
+++ b/test/metabase/metabot/agent/profiles_test.clj
@@ -1,7 +1,9 @@
(ns metabase.metabot.agent.profiles-test
(:require
[clojure.test :refer :all]
+ [metabase.api-scope.core :as api-scope]
[metabase.metabot.agent.profiles :as profiles]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools.transforms :as tools.transforms]
[metabase.premium-features.core :as premium-features]
[metabase.test :as mt]))
@@ -100,61 +102,64 @@
(mt/with-temporary-setting-values [llm-metabot-provider "openrouter/google/gemini-2.5-flash"]
(is (= "openrouter/google/gemini-2.5-flash" (:model (profiles/get-profile :embedding_next)))))))
-(deftest get-tools-for-profile-capabilities-test
- (testing "filters tools by capabilities"
+(deftest get-tools-for-profile-excludes-capability-gated-tools-test
+ (binding [scope/*current-user-scope* api-scope/unrestricted]
(testing "empty capabilities excludes capability-gated tools but includes ungated tools"
(let [tools (profiles/get-tools-for-profile :internal [])]
;; Ungated tools should always be available
(is (contains? tools "search"))
(is (contains? tools "create_autogenerated_dashboard"))
;; Capability-gated tools should be excluded
- (is (not (contains? tools "navigate_user")))))
+ (is (not (contains? tools "navigate_user")))))))
+(deftest get-tools-for-profile-includes-capability-gated-tools-test
+ (binding [scope/*current-user-scope* api-scope/unrestricted]
(testing "providing a capability includes tools gated by that capability"
(let [tools (profiles/get-tools-for-profile :internal [:frontend-navigate-user-v1])]
(is (contains? tools "navigate_user"))))))
(deftest get-tools-for-profile-string-capabilities-test
- (testing "capabilities as strings (as sent by the API / benchmark client)"
- (testing "NLQ-only capabilities should exclude SQL tools and include navigate_user"
- (let [;; This is what the NLQ benchmark actually sends via the API:
- nlq-capabilities ["frontend:navigate_user_v1"
- "permission:save_questions"]
- tools (profiles/get-tools-for-profile :internal nlq-capabilities)]
- (is (contains? tools "search") "search should always be available")
- (is (contains? tools "construct_notebook_query") "notebook queries should be available")
- (is (contains? tools "read_resource") "read_resource should always be available")
- (is (contains? tools "navigate_user")
- "navigate_user should be available when frontend:navigate_user_v1 is in capabilities")
- (is (not (contains? tools "create_sql_query"))
- "create_sql_query should NOT be available without permission:write_sql_queries")
- (is (not (contains? tools "edit_sql_query"))
- "edit_sql_query should NOT be available without permission:write_sql_queries")
- (is (not (contains? tools "replace_sql_query"))
- "replace_sql_query should NOT be available without permission:write_sql_queries")))
+ (binding [scope/*current-user-scope* api-scope/unrestricted]
+ (testing "capabilities as strings (as sent by the API / benchmark client)"
+ (testing "NLQ-only capabilities should exclude SQL tools and include navigate_user"
+ (let [;; This is what the NLQ benchmark actually sends via the API:
+ nlq-capabilities ["frontend:navigate_user_v1"
+ "permission:save_questions"]
+ tools (profiles/get-tools-for-profile :internal nlq-capabilities)]
+ (is (contains? tools "search") "search should always be available")
+ (is (contains? tools "construct_notebook_query") "notebook queries should be available")
+ (is (contains? tools "read_resource") "read_resource should always be available")
+ (is (contains? tools "navigate_user")
+ "navigate_user should be available when frontend:navigate_user_v1 is in capabilities")
+ (is (not (contains? tools "create_sql_query"))
+ "create_sql_query should NOT be available without permission:write_sql_queries")
+ (is (not (contains? tools "edit_sql_query"))
+ "edit_sql_query should NOT be available without permission:write_sql_queries")
+ (is (not (contains? tools "replace_sql_query"))
+ "replace_sql_query should NOT be available without permission:write_sql_queries")))
- (testing "full capabilities including SQL write permission should include SQL tools"
- (let [full-capabilities ["frontend:navigate_user_v1"
- "permission:save_questions"
- "permission:write_sql_queries"]
- tools (profiles/get-tools-for-profile :internal full-capabilities)]
- (is (contains? tools "search"))
- (is (contains? tools "construct_notebook_query"))
- (is (contains? tools "navigate_user")
- "navigate_user should be available with frontend:navigate_user_v1")
- (is (contains? tools "create_sql_query")
- "create_sql_query should be available with permission:write_sql_queries")
- (is (contains? tools "edit_sql_query")
- "edit_sql_query should be available with permission:write_sql_queries")
- (is (contains? tools "replace_sql_query")
- "replace_sql_query should be available with permission:write_sql_queries")))
+ (testing "full capabilities including SQL write permission should include SQL tools"
+ (let [full-capabilities ["frontend:navigate_user_v1"
+ "permission:save_questions"
+ "permission:write_sql_queries"]
+ tools (profiles/get-tools-for-profile :internal full-capabilities)]
+ (is (contains? tools "search"))
+ (is (contains? tools "construct_notebook_query"))
+ (is (contains? tools "navigate_user")
+ "navigate_user should be available with frontend:navigate_user_v1")
+ (is (contains? tools "create_sql_query")
+ "create_sql_query should be available with permission:write_sql_queries")
+ (is (contains? tools "edit_sql_query")
+ "edit_sql_query should be available with permission:write_sql_queries")
+ (is (contains? tools "replace_sql_query")
+ "replace_sql_query should be available with permission:write_sql_queries")))
- (testing "empty capabilities should exclude all capability-gated tools"
- (let [tools (profiles/get-tools-for-profile :internal [])]
- (is (contains? tools "search") "ungated tools should remain")
- (is (not (contains? tools "navigate_user")))
- (is (not (contains? tools "create_sql_query"))
- "SQL tools should be gated by permission:write_sql_queries")))))
+ (testing "empty capabilities should exclude all capability-gated tools"
+ (let [tools (profiles/get-tools-for-profile :internal [])]
+ (is (contains? tools "search") "ungated tools should remain")
+ (is (not (contains? tools "navigate_user")))
+ (is (not (contains? tools "create_sql_query"))
+ "SQL tools should be gated by permission:write_sql_queries"))))))
(deftest transform-feature-capabilities-test
(let [orig-has-feature premium-features/has-feature?
diff --git a/test/metabase/metabot/agent/prompt_gating_test.clj b/test/metabase/metabot/agent/prompt_gating_test.clj
new file mode 100644
index 00000000000..940cc4ffdab
--- /dev/null
+++ b/test/metabase/metabot/agent/prompt_gating_test.clj
@@ -0,0 +1,283 @@
+(ns metabase.metabot.agent.prompt-gating-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.metabot.agent.prompts :as prompts]
+ [metabase.metabot.scope :as scope]
+ [metabase.test :as mt]))
+
+(defn- render-internal-template
+ "Render the internal.selmer template with given permission flags."
+ [perms]
+ (binding [scope/*current-user-metabot-permissions* perms]
+ (prompts/build-system-message-content
+ {:prompt-template "internal.selmer"}
+ {:current_time "2026-03-25T12:00:00Z"}
+ {})))
+
+(def ^:private all-yes-perms
+ {:permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :yes
+ :permission/metabot-other-tools :yes})
+
+(def ^:private no-sql-perms
+ {:permission/metabot-sql-generation :no
+ :permission/metabot-nlq :yes
+ :permission/metabot-other-tools :yes})
+
+(def ^:private no-nql-perms
+ {:permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :no
+ :permission/metabot-other-tools :yes})
+
+(def ^:private all-no-perms
+ {:permission/metabot-sql-generation :no
+ :permission/metabot-nlq :no
+ :permission/metabot-other-tools :no})
+
+(deftest ^:parallel prompt-includes-sql-sections-when-permitted-test
+ (let [rendered (render-internal-template all-yes-perms)]
+ (testing "SQL construction section is included"
+ (is (re-find #"sql_construction" rendered)))
+ (testing "SQL routing option is included"
+ (is (re-find #"Use SQL tools" rendered)))
+ (testing "SQL examples are included"
+ (is (re-find #"sql_writing" rendered)))
+ (testing "SQL tool selection guidance is included"
+ (is (re-find #"Explicitly requested.*Write SQL" rendered)))
+ (testing "SQL anti-pattern example is included"
+ (is (re-find #"Not checking field formats before SQL" rendered)))))
+
+(deftest ^:parallel prompt-excludes-sql-sections-when-not-permitted-test
+ (let [rendered (render-internal-template no-sql-perms)]
+ (testing "SQL construction section is excluded"
+ (is (not (re-find #"sql_construction" rendered))))
+ (testing "SQL routing option is excluded"
+ (is (not (re-find #"Use SQL tools" rendered))))
+ (testing "SQL examples are excluded"
+ (is (not (re-find #"sql_writing" rendered))))
+ (testing "SQL tool selection guidance is excluded"
+ (is (not (re-find #"Explicitly requested.*Write SQL" rendered))))
+ (testing "SQL anti-pattern example is excluded"
+ (is (not (re-find #"Not checking field formats before SQL" rendered))))
+ (testing "explicit denial for SQL is included"
+ (is (re-find #"You cannot write SQL" rendered)))
+ (testing "denial suggests NLQ as alternative"
+ (is (re-find #"natural language query builder" rendered)))))
+
+(deftest ^:parallel prompt-gates-nql-section-test
+ (let [with-nql (render-internal-template all-yes-perms)
+ without-nql (render-internal-template no-nql-perms)]
+ (testing "NLQ guidance included when permitted"
+ (is (re-find #"Natural Language Querying" with-nql)))
+ (testing "NLQ routing included when permitted"
+ (is (re-find #"Use natural language querying \(your default mode\)" with-nql)))
+ (testing "NLQ guidance excluded when not permitted"
+ (is (not (re-find #"Natural Language Querying" without-nql))))
+ (testing "NLQ routing excluded when not permitted"
+ (is (not (re-find #"Use natural language querying \(your default mode\)" without-nql))))
+ (testing "explicit denial for NLQ is included when not permitted"
+ (is (re-find #"You cannot use natural language querying" without-nql)))
+ (testing "denial suggests SQL as alternative"
+ (is (re-find #"offer to write SQL" without-nql)))))
+
+(deftest ^:parallel prompt-gates-other-tools-section-test
+ (let [with-other (render-internal-template all-yes-perms)
+ without-other (render-internal-template
+ {:permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :yes
+ :permission/metabot-other-tools :no})]
+ (testing "dashboard routing included when permitted"
+ (is (re-find #"Use X-ray auto-generated dashboard tool" with-other)))
+ (testing "dashboard routing excluded when not permitted"
+ (is (not (re-find #"Use dashboard tools" without-other))))
+ (testing "explicit denial for other tools is included when not permitted"
+ (is (re-find #"You cannot create dashboards or documents" without-other)))))
+
+(deftest ^:parallel prompt-gates-query-tools-sections-test
+ (let [with-queries (render-internal-template all-yes-perms)
+ without-queries (render-internal-template
+ {:permission/metabot-sql-generation :no
+ :permission/metabot-nlq :no
+ :permission/metabot-other-tools :yes})]
+ (testing "query-focused sections included when NQL or SQL is available"
+ (is (re-find #"CRITICAL CONSTRAINTS" with-queries))
+ (is (re-find #"Verify Data Structure" with-queries))
+ (is (re-find #"Anti-Patterns" with-queries))
+ (is (re-find #"value_in_samples" with-queries))
+ (is (re-find #"Show me X" with-queries)))
+ (testing "query-focused sections excluded when neither NQL nor SQL is available"
+ (is (not (re-find #"CRITICAL CONSTRAINTS" without-queries)))
+ (is (not (re-find #"Verify Data Structure" without-queries)))
+ (is (not (re-find #"Anti-Patterns" without-queries)))
+ (is (not (re-find #"value_in_samples" without-queries)))
+ (is (not (re-find #"Show me X" without-queries))))
+ (testing "general sections remain even without query tools"
+ (is (re-find #"data analysis assistant" without-queries))
+ (is (re-find #"Communication Style" without-queries))
+ (is (re-find #"search_request" without-queries))
+ (is (re-find #"Find \[existing content\]" without-queries)))
+ (testing "explicit denial for query tools is included"
+ (is (re-find #"You cannot build queries or create charts" without-queries)))
+ (testing "no individual SQL/NQL denials when both are off"
+ (is (not (re-find #"You cannot write SQL" without-queries)))
+ (is (not (re-find #"You cannot use natural language querying" without-queries))))))
+
+(deftest ^:parallel prompt-all-no-permissions-test
+ (let [rendered (render-internal-template all-no-perms)]
+ (testing "core prompt structure still renders"
+ (is (re-find #"data analysis assistant" rendered))
+ (is (re-find #"Communication Style" rendered)))
+ (testing "all gated sections are excluded"
+ (is (not (re-find #"sql_construction" rendered)))
+ (is (not (re-find #"Natural Language Querying" rendered)))
+ (is (not (re-find #"Use X-ray auto-generated dashboard tool" rendered)))
+ (is (not (re-find #"CRITICAL CONSTRAINTS" rendered)))
+ (is (not (re-find #"Verify Data Structure" rendered))))
+ (testing "denial messages are present"
+ (is (re-find #"You cannot build queries or create charts" rendered))
+ (is (re-find #"You cannot create dashboards or documents" rendered)))))
+
+(deftest ^:parallel defaults-to-no-permissions-when-unbound-test
+ (testing "when *current-user-metabot-permissions* is nil, defaults exclude everything"
+ (let [rendered (render-internal-template nil)]
+ (is (not (re-find #"sql_construction" rendered)))
+ (is (not (re-find #"Natural Language Querying" rendered)))
+ (is (not (re-find #"Use X-ray auto-generated dashboard tool" rendered)))
+ (is (not (re-find #"CRITICAL CONSTRAINTS" rendered)))
+ (is (re-find #"You cannot build queries or create charts" rendered))
+ (is (re-find #"You cannot create dashboards or documents" rendered)))))
+
+(deftest ^:parallel prompt-no-denials-when-all-enabled-test
+ (let [rendered (render-internal-template all-yes-perms)]
+ (testing "no denial messages when all permissions are enabled"
+ (is (not (re-find #"You cannot" rendered))))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Slackbot template gating
+;;; ──────────────────────────────────────────────────────────────────
+
+(defn- render-slackbot-template
+ "Render the slackbot.selmer template with given permission flags."
+ [perms]
+ (binding [scope/*current-user-metabot-permissions* perms]
+ (prompts/build-system-message-content
+ {:prompt-template "slackbot.selmer"}
+ {:current_time "2026-03-25T12:00:00Z"}
+ {})))
+
+(deftest ^:parallel slackbot-nlq-sections-gated-test
+ (let [with-nlq (render-slackbot-template all-yes-perms)
+ without-nlq (render-slackbot-template {:permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :no
+ :permission/metabot-other-tools :yes})]
+ (testing "NLQ sections included when permitted"
+ (is (re-find #"construct_notebook_query" with-nlq))
+ (is (re-find #"Data Exploration Workflow" with-nlq))
+ (is (re-find #"Request Modification Workflow" with-nlq))
+ (is (re-find #"CSV File Uploads" with-nlq)))
+ (testing "NLQ sections excluded when not permitted"
+ (is (not (re-find #"construct_notebook_query" without-nlq)))
+ (is (not (re-find #"Data Exploration Workflow" without-nlq)))
+ (is (not (re-find #"Request Modification Workflow" without-nlq)))
+ (is (not (re-find #"CSV File Uploads" without-nlq))))
+ (testing "NLQ denial message present when not permitted"
+ (is (re-find #"You cannot build custom queries" without-nlq)))))
+
+(deftest ^:parallel slackbot-other-tools-sections-gated-test
+ (let [with-other (render-slackbot-template all-yes-perms)
+ without-other (render-slackbot-template {:permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :yes
+ :permission/metabot-other-tools :no})]
+ (testing "other-tools sections included when permitted"
+ (is (re-find #"static_viz" with-other))
+ (is (re-find #"Visualization Titles" with-other))
+ (is (re-find #"Visual Previews" with-other)))
+ (testing "other-tools sections excluded when not permitted"
+ (is (not (re-find #"static_viz" without-other)))
+ (is (not (re-find #"Visualization Titles" without-other)))
+ (is (not (re-find #"Visual Previews" without-other))))
+ (testing "other-tools denial message present when not permitted"
+ (is (re-find #"You cannot create inline visualizations" without-other)))))
+
+(deftest ^:parallel slackbot-all-no-permissions-test
+ (let [rendered (render-slackbot-template all-no-perms)]
+ (testing "core structure still renders"
+ (is (re-find #"expert data analyst" rendered))
+ (is (re-find #"business-validated insights" rendered)))
+ (testing "NLQ and viz sections excluded"
+ (is (not (re-find #"construct_notebook_query" rendered)))
+ (is (not (re-find #"static_viz" rendered))))
+ (testing "denial messages present"
+ (is (re-find #"You cannot build custom queries" rendered))
+ (is (re-find #"You cannot create inline visualizations" rendered)))))
+
+(deftest ^:parallel slackbot-no-denials-when-all-enabled-test
+ (let [rendered (render-slackbot-template all-yes-perms)]
+ (testing "no denial messages when all permissions are enabled"
+ (is (not (re-find #"You cannot build custom queries" rendered)))
+ (is (not (re-find #"You cannot create inline visualizations" rendered))))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Custom system prompt injection
+;;; ──────────────────────────────────────────────────────────────────
+
+(defn- render-template
+ "Render a template with given permission flags and optional setting overrides."
+ [template-name perms]
+ (binding [scope/*current-user-metabot-permissions* perms]
+ (prompts/build-system-message-content
+ {:prompt-template template-name}
+ {:current_time "2026-03-25T12:00:00Z"}
+ {})))
+
+(deftest custom-chat-instructions-injected-when-set-test
+ (mt/with-premium-features #{:ai-controls}
+ (mt/with-temporary-setting-values [metabot-chat-system-prompt "Always respond in French."]
+ (let [rendered (render-template "internal.selmer" all-yes-perms)]
+ (is (re-find #"Custom Instructions" rendered))
+ (is (re-find #"Always respond in French" rendered))))))
+
+(deftest custom-sql-instructions-injected-when-set-test
+ (mt/with-premium-features #{:ai-controls}
+ (mt/with-temporary-setting-values [metabot-sql-system-prompt "Always respond in French."]
+ (let [rendered (render-template "sql-querying-only.selmer" all-yes-perms)]
+ (is (re-find #"Custom Instructions" rendered))
+ (is (re-find #"Always respond in French" rendered))))))
+
+(deftest custom-nlq-instructions-injected-when-set-test
+ (mt/with-premium-features #{:ai-controls}
+ (mt/with-temporary-setting-values [metabot-nlq-system-prompt "Always respond in French."]
+ (let [rendered (render-template "natural-language-querying-only.selmer" all-yes-perms)]
+ (is (re-find #"Custom Instructions" rendered))
+ (is (re-find #"Always respond in French" rendered))))))
+
+(deftest custom-instructions-absent-when-empty-test
+ (mt/with-temporary-setting-values [metabot-chat-system-prompt ""
+ metabot-nlq-system-prompt ""
+ metabot-sql-system-prompt ""]
+ (testing "internal template has no custom instructions section"
+ (let [rendered (render-template "internal.selmer" all-yes-perms)]
+ (is (not (re-find #"Custom Instructions" rendered)))))
+ (testing "sql template has no custom instructions section"
+ (let [rendered (render-template "sql-querying-only.selmer" all-yes-perms)]
+ (is (not (re-find #"Custom Instructions" rendered)))))
+ (testing "nlq template has no custom instructions section"
+ (let [rendered (render-template "natural-language-querying-only.selmer" all-yes-perms)]
+ (is (not (re-find #"Custom Instructions" rendered)))))))
+
+(deftest custom-instructions-isolated-per-template-test
+ (testing "chat prompt does not appear in sql template"
+ (mt/with-temporary-setting-values [metabot-chat-system-prompt "Chat only instruction."
+ metabot-sql-system-prompt ""]
+ (let [rendered (render-template "sql-querying-only.selmer" all-yes-perms)]
+ (is (not (re-find #"Chat only instruction" rendered))))))
+ (testing "sql prompt does not appear in nlq template"
+ (mt/with-temporary-setting-values [metabot-sql-system-prompt "SQL only instruction."
+ metabot-nlq-system-prompt ""]
+ (let [rendered (render-template "natural-language-querying-only.selmer" all-yes-perms)]
+ (is (not (re-find #"SQL only instruction" rendered))))))
+ (testing "nlq prompt does not appear in chat template"
+ (mt/with-temporary-setting-values [metabot-nlq-system-prompt "NLQ only instruction."
+ metabot-chat-system-prompt ""]
+ (let [rendered (render-template "internal.selmer" all-yes-perms)]
+ (is (not (re-find #"NLQ only instruction" rendered)))))))
diff --git a/test/metabase/metabot/agent/prompts_test.clj b/test/metabase/metabot/agent/prompts_test.clj
index 4ba35d9b06e..502414acf0e 100644
--- a/test/metabase/metabot/agent/prompts_test.clj
+++ b/test/metabase/metabot/agent/prompts_test.clj
@@ -10,13 +10,13 @@
(is (some? template))
(is (string? template))
(is (> (count template) 1000))
- (is (re-find #"Metabot" template))))
+ (is (re-find #"metabot_name" template))))
(testing "loads embedding-next.selmer template"
(let [template (prompts/load-system-prompt-template "embedding-next.selmer")]
(is (some? template))
(is (string? template))
- (is (re-find #"Metabot" template))))
+ (is (re-find #"metabot_name" template))))
(testing "returns nil for non-existent template"
(let [template (prompts/load-system-prompt-template "non-existent.selmer")]
diff --git a/test/metabase/metabot/agent/scope_enforcement_test.clj b/test/metabase/metabot/agent/scope_enforcement_test.clj
new file mode 100644
index 00000000000..1eb0ffbb6e9
--- /dev/null
+++ b/test/metabase/metabot/agent/scope_enforcement_test.clj
@@ -0,0 +1,92 @@
+(ns metabase.metabot.agent.scope-enforcement-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.api-scope.core :as api-scope]
+ [metabase.metabot.scope :as scope]
+ [metabase.metabot.tools :as tools]))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Tool list filtering by scope (via profiles/filter-by-scope)
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest ^:parallel filter-by-scope-test
+ (let [no-scope (with-meta (fn [_] {:output "legacy"})
+ {:tool-name "legacy" :schema [:=> [:cat :map] :map]})]
+
+ (testing "with unrestricted scope, all tools pass"
+ (binding [scope/*current-user-scope* api-scope/unrestricted]
+ (is (api-scope/scope-matches? scope/*current-user-scope* "agent:sql:create"))
+ (is (api-scope/scope-matches? scope/*current-user-scope* "agent:search"))))
+
+ (testing "with empty scope, no scoped tools pass"
+ (binding [scope/*current-user-scope* #{}]
+ (is (not (api-scope/scope-matches? scope/*current-user-scope* "agent:sql:create")))
+ (is (not (api-scope/scope-matches? scope/*current-user-scope* "agent:search")))))
+
+ (testing "with wildcard scope, matching tools pass"
+ (binding [scope/*current-user-scope* #{"agent:sql:*"}]
+ (is (api-scope/scope-matches? scope/*current-user-scope* "agent:sql:create"))
+ (is (not (api-scope/scope-matches? scope/*current-user-scope* "agent:search")))))
+
+ (testing "tools without scope always pass"
+ (binding [scope/*current-user-scope* #{}]
+ (is (nil? (:scope (meta no-scope))))))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Tool invocation scope check (via wrap-tools-with-state)
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest ^:parallel wrapped-tool-scope-enforcement-test
+ (let [tool-var (with-meta (fn [_args] {:output "success"})
+ {:tool-name "test_tool"
+ :schema [:=> [:cat :map] :map]
+ :scope "agent:sql:create"})
+ tools-map {"test_tool" tool-var}
+ memory-atom (atom {})
+ wrapped (tools/wrap-tools-with-state tools-map memory-atom nil)
+ wrapped-fn (get-in wrapped ["test_tool" :fn])]
+
+ (testing "tool executes when scope is satisfied"
+ (binding [scope/*current-user-scope* api-scope/unrestricted]
+ (is (= {:output "success"} (wrapped-fn {})))))
+
+ (testing "tool executes with matching wildcard scope"
+ (binding [scope/*current-user-scope* #{"agent:sql:*"}]
+ (is (= {:output "success"} (wrapped-fn {})))))
+
+ (testing "tool executes with exact scope match"
+ (binding [scope/*current-user-scope* #{"agent:sql:create"}]
+ (is (= {:output "success"} (wrapped-fn {})))))
+
+ (testing "tool returns denial when scope is not satisfied"
+ (binding [scope/*current-user-scope* #{}]
+ (let [result (wrapped-fn {})]
+ (is (string? (:output result)))
+ (is (re-find #"do not have permission" (:output result)))
+ ;; scope string should NOT be leaked in the output
+ (is (not (re-find #"agent:sql" (:output result)))))))
+
+ (testing "tool returns denial with wrong scope"
+ (binding [scope/*current-user-scope* #{"agent:notebook:*"}]
+ (let [result (wrapped-fn {})]
+ (is (re-find #"do not have permission" (:output result))))))))
+
+(deftest ^:parallel wrapped-tool-no-scope-test
+ (let [tool-var (with-meta (fn [_args] {:output "no-scope-tool"})
+ {:tool-name "legacy_tool"
+ :schema [:=> [:cat :map] :map]})
+ tools-map {"legacy_tool" tool-var}
+ memory-atom (atom {})
+ wrapped (tools/wrap-tools-with-state tools-map memory-atom nil)
+ wrapped-fn (get-in wrapped ["legacy_tool" :fn])]
+
+ (testing "tool without :scope always executes regardless of current scope"
+ (binding [scope/*current-user-scope* #{}]
+ (is (= {:output "no-scope-tool"} (wrapped-fn {}))))
+ (binding [scope/*current-user-scope* api-scope/unrestricted]
+ (is (= {:output "no-scope-tool"} (wrapped-fn {})))))))
+
+(deftest ^:parallel default-scope-is-empty-test
+ (testing "*current-user-scope* defaults to empty set — denies all scoped tools"
+ (is (= #{} scope/*current-user-scope*))
+ (is (not (api-scope/scope-matches? scope/*current-user-scope* "agent:sql:create")))))
diff --git a/test/metabase/metabot/api/document_test.clj b/test/metabase/metabot/api/document_test.clj
index e9e6c8ae3ae..e4763cdc716 100644
--- a/test/metabase/metabot/api/document_test.clj
+++ b/test/metabase/metabot/api/document_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.test :refer :all]
[metabase.analytics.snowplow-test :as snowplow-test]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.self.openrouter :as openrouter]
[metabase.metabot.test-util :as mut]
[metabase.test :as mt]
@@ -55,27 +56,28 @@
(deftest generate-content-snowplow-test
(mt/with-temporary-setting-values [llm-metabot-provider test-provider]
- (let [rasta-id (mt/user->id :rasta)]
- (with-redefs [openrouter/openrouter
- (fn [_]
- (mut/mock-llm-response
- [{:type :start :id "msg-1"}
- {:type :text :text "No chart available"}
- {:type :usage :usage {:promptTokens 100 :completionTokens 20}
- :model "anthropic/claude-haiku-4-5" :id "msg-1"}]))]
- (snowplow-test/with-fake-snowplow-collector
- (mt/user-http-request :rasta
- :post 200 "metabot/document/generate-content"
- {:instructions "Show me sales data"})
- (let [events (snowplow-test/pop-event-data-and-user-id!)
- token-events (filter #(contains? (:data %) "total_tokens") events)]
- (is (=? [{:user-id (str rasta-id)
- :data {"model_id" "openrouter/anthropic/claude-haiku-4-5"
- "total_tokens" 120
- "prompt_tokens" 100
- "completion_tokens" 20
- "estimated_costs_usd" 0.0
- "duration_ms" nat-int?
- "source" "document_generate_content"
- "tag" "agent"}}]
- token-events))))))))
+ (binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]
+ (let [rasta-id (mt/user->id :rasta)]
+ (with-redefs [openrouter/openrouter
+ (fn [_]
+ (mut/mock-llm-response
+ [{:type :start :id "msg-1"}
+ {:type :text :text "No chart available"}
+ {:type :usage :usage {:promptTokens 100 :completionTokens 20}
+ :model "anthropic/claude-haiku-4-5" :id "msg-1"}]))]
+ (snowplow-test/with-fake-snowplow-collector
+ (mt/user-http-request :rasta
+ :post 200 "metabot/document/generate-content"
+ {:instructions "Show me sales data"})
+ (let [events (snowplow-test/pop-event-data-and-user-id!)
+ token-events (filter #(contains? (:data %) "total_tokens") events)]
+ (is (=? [{:user-id (str rasta-id)
+ :data {"model_id" "openrouter/anthropic/claude-haiku-4-5"
+ "total_tokens" 120
+ "prompt_tokens" 100
+ "completion_tokens" 20
+ "estimated_costs_usd" 0.0
+ "duration_ms" nat-int?
+ "source" "document_generate_content"
+ "tag" "agent"}}]
+ token-events)))))))))
diff --git a/test/metabase/metabot/api/permissions_test.clj b/test/metabase/metabot/api/permissions_test.clj
new file mode 100644
index 00000000000..96f63b90b6b
--- /dev/null
+++ b/test/metabase/metabot/api/permissions_test.clj
@@ -0,0 +1,21 @@
+(ns metabase.metabot.api.permissions-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.test :as mt]))
+
+(deftest ^:parallel user-permissions-test
+ (testing "GET /api/metabot/permissions/user-permissions"
+ (testing "requires authentication"
+ (is (= "Unauthenticated"
+ (mt/client :get 401 "metabot/permissions/user-permissions"))))
+ (testing "superuser gets all-yes permissions"
+ (let [perms (:permissions (mt/user-http-request :crowberto :get 200 "metabot/permissions/user-permissions"))]
+ (is (= "yes" (:metabot perms)))
+ (is (= "yes" (:metabot-sql-generation perms)))
+ (is (= "yes" (:metabot-nlq perms)))
+ (is (= "yes" (:metabot-other-tools perms)))))
+ (testing "non-admin user gets resolved permissions"
+ (let [perms (:permissions (mt/user-http-request :rasta :get 200 "metabot/permissions/user-permissions"))]
+ (is (= 4 (count perms)))
+ (testing "all perm types are present with string values"
+ (is (every? string? (vals perms))))))))
diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.clj
index 1fa371ef6dc..30ca539228c 100644
--- a/test/metabase/metabot/api_test.clj
+++ b/test/metabase/metabot/api_test.clj
@@ -10,6 +10,7 @@
[metabase.metabot.api :as api]
[metabase.metabot.config :as metabot.config]
[metabase.metabot.context :as metabot.context]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.self :as metabot.self]
[metabase.metabot.self.openrouter :as openrouter]
[metabase.metabot.settings :as metabot.settings]
@@ -28,52 +29,53 @@
(deftest native-agent-streaming-test
(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider test-provider]
- (with-redefs [config/is-dev? true]
- (let [conversation-id (str (random-uuid))
- question {:role "user" :content "Test native streaming"}
- historical-message {:role "user" :content "previous message"}]
- (with-redefs [openrouter/openrouter (fn [_]
- (mut/mock-llm-response
- [{:type :start :id "msg-1"}
- {:type :text :text "Hello from native agent!"}
- {:type :usage :usage {:promptTokens 10 :completionTokens 5}
- :model "test-model" :id "msg-1"}]))]
- (testing "Native agent streaming request"
- (mt/with-model-cleanup [:model/MetabotMessage
- [:model/MetabotConversation :created_at]]
- (let [response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
- {:message (:content question)
- :context {}
- :conversation_id conversation-id
- :history [historical-message]
- :state {}})
- lines (str/split-lines response)
- conv (t2/select-one :model/MetabotConversation :id conversation-id)
- messages (t2/select :model/MetabotMessage :conversation_id conversation-id)]
+ (binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]
+ (with-redefs [config/is-dev? true]
+ (let [conversation-id (str (random-uuid))
+ question {:role "user" :content "Test native streaming"}
+ historical-message {:role "user" :content "previous message"}]
+ (with-redefs [openrouter/openrouter (fn [_]
+ (mut/mock-llm-response
+ [{:type :start :id "msg-1"}
+ {:type :text :text "Hello from native agent!"}
+ {:type :usage :usage {:promptTokens 10 :completionTokens 5}
+ :model "test-model" :id "msg-1"}]))]
+ (testing "Native agent streaming request"
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (let [response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ {:message (:content question)
+ :context {}
+ :conversation_id conversation-id
+ :history [historical-message]
+ :state {}})
+ lines (str/split-lines response)
+ conv (t2/select-one :model/MetabotConversation :id conversation-id)
+ messages (t2/select :model/MetabotMessage :conversation_id conversation-id)]
;; Native agent emits AI SDK v4 line protocol directly
- (testing "response contains expected line types"
+ (testing "response contains expected line types"
;; f:{start}, 0:"text" chunks, 2:{state data}, d:{finish with usage}
- (is (=? [#"f:.*"
- #"0:.*"
- #"2:.*"
- #"d:.*"]
- (m/distinct-by #(subs % 0 2) lines)))
+ (is (=? [#"f:.*"
+ #"0:.*"
+ #"2:.*"
+ #"d:.*"]
+ (m/distinct-by #(subs % 0 2) lines)))
;; Text chunks reassemble to full message
- (let [text-lines (filter #(str/starts-with? % "0:") lines)]
- (is (= "Hello from native agent!"
- (apply str (map #(json/decode (subs % 2)) text-lines)))))
+ (let [text-lines (filter #(str/starts-with? % "0:") lines)]
+ (is (= "Hello from native agent!"
+ (apply str (map #(json/decode (subs % 2)) text-lines)))))
;; Finish line includes usage
- (is (str/includes? (last lines) "promptTokens")))
- (is (=? {:user_id (mt/user->id :rasta)}
- conv))
+ (is (str/includes? (last lines) "promptTokens")))
+ (is (=? {:user_id (mt/user->id :rasta)}
+ conv))
;; Native agent stores parts in raw format
- (is (=? [{:total_tokens 0
- :role :user
- :data [{:role "user" :content (:content question)}]}
- {:total_tokens pos-int?
- :role :assistant
- :data [{:type "text" :text "Hello from native agent!"}]}]
- messages))))))))))
+ (is (=? [{:total_tokens 0
+ :role :user
+ :data [{:role "user" :content (:content question)}]}
+ {:total_tokens pos-int?
+ :role :assistant
+ :data [{:type "text" :text "Hello from native agent!"}]}]
+ messages)))))))))))
(defn ^:private sse-event
"Format an SSE event as a string for a mock LLM server."
@@ -146,6 +148,7 @@
(let [real-http-post http/post]
(with-redefs [llm.settings/llm-openrouter-api-key (constantly "fake-key")
llm.settings/llm-openrouter-api-base-url (constantly llm-url)
+ scope/resolve-user-permissions (constantly scope/all-yes-permissions)
;; The fake LLM server doesn't gzip, but clj-http wraps with
;; GZIPInputStream by default. Closing mid-stream causes ZLIB errors.
http/post (fn [url opts]
@@ -169,8 +172,8 @@
(.close ^java.io.Closeable body)
(u/poll {:thunk #(deref stored-parts)
:done? some?
- :interval-ms 5
- :timeout-ms 1000})
+ :interval-ms 10
+ :timeout-ms 3000})
(is (some? @stored-parts) "store-parts! was called even though client disconnected")
(testing "LLM server stopped writing when connection was dropped"
(is (< 10 @cnt) "Server should not have written all chunks"))
@@ -378,66 +381,62 @@
(deftest metabot-enabled-setting-test
(mt/with-temporary-setting-values [metabot.settings/llm-metabot-provider test-provider]
- (let [base-request {:message "Test"
- :context {}
- :conversation_id (str (random-uuid))
- :history []
- :state {}}]
- (with-redefs [openrouter/openrouter (fn [_]
- (mut/mock-llm-response
- [{:type :start :id "msg-1"}
- {:type :text :text "Hello"}
- {:type :usage :usage {:promptTokens 1 :completionTokens 1}
- :model "test-model" :id "msg-1"}]))]
- (testing "Regular metabot is blocked when metabot-enabled is false"
- (mt/with-temporary-setting-values [metabot-enabled? false]
- (mt/with-model-cleanup [:model/MetabotMessage
- [:model/MetabotConversation :created_at]]
- (mt/user-http-request :rasta :post 403 "metabot/agent-streaming"
- base-request))))
-
- (testing "Regular metabot works when metabot-enabled is true"
- (mt/with-temporary-setting-values [metabot-enabled? true]
- (mt/with-model-cleanup [:model/MetabotMessage
- [:model/MetabotConversation :created_at]]
- (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
- (assoc base-request :conversation_id (str (random-uuid)))))))
-
- (testing "Embedded metabot is blocked when embedded-metabot-enabled? is false"
- (mt/with-temporary-setting-values [embedded-metabot-enabled? false]
- (mt/with-model-cleanup [:model/MetabotMessage
- [:model/MetabotConversation :created_at]]
- (mt/user-http-request :rasta :post 403 "metabot/agent-streaming"
- (assoc base-request
- :metabot_id metabot.config/embedded-metabot-id
- :conversation_id (str (random-uuid)))))))
-
- (testing "Embedded metabot works when embedded-metabot-enabled? is true"
- (mt/with-temporary-setting-values [embedded-metabot-enabled? true]
- (mt/with-model-cleanup [:model/MetabotMessage
- [:model/MetabotConversation :created_at]]
- (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
- (assoc base-request
- :metabot_id metabot.config/embedded-metabot-id
- :conversation_id (str (random-uuid)))))))
-
- (testing "Regular metabot still works when only embedded is disabled"
- (mt/with-temporary-setting-values [metabot-enabled? true
- embedded-metabot-enabled? false]
- (mt/with-model-cleanup [:model/MetabotMessage
- [:model/MetabotConversation :created_at]]
- (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
- (assoc base-request :conversation_id (str (random-uuid)))))))
-
- (testing "Embedded metabot still works when only regular is disabled"
- (mt/with-temporary-setting-values [metabot-enabled? false
- embedded-metabot-enabled? true]
- (mt/with-model-cleanup [:model/MetabotMessage
- [:model/MetabotConversation :created_at]]
- (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
- (assoc base-request
- :metabot_id metabot.config/embedded-metabot-id
- :conversation_id (str (random-uuid)))))))))))
+ (binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]
+ (let [base-request {:message "Test"
+ :context {}
+ :conversation_id (str (random-uuid))
+ :history []
+ :state {}}]
+ (with-redefs [openrouter/openrouter (fn [_]
+ (mut/mock-llm-response
+ [{:type :start :id "msg-1"}
+ {:type :text :text "Hello"}
+ {:type :usage :usage {:promptTokens 1 :completionTokens 1}
+ :model "test-model" :id "msg-1"}]))]
+ (testing "Regular metabot is blocked when metabot-enabled is false"
+ (mt/with-temporary-setting-values [metabot-enabled? false]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (mt/user-http-request :rasta :post 403 "metabot/agent-streaming"
+ base-request))))
+ (testing "Regular metabot works when metabot-enabled is true"
+ (mt/with-temporary-setting-values [metabot-enabled? true]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ (assoc base-request :conversation_id (str (random-uuid)))))))
+ (testing "Embedded metabot is blocked when embedded-metabot-enabled? is false"
+ (mt/with-temporary-setting-values [embedded-metabot-enabled? false]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (mt/user-http-request :rasta :post 403 "metabot/agent-streaming"
+ (assoc base-request
+ :metabot_id metabot.config/embedded-metabot-id
+ :conversation_id (str (random-uuid)))))))
+ (testing "Embedded metabot works when embedded-metabot-enabled? is true"
+ (mt/with-temporary-setting-values [embedded-metabot-enabled? true]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ (assoc base-request
+ :metabot_id metabot.config/embedded-metabot-id
+ :conversation_id (str (random-uuid)))))))
+ (testing "Regular metabot still works when only embedded is disabled"
+ (mt/with-temporary-setting-values [metabot-enabled? true
+ embedded-metabot-enabled? false]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ (assoc base-request :conversation_id (str (random-uuid)))))))
+ (testing "Embedded metabot still works when only regular is disabled"
+ (mt/with-temporary-setting-values [metabot-enabled? false
+ embedded-metabot-enabled? true]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ (assoc base-request
+ :metabot_id metabot.config/embedded-metabot-id
+ :conversation_id (str (random-uuid))))))))))))
(deftest extract-usage-test
(testing "takes last cumulative usage per model"
diff --git a/test/metabase/metabot/scope_resolution_test.clj b/test/metabase/metabot/scope_resolution_test.clj
new file mode 100644
index 00000000000..6d641c5e2cf
--- /dev/null
+++ b/test/metabase/metabot/scope_resolution_test.clj
@@ -0,0 +1,84 @@
+(ns metabase.metabot.scope-resolution-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.metabot.scope :as scope]
+ [metabase.test :as mt]))
+
+(deftest user-metabot-perms-sql-generation-scopes-test
+ (testing "sql-generation :yes grants sql, transforms, snippets scopes"
+ (let [scopes (scope/user-metabot-perms->scopes
+ {:permission/metabot-sql-generation :yes
+ :permission/metabot-nlq :no
+ :permission/metabot-other-tools :no})]
+ (is (contains? scopes "agent:sql:*"))
+ (is (contains? scopes "agent:transforms:*"))
+ (is (contains? scopes "agent:snippets:*"))
+ (is (not (contains? scopes "agent:notebook:*")))
+ (is (not (contains? scopes "agent:viz:*"))))))
+
+(deftest user-metabot-perms-nql-scopes-test
+ (testing "nql :yes grants notebook, query, table, metric scopes"
+ (let [scopes (scope/user-metabot-perms->scopes
+ {:permission/metabot-sql-generation :no
+ :permission/metabot-nlq :yes
+ :permission/metabot-other-tools :no})]
+ (is (contains? scopes "agent:notebook:*"))
+ (is (contains? scopes "agent:query:*"))
+ (is (contains? scopes "agent:table:*"))
+ (is (contains? scopes "agent:metric:*"))
+ (is (not (contains? scopes "agent:sql:*"))))))
+
+(deftest user-metabot-perms-other-tools-scopes-test
+ (testing "other-tools :yes grants viz, dashboard, document, alert scopes"
+ (let [scopes (scope/user-metabot-perms->scopes
+ {:permission/metabot-sql-generation :no
+ :permission/metabot-nlq :no
+ :permission/metabot-other-tools :yes})]
+ (is (contains? scopes "agent:viz:*"))
+ (is (contains? scopes "agent:dashboard:*"))
+ (is (contains? scopes "agent:document:*"))
+ (is (contains? scopes "agent:alert:*"))
+ (is (not (contains? scopes "agent:sql:*"))))))
+
+(deftest user-metabot-perms-always-granted-scopes-test
+ (testing "always-granted scopes present regardless of permissions"
+ (let [scopes (scope/user-metabot-perms->scopes
+ {:permission/metabot-sql-generation :no
+ :permission/metabot-nlq :no
+ :permission/metabot-other-tools :no})]
+ (is (contains? scopes "agent:search"))
+ (is (contains? scopes "agent:resource:*"))
+ (is (contains? scopes "agent:todo:*"))
+ (is (contains? scopes "agent:metadata:*")))))
+
+(deftest user-metabot-perms-all-yes-scopes-test
+ (testing "all-yes grants all scopes"
+ (let [scopes (scope/user-metabot-perms->scopes scope/all-yes-permissions)]
+ (is (contains? scopes "agent:sql:*"))
+ (is (contains? scopes "agent:notebook:*"))
+ (is (contains? scopes "agent:viz:*"))
+ (is (contains? scopes "agent:search")))))
+
+(deftest user-metabot-perms-nil-falls-back-to-defaults-test
+ (testing "nil permissions falls back to defaults (all :no)"
+ (let [scopes (scope/user-metabot-perms->scopes nil)]
+ (is (contains? scopes "agent:search"))
+ (is (not (contains? scopes "agent:sql:*")))
+ (is (not (contains? scopes "agent:notebook:*")))
+ (is (not (contains? scopes "agent:viz:*"))))))
+
+(deftest resolve-user-permissions-nil-test
+ (testing "nil user-id returns all-yes in OSS"
+ (mt/with-premium-features #{}
+ (let [perms (scope/resolve-user-permissions nil)]
+ (is (= scope/all-yes-permissions perms)))))
+ (testing "nil user-id returns all-yes in EE with ai-controls"
+ (mt/with-premium-features #{:ai-controls}
+ (let [perms (scope/resolve-user-permissions nil)]
+ (is (= scope/all-yes-permissions perms))))))
+
+(deftest resolve-user-permissions-oss-returns-all-yes-test
+ (mt/with-premium-features #{}
+ (testing "OSS always returns all-yes regardless of user-id"
+ (let [perms (scope/resolve-user-permissions 1)]
+ (is (= scope/all-yes-permissions perms))))))
diff --git a/test/metabase/metabot/scope_test.clj b/test/metabase/metabot/scope_test.clj
new file mode 100644
index 00000000000..489a9644ebc
--- /dev/null
+++ b/test/metabase/metabot/scope_test.clj
@@ -0,0 +1,169 @@
+(ns metabase.metabot.scope-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.api-scope.core :as api-scope]
+ [metabase.metabot.agent.profiles]
+ [metabase.metabot.scope :as scope]))
+
+(deftest ^:parallel scope-matches?-test
+ (testing "exact match"
+ (is (api-scope/scope-matches? #{"agent:sql:create"} "agent:sql:create"))
+ (is (not (api-scope/scope-matches? #{"agent:sql:edit"} "agent:sql:create"))))
+
+ (testing "unrestricted wildcard"
+ (is (api-scope/scope-matches? #{"*"} "agent:sql:create"))
+ (is (api-scope/scope-matches? api-scope/unrestricted "agent:anything:here")))
+
+ (testing "hierarchical wildcard"
+ (is (api-scope/scope-matches? #{"agent:sql:*"} "agent:sql:create"))
+ (is (api-scope/scope-matches? #{"agent:sql:*"} "agent:sql:edit"))
+ (is (not (api-scope/scope-matches? #{"agent:sql:*"} "agent:notebook:create"))))
+
+ (testing "mid-level wildcard"
+ (is (api-scope/scope-matches? #{"agent:*"} "agent:sql:create"))
+ (is (api-scope/scope-matches? #{"agent:*"} "agent:viz:edit"))
+ (is (not (api-scope/scope-matches? #{"other:*"} "agent:sql:create"))))
+
+ (testing "empty scope set grants nothing"
+ (is (not (api-scope/scope-matches? #{} "agent:sql:create")))
+ (is (not (api-scope/scope-matches? #{} "agent:search"))))
+
+ (testing "multiple granted scopes"
+ (is (api-scope/scope-matches? #{"agent:sql:create" "agent:viz:edit"} "agent:sql:create"))
+ (is (api-scope/scope-matches? #{"agent:sql:create" "agent:viz:edit"} "agent:viz:edit"))
+ (is (not (api-scope/scope-matches? #{"agent:sql:create" "agent:viz:edit"} "agent:notebook:create"))))
+
+ (testing "malformed scope strings do not match"
+ (is (not (api-scope/scope-matches? #{""} "agent:sql:create")))
+ (is (not (api-scope/scope-matches? #{":"} "agent:sql:create")))
+ (is (not (api-scope/scope-matches? #{"agent:sql:create"} "")))))
+
+(deftest ^:parallel current-user-scope-default-test
+ (testing "*current-user-scope* defaults to empty set (no permissions)"
+ (is (= #{} scope/*current-user-scope*))))
+
+(deftest ^:parallel perms->scopes-default-test
+ (is (= scope/always-granted-scopes (scope/user-metabot-perms->scopes {})))
+ (is (= scope/always-granted-scopes (scope/user-metabot-perms->scopes nil))))
+
+(deftest ^:parallel perms->scopes-sql-generation-test
+ (let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-sql-generation :yes})]
+ (is (contains? scopes "agent:sql:*"))
+ (is (contains? scopes "agent:transforms:*"))
+ (is (contains? scopes "agent:snippets:*"))
+ (is (contains? scopes "agent:search"))))
+
+(deftest ^:parallel perms->scopes-nql-test
+ (let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-nlq :yes})]
+ (is (contains? scopes "agent:notebook:*"))
+ (is (contains? scopes "agent:query:*"))
+ (is (contains? scopes "agent:table:*"))
+ (is (contains? scopes "agent:metric:*"))))
+
+(deftest ^:parallel perms->scopes-other-tools-test
+ (let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-other-tools :yes})]
+ (is (contains? scopes "agent:viz:*"))
+ (is (contains? scopes "agent:dashboard:*"))
+ (is (contains? scopes "agent:document:*"))
+ (is (contains? scopes "agent:alert:*"))))
+
+(deftest ^:parallel perms->scopes-no-does-not-grant-test
+ (let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-sql-generation :no
+ :permission/metabot-nlq :no})]
+ (is (not (contains? scopes "agent:sql:*")))
+ (is (not (contains? scopes "agent:notebook:*")))
+ (is (contains? scopes "agent:search"))))
+
+(deftest ^:parallel perms->scopes-all-yes-test
+ (let [scopes (scope/user-metabot-perms->scopes scope/all-yes-permissions)]
+ (is (contains? scopes "agent:sql:*"))
+ (is (contains? scopes "agent:notebook:*"))
+ (is (contains? scopes "agent:viz:*"))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; Scope registry
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest ^:parallel defscope-vars-test
+ (testing "defscope vars are bound to their scope strings"
+ (is (= "agent:sql:create" scope/agent-sql-create))
+ (is (= "agent:viz:read" scope/agent-viz-read))
+ (is (= "agent:search" scope/agent-search))))
+
+(deftest ^:parallel registered-scope?-test
+ (testing "registered scopes return true"
+ (is (api-scope/registered-scope? "agent:sql:create"))
+ (is (api-scope/registered-scope? "agent:search"))
+ (is (api-scope/registered-scope? "agent:viz:edit")))
+ (testing "unregistered scopes return false"
+ (is (not (api-scope/registered-scope? "agent:nonexistent:scope")))
+ (is (not (api-scope/registered-scope? "agent:sql:*")))
+ (is (not (api-scope/registered-scope? "")))))
+
+(deftest ^:parallel all-scopes-test
+ (testing "all-scopes returns a non-empty collection of maps"
+ (let [scopes (api-scope/all-scopes)]
+ (is (pos? (count scopes)))
+ (is (every? #(contains? % :scope) scopes))
+ (is (every? #(contains? % :description) scopes))
+ (is (every? #(string? (:scope %)) scopes))))
+ (testing "all-scopes includes known scopes"
+ (let [scope-strings (set (map :scope (api-scope/all-scopes)))]
+ (is (contains? scope-strings "agent:sql:create"))
+ (is (contains? scope-strings "agent:search"))
+ (is (contains? scope-strings "agent:viz:read")))))
+
+(deftest ^:parallel scope-description-test
+ (testing "returns description for registered scope"
+ (is (some? (api-scope/scope-description "agent:sql:create"))))
+ (testing "returns nil for unregistered scope"
+ (is (nil? (api-scope/scope-description "agent:nonexistent:scope")))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; parse-scopes
+;;; ──────────────────────────────────────────────────────────────────
+
+(deftest ^:parallel parse-scopes-space-delimited-test
+ (is (= #{"agent:sql:create" "agent:search"} (api-scope/parse-scopes "agent:sql:create agent:search"))))
+
+(deftest ^:parallel parse-scopes-single-scope-test
+ (is (= #{"agent:search"} (api-scope/parse-scopes "agent:search"))))
+
+(deftest ^:parallel parse-scopes-trims-whitespace-test
+ (is (= #{"agent:search"} (api-scope/parse-scopes " agent:search "))))
+
+(deftest ^:parallel parse-scopes-multiple-spaces-test
+ (is (= #{"a" "b"} (api-scope/parse-scopes "a b"))))
+
+(deftest ^:parallel parse-scopes-nil-test
+ (is (nil? (api-scope/parse-scopes nil))))
+
+(deftest ^:parallel parse-scopes-blank-string-test
+ (is (nil? (api-scope/parse-scopes "")))
+ (is (nil? (api-scope/parse-scopes " "))))
+
+(deftest ^:parallel parse-scopes-non-string-test
+ (is (nil? (api-scope/parse-scopes 42))))
+
+;;; ──────────────────────────────────────────────────────────────────
+;;; validate-tool-var! rejects unregistered scopes
+;;; ──────────────────────────────────────────────────────────────────
+
+(defn- make-tool-var!
+ "Create a var with tool metadata for testing validate-tool-var!."
+ [sym tool-meta]
+ (let [v (intern *ns* sym (fn [_] nil))]
+ (alter-meta! v merge tool-meta)
+ v))
+
+(deftest validate-tool-var-rejects-unregistered-scope-test
+ (let [validate! @(resolve 'metabase.metabot.agent.profiles/validate-tool-var!)]
+ (testing "tool with registered scope passes validation"
+ (let [v (make-tool-var! 'test-ok-tool {:tool-name "ok" :schema [:=> [:cat :map] :map] :scope "agent:sql:create"})]
+ (is (true? (validate! v)))))
+ (testing "tool with unregistered scope throws"
+ (let [v (make-tool-var! 'test-bad-tool {:tool-name "bad" :schema [:=> [:cat :map] :map] :scope "agent:bogus:scope"})]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"unregistered scope" (validate! v)))))
+ (testing "tool without scope passes validation"
+ (let [v (make-tool-var! 'test-legacy-tool {:tool-name "legacy" :schema [:=> [:cat :map] :map]})]
+ (is (true? (validate! v)))))))
diff --git a/test/metabase/metabot/settings_test.clj b/test/metabase/metabot/settings_test.clj
index 5ee3ba699f1..7734fd38512 100644
--- a/test/metabase/metabot/settings_test.clj
+++ b/test/metabase/metabot/settings_test.clj
@@ -1,8 +1,80 @@
(ns metabase.metabot.settings-test
(:require
- [clojure.test :refer :all]
+ [clojure.test :refer [deftest is testing use-fixtures]]
[metabase.metabot.settings :as metabot.settings]
- [metabase.test :as mt]))
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]))
+
+(use-fixtures :once (fixtures/initialize :db))
+
+(deftest customization-settings-require-ai-controls-test
+ (testing "without :ai-controls feature, customization settings return defaults and reject writes"
+ (mt/with-premium-features #{}
+ (testing "branding settings return defaults"
+ (is (= "Metabot" (metabot.settings/metabot-name)))
+ (is (= "metabot" (metabot.settings/metabot-icon)))
+ (is (true? (metabot.settings/metabot-show-illustrations))))
+ (testing "system prompt settings return defaults"
+ (is (= "" (metabot.settings/metabot-chat-system-prompt)))
+ (is (= "" (metabot.settings/metabot-nlq-system-prompt)))
+ (is (= "" (metabot.settings/metabot-sql-system-prompt))))
+ (testing "branding settings reject writes"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Setting metabot-name is not enabled because feature :ai-controls is not available"
+ (metabot.settings/metabot-name! "Custom Bot")))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Setting metabot-icon is not enabled because feature :ai-controls is not available"
+ (metabot.settings/metabot-icon! "custom-icon")))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Setting metabot-show-illustrations is not enabled because feature :ai-controls is not available"
+ (metabot.settings/metabot-show-illustrations! false))))
+ (testing "system prompt settings reject writes"
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Setting metabot-chat-system-prompt is not enabled because feature :ai-controls is not available"
+ (metabot.settings/metabot-chat-system-prompt! "custom prompt")))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Setting metabot-nlq-system-prompt is not enabled because feature :ai-controls is not available"
+ (metabot.settings/metabot-nlq-system-prompt! "custom prompt")))
+ (is (thrown-with-msg?
+ clojure.lang.ExceptionInfo
+ #"Setting metabot-sql-system-prompt is not enabled because feature :ai-controls is not available"
+ (metabot.settings/metabot-sql-system-prompt! "custom prompt")))))))
+
+(deftest customization-settings-writable-with-ai-controls-test
+ (mt/with-premium-features #{:ai-controls}
+ (testing "branding settings are writable with :ai-controls"
+ (mt/discard-setting-changes [metabot-name]
+ (metabot.settings/metabot-name! "Custom Bot")
+ (is (= "Custom Bot" (metabot.settings/metabot-name))))
+ (mt/discard-setting-changes [metabot-icon]
+ (metabot.settings/metabot-icon! "custom-icon")
+ (is (= "custom-icon" (metabot.settings/metabot-icon))))
+ (mt/discard-setting-changes [metabot-show-illustrations]
+ (metabot.settings/metabot-show-illustrations! false)
+ (is (= false (metabot.settings/metabot-show-illustrations)))))
+ (testing "system prompt settings are writable with :ai-controls"
+ (mt/discard-setting-changes [metabot-chat-system-prompt]
+ (metabot.settings/metabot-chat-system-prompt! "Always respond in French.")
+ (is (= "Always respond in French." (metabot.settings/metabot-chat-system-prompt))))
+ (mt/discard-setting-changes [metabot-nlq-system-prompt]
+ (metabot.settings/metabot-nlq-system-prompt! "Be concise.")
+ (is (= "Be concise." (metabot.settings/metabot-nlq-system-prompt))))
+ (mt/discard-setting-changes [metabot-sql-system-prompt]
+ (metabot.settings/metabot-sql-system-prompt! "Use CTEs.")
+ (is (= "Use CTEs." (metabot.settings/metabot-sql-system-prompt)))))))
+
+(deftest ^:parallel operational-settings-not-gated-test
+ (testing "core operational settings remain functional without :ai-controls"
+ (mt/with-premium-features #{}
+ (is (boolean? (metabot.settings/metabot-enabled?)))
+ (is (boolean? (metabot.settings/embedded-metabot-enabled?)))
+ (is (string? (metabot.settings/llm-metabot-provider)))
+ (is (string? (metabot.settings/llm-metabot-provider-lite))))))
(deftest internal-tasks-disabled-by-default-test
(testing "returns false when the setting is not explicitly enabled"
diff --git a/test/metabase/metabot/tools_test.clj b/test/metabase/metabot/tools_test.clj
index 8671a8be090..02242526cf4 100644
--- a/test/metabase/metabot/tools_test.clj
+++ b/test/metabase/metabot/tools_test.clj
@@ -1,7 +1,9 @@
(ns metabase.metabot.tools-test
(:require
[clojure.test :refer :all]
+ [metabase.api-scope.core :as api-scope]
[metabase.metabot.agent.profiles :as profiles]
+ [metabase.metabot.scope :as scope]
[metabase.metabot.tools :as agent-tools]
[metabase.metabot.tools.charts.create :as create-chart-tools]
[metabase.metabot.tools.filters :as filter-tools]))
@@ -47,77 +49,82 @@
result (#'profiles/filter-by-capabilities tool-vars capabilities)]
(is (= tool-vars result)))))
-(deftest get-tools-for-profile-test
- (testing "returns tools for embedding_next profile"
- (let [tools (profiles/get-tools-for-profile :embedding_next #{})]
- (is (map? tools))
- (is (contains? tools "construct_notebook_query"))
- (is (contains? tools "read_resource"))
- (is (contains? tools "list_available_data_sources"))))
+(defn- tools-for-profile
+ "Get tools for a profile with unrestricted scope."
+ [profile-id]
+ (binding [scope/*current-user-scope* api-scope/unrestricted]
+ (profiles/get-tools-for-profile profile-id #{})))
- (testing "returns tools for internal profile"
- (let [tools (profiles/get-tools-for-profile :internal #{})]
- (is (map? tools))
- (is (>= (count tools) 5))
- (is (contains? tools "search"))
- (is (contains? tools "edit_chart"))
- (is (contains? tools "create_chart"))
- (is (contains? tools "create_dashboard_subscription"))))
+(deftest ^:parallel get-tools-for-embedding-next-profile-test
+ (let [tools (tools-for-profile :embedding_next)]
+ (is (map? tools))
+ (is (contains? tools "construct_notebook_query"))
+ (is (contains? tools "read_resource"))
+ (is (contains? tools "list_available_data_sources"))))
- (testing "returns tools for transforms_codegen profile"
- (let [tools (profiles/get-tools-for-profile :transforms_codegen #{})]
- (is (map? tools))
- (is (contains? tools "search"))
- (is (contains? tools "list_available_fields"))
- (is (contains? tools "todo_write"))
- (is (contains? tools "todo_read"))))
+(deftest ^:parallel get-tools-for-internal-profile-test
+ (let [tools (tools-for-profile :internal)]
+ (is (map? tools))
+ (is (>= (count tools) 5))
+ (is (contains? tools "search"))
+ (is (contains? tools "edit_chart"))
+ (is (contains? tools "create_chart"))
+ (is (contains? tools "create_dashboard_subscription"))))
- (testing "returns tools for sql profile"
- (let [tools (profiles/get-tools-for-profile :sql #{})]
- (is (map? tools))
- (is (contains? tools "search"))
- (is (contains? tools "read_resource"))
- (is (contains? tools "ask_for_sql_clarification"))))
+(deftest ^:parallel get-tools-for-transforms-codegen-profile-test
+ (let [tools (tools-for-profile :transforms_codegen)]
+ (is (map? tools))
+ (is (contains? tools "search"))
+ (is (contains? tools "list_available_fields"))
+ (is (contains? tools "todo_write"))
+ (is (contains? tools "todo_read"))))
- (testing "returns tools for nlq profile"
- (let [tools (profiles/get-tools-for-profile :nlq #{})]
- (is (map? tools))
- (is (contains? tools "search"))
- (is (contains? tools "construct_notebook_query"))
- (is (contains? tools "create_chart"))))
+(deftest ^:parallel get-tools-for-sql-profile-test
+ (let [tools (tools-for-profile :sql)]
+ (is (map? tools))
+ (is (contains? tools "search"))
+ (is (contains? tools "read_resource"))
+ (is (contains? tools "ask_for_sql_clarification"))))
- (testing "returns tools for document_generate_content profile"
- (let [tools (profiles/get-tools-for-profile :document-generate-content #{})]
- (is (map? tools))
- (is (contains? tools "document_schema_collect"))
- (is (contains? tools "list_available_data_sources"))
- (is (contains? tools "list_available_fields"))
- (is (contains? tools "get_field_values"))
- (is (contains? tools "document_construct_model_chart"))
- (is (contains? tools "document_construct_sql_chart"))))
+(deftest ^:parallel get-tools-for-nlq-profile-test
+ (let [tools (tools-for-profile :nlq)]
+ (is (map? tools))
+ (is (contains? tools "search"))
+ (is (contains? tools "construct_notebook_query"))
+ (is (contains? tools "create_chart"))))
- (testing "returns tools for slackbot profile"
- (let [tools (profiles/get-tools-for-profile :slackbot #{})]
- (is (map? tools))
- (is (contains? tools "search"))
- (is (contains? tools "construct_notebook_query"))
- (is (contains? tools "list_available_fields"))
- (is (contains? tools "get_field_values"))
- (is (contains? tools "static_viz"))
- (is (contains? tools "create_alert"))
- (is (contains? tools "create_dashboard_subscription"))))
+(deftest ^:parallel get-tools-for-document-generate-content-profile-test
+ (let [tools (tools-for-profile :document-generate-content)]
+ (is (map? tools))
+ (is (contains? tools "document_schema_collect"))
+ (is (contains? tools "list_available_data_sources"))
+ (is (contains? tools "list_available_fields"))
+ (is (contains? tools "get_field_values"))
+ (is (contains? tools "document_construct_model_chart"))
+ (is (contains? tools "document_construct_sql_chart"))))
- (testing "returns empty map for unknown profile"
- (let [tools (profiles/get-tools-for-profile :unknown-profile #{})]
- (is (empty? tools))))
+(deftest ^:parallel get-tools-for-slackbot-profile-test
+ (let [tools (tools-for-profile :slackbot)]
+ (is (map? tools))
+ (is (contains? tools "search"))
+ (is (contains? tools "construct_notebook_query"))
+ (is (contains? tools "list_available_fields"))
+ (is (contains? tools "get_field_values"))
+ (is (contains? tools "static_viz"))
+ (is (contains? tools "create_alert"))
+ (is (contains? tools "create_dashboard_subscription"))))
- (testing "returned tools are vars with correct metadata"
- (let [tools (profiles/get-tools-for-profile :embedding_next #{})]
- (doseq [[tool-name tool-var] tools]
- (is (var? tool-var))
- (is (string? tool-name))
- (is (= tool-name (:tool-name (meta tool-var))))
- (is (some? (:schema (meta tool-var))))))))
+(deftest ^:parallel get-tools-for-unknown-profile-test
+ (let [tools (tools-for-profile :unknown-profile)]
+ (is (empty? tools))))
+
+(deftest ^:parallel get-tools-for-profile-metadata-test
+ (let [tools (tools-for-profile :embedding_next)]
+ (doseq [[tool-name tool-var] tools]
+ (is (var? tool-var))
+ (is (string? tool-name))
+ (is (= tool-name (:tool-name (meta tool-var))))
+ (is (some? (:schema (meta tool-var)))))))
(deftest search-tool-test
(testing "search-tool var has valid metadata"
diff --git a/test_resources/serialization_baseline/settings.yaml b/test_resources/serialization_baseline/settings.yaml
index 524cb03adc8..8fbf4793b82 100644
--- a/test_resources/serialization_baseline/settings.yaml
+++ b/test_resources/serialization_baseline/settings.yaml
@@ -39,7 +39,13 @@ landing-page-illustration-custom: null
loading-message: null
login-page-illustration: null
login-page-illustration-custom: null
+metabot-chat-system-prompt: null
metabot-enabled?: null
+metabot-icon: null
+metabot-name: null
+metabot-nlq-system-prompt: null
+metabot-show-illustrations: null
+metabot-sql-system-prompt: null
native-query-autocomplete-match-style: null
no-data-illustration: null
no-data-illustration-custom: null