The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Report where MCP saves questions; default to personal collection (#75491)
Chris Truter8c71b27b7700
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 70b3da4b207..191fd75dab7 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -176,6 +176,7 @@settingsutil}:model-imports #{:model/Card+ :model/Collection:model/Dashboard:model/DashboardCard:model/Tablediff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex 81b96a820a5..0cce808823d 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -57,6 +57,32 @@;;; ---------------------------------------------------- Helpers ------------------------------------------------------+(defn- personal-collection-id+ "Id of the current caller's personal collection, created on demand; `nil` for API-key callers,+ which have none. Agent-created content defaults here rather than the root collection REST uses —+ the user's own space, not shared \"Our analytics\"."+ []+ (:id (collection/user->personal-collection api/*current-user-id*)))++(defn- collection-path+ "Permission-filtered location breadcrumb of `collection-id`, e.g. \"Our analytics / Marketing / Q3\".+ Ancestors the caller can't read are omitted, matching the app breadcrumb.+ A `nil` `collection-id` is the root collection (\"Our analytics\"), not a personal collection."+ [collection-id]+ (if-not collection-id+ (:name (collection/root-collection-with-ui-details nil))+ (let [coll (t2/select-one [:model/Collection :id :name :location :personal_owner_id+ :namespace :archived_directly]+ collection-id)+ ;; `:effective_ancestors` is the app breadcrumb: it leads with the "Our analytics" root and+ ;; drops ancestors the caller can't read. A personal subtree leads with the personal+ ;; collection instead, so drop that root crumb for them.+ ancestors (cond->> (:effective_ancestors (t2/hydrate coll :effective_ancestors))+ (collection/is-personal-collection-or-descendant-of-one? coll)+ (remove #(= "root" (:id %))))+ chain (collection/personal-collections-with-ui-details (conj (vec ancestors) coll))]+ (str/join " / " (map :name chain)))))+(defn submit-mcp-visualization-feedback!"Submit MCP Apps visualization feedback to Harbormaster.@@ -612,31 +638,37 @@(mr/def ::create-question-response[:map- [:id ms/PositiveInt]- [:name ms/NonBlankString]- [:url :string]- [:display :string]- [:collection_id [:maybe ms/PositiveInt]]- [:description [:maybe :string]]])+ [:id ms/PositiveInt]+ [:name ms/NonBlankString]+ [:url :string]+ [:display :string]+ [:collection_id [:maybe ms/PositiveInt]]+ [:collection_path :string]+ [:description [:maybe :string]]])(api.macros/defendpoint :post "/v1/question" :- ::create-question-response"Save a previously constructed query as a named question (card).The `query` parameter accepts a `query_handle` (UUID) returned by `construct_query`,or a base64-encoded MBQL string. MCP callers should always use the handle.- Optionally specify display type, description, collection, and visualization settings."+ Optionally specify display type, description, collection, and visualization settings.+ If `collection_id` is omitted the question is saved to the caller's personal collection.+ The response `collection_path` is the saved location."{:scope metabot/agent-question-create:tool {:name "create_question":description (str "Save a query as a named question in Metabase. ""Pass the `query_handle` returned by `construct_query`. ""Optionally set display type (table, bar, line, pie, etc.), "- "description, and target collection.")}}+ "description, and target collection. "+ "If you omit collection_id it's saved to the user's personal collection. "+ "Report the saved location from the response `collection_path`.")}}[_route-params_query-params{:keys [query display description collection_id visualization_settings]question-name :name}:- ::create-question-request]- (let [dataset-query (-> query u/decode-base64 json/decode+kw)]+ (let [dataset-query (-> query u/decode-base64 json/decode+kw)+ collection_id (or collection_id (personal-collection-id))];; Mirror REST `POST /api/card/` pre-checks before calling `queries/create-card!`.;; `create-card!` itself does NOT run permissions checks; without these mirroring the;; REST endpoint, an LLM caller could (a) save a card whose query references data the@@ -658,12 +690,13 @@:collection_id collection_id:visualization_settings (or visualization_settings {})}{:id api/*current-user-id*})]- {:id (:id card)- :name (:name card)- :url (channel.urls/card-url (:id card))- :display (name (:display card))- :collection_id (:collection_id card)- :description (:description card)})))+ {:id (:id card)+ :name (:name card)+ :url (channel.urls/card-url (:id card))+ :display (name (:display card))+ :collection_id (:collection_id card)+ :collection_path (collection-path (:collection_id card))+ :description (:description card)})));;; ------------------------------------------------- Update Question ------------------------------------------------@@ -685,12 +718,13 @@after an update. Excludes the full dataset_query, which the caller can re-fetch via`read_resource` if needed."[:map- [:id ms/PositiveInt]- [:name ms/NonBlankString]- [:display :string]- [:collection_id [:maybe ms/PositiveInt]]- [:description [:maybe :string]]- [:archived :boolean]])+ [:id ms/PositiveInt]+ [:name ms/NonBlankString]+ [:display :string]+ [:collection_id [:maybe ms/PositiveInt]]+ [:collection_path :string]+ [:description [:maybe :string]]+ [:archived :boolean]])(api.macros/defendpoint :put "/v1/question/:id" :- ::update-question-response"Update a saved question (card). Patch semantics - only fields that you pass are changed.@@ -770,12 +804,13 @@:actor @api/*current-user*:delete-old-dashcards? false})updated (t2/select-one :model/Card :id id)]- {:id (:id updated)- :name (:name updated)- :display (clojure.core/name (:display updated))- :collection_id (:collection_id updated)- :description (:description updated)- :archived (boolean (:archived updated))}))+ {:id (:id updated)+ :name (:name updated)+ :display (clojure.core/name (:display updated))+ :collection_id (:collection_id updated)+ :collection_path (collection-path (:collection_id updated))+ :description (:description updated)+ :archived (boolean (:archived updated))}));;; ------------------------------------------------ Create Dashboard -----------------------------------------------@@ -788,59 +823,66 @@(mr/def ::create-dashboard-response[:map- [:id ms/PositiveInt]- [:name ms/NonBlankString]- [:url :string]- [:collection_id [:maybe ms/PositiveInt]]- [:description [:maybe :string]]- [:dashcard_ids [:sequential ms/PositiveInt]]])+ [:id ms/PositiveInt]+ [:name ms/NonBlankString]+ [:url :string]+ [:collection_id [:maybe ms/PositiveInt]]+ [:collection_path :string]+ [:description [:maybe :string]]+ [:dashcard_ids [:sequential ms/PositiveInt]]])(api.macros/defendpoint :post "/v1/dashboard" :- ::create-dashboard-response"Create a new dashboard, optionally populated with saved questions.Pass `question_ids` to add existing saved questions as cards on the dashboard.- Cards are automatically positioned on the grid based on their display type."+ Cards are automatically positioned on the grid based on their display type.+ If `collection_id` is omitted the dashboard is saved to the caller's personal collection.+ The response `collection_path` is the saved location."{:scope metabot/agent-dashboard-create:tool {:name "create_dashboard":description (str "Create a dashboard in Metabase. ""Optionally pass question_ids to add saved questions as cards. ""Cards are auto-positioned on the dashboard grid. "+ "If you omit collection_id it's saved to the user's personal collection. "+ "Report the saved location from the response `collection_path`. ""Returns the dashboard URL.")}}[_route-params_query-params{:keys [description collection_id question_ids]dashboard-name :name}:- ::create-dashboard-request]- (api/create-check :model/Dashboard {:collection_id collection_id})- (let [cards (when (seq question_ids)- (mapv #(api/read-check :model/Card %) question_ids))- dash (t2/with-transaction [_conn]- (let [dash (first (t2/insert-returning-instances!- :model/Dashboard- {:name dashboard-name- :description description- :parameters []- :creator_id api/*current-user-id*- :collection_id collection_id}))]- (when (seq cards)- (reduce (fn [placed card]- (let [display (or (:display card) :table)- position (autoplace/get-position-for-new-dashcard placed display)]- (t2/insert-returning-instance!- :model/DashboardCard- (merge position {:dashboard_id (:id dash)- :card_id (:id card)}))- (conj placed position)))- []- cards))- dash))]- (events/publish-event! :event/dashboard-create {:object dash :user-id api/*current-user-id*})- {:id (:id dash)- :name (:name dash)- :url (channel.urls/dashboard-url (:id dash))- :collection_id (:collection_id dash)- :description (:description dash)- :dashcard_ids (mapv :id (t2/select :model/DashboardCard :dashboard_id (:id dash)))}))+ (let [collection_id (or collection_id (personal-collection-id))]+ (api/create-check :model/Dashboard {:collection_id collection_id})+ (let [cards (when (seq question_ids)+ (mapv #(api/read-check :model/Card %) question_ids))+ dash (t2/with-transaction [_conn]+ (let [dash (first (t2/insert-returning-instances!+ :model/Dashboard+ {:name dashboard-name+ :description description+ :parameters []+ :creator_id api/*current-user-id*+ :collection_id collection_id}))]+ (when (seq cards)+ (reduce (fn [placed card]+ (let [display (or (:display card) :table)+ position (autoplace/get-position-for-new-dashcard placed display)]+ (t2/insert-returning-instance!+ :model/DashboardCard+ (merge position {:dashboard_id (:id dash)+ :card_id (:id card)}))+ (conj placed position)))+ []+ cards))+ dash))]+ (events/publish-event! :event/dashboard-create {:object dash :user-id api/*current-user-id*})+ {:id (:id dash)+ :name (:name dash)+ :url (channel.urls/dashboard-url (:id dash))+ :collection_id (:collection_id dash)+ :collection_path (collection-path (:collection_id dash))+ :description (:description dash)+ :dashcard_ids (mapv :id (t2/select :model/DashboardCard :dashboard_id (:id dash)))})));;; ------------------------------------------------- Update Dashboard -----------------------------------------------@@ -876,12 +918,13 @@"Returned by `update_dashboard`. `:dashcard_ids` is the post-mutation list of dashcardids in row/col order so the LLM can confirm what landed on the dashboard."[:map- [:id ms/PositiveInt]- [:name ms/NonBlankString]- [:collection_id [:maybe ms/PositiveInt]]- [:description [:maybe :string]]- [:archived :boolean]- [:dashcard_ids [:sequential ms/PositiveInt]]])+ [:id ms/PositiveInt]+ [:name ms/NonBlankString]+ [:collection_id [:maybe ms/PositiveInt]]+ [:collection_path :string]+ [:description [:maybe :string]]+ [:archived :boolean]+ [:dashcard_ids [:sequential ms/PositiveInt]]])(defn- size-override"Optional explicit size from the LLM. Returns {:width :height} or nil to fall back to defaults."@@ -1036,12 +1079,13 @@(let [updated (t2/select-one :model/Dashboard :id id)](events/publish-event! :event/dashboard-update{:object updated :user-id api/*current-user-id*})- {:id (:id updated)- :name (:name updated)- :collection_id (:collection_id updated)- :description (:description updated)- :archived (boolean (:archived updated))- :dashcard_ids (mapv :id (t2/select :model/DashboardCard :dashboard_id id))})))+ {:id (:id updated)+ :name (:name updated)+ :collection_id (:collection_id updated)+ :collection_path (collection-path (:collection_id updated))+ :description (:description updated)+ :archived (boolean (:archived updated))+ :dashcard_ids (mapv :id (t2/select :model/DashboardCard :dashboard_id id))})));;; ------------------------------------------------ Create Collection -----------------------------------------------diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex 3006ac6d8c0..ff72ab18260 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -8,6 +8,7 @@[java-time.api :as t][metabase.agent-api.api :as agent-api.api][metabase.agent-api.settings :as agent-api.settings]+ [metabase.collections.models.collection :as collection][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.lib.normalize :as lib.normalize]@@ -446,17 +447,20 @@;;; ------------------------------------------------ Create Question Tests -------------------------------------------(deftest create-question-test- (testing "Creates a saved question from a constructed query"- (let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"+ (testing "Omitting collection_id saves to the caller's personal collection, not root"+ (let [personal-id (:id (collection/user->personal-collection (mt/user->id :rasta)))+ personal-name (collection/user->personal-collection-name (mt/user->id :rasta) :user)+ construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"{:query (orders-query :limit 10)})create-resp (mt/user-http-request :rasta :post 200 "agent/v1/question"{:name "Agent Test Question":query (:query construct-resp)})]- (is (=? {:id pos?- :name "Agent Test Question"- :display "table"- :collection_id nil- :description nil}+ (is (=? {:id pos?+ :name "Agent Test Question"+ :display "table"+ :collection_id personal-id+ :collection_path personal-name+ :description nil}create-resp))(is (t2/exists? :model/Card :id (:id create-resp)))(t2/delete! :model/Card :id (:id create-resp))))@@ -470,11 +474,12 @@:display "bar":description "A test question":collection_id coll-id})]- (is (=? {:id pos?- :name "Agent Question With Options"- :display "bar"- :collection_id coll-id- :description "A test question"}+ (is (=? {:id pos?+ :name "Agent Question With Options"+ :display "bar"+ :collection_id coll-id+ :collection_path "Our analytics / Agent Question Collection"+ :description "A test question"}create-resp))(t2/delete! :model/Card :id (:id create-resp)))))(testing "Returns 403 when caller cannot run the proposed query"@@ -502,17 +507,62 @@:query (:query construct-resp):collection_id locked-id}))))))+(deftest create-question-collection-path-test+ (testing "collection_path is the full breadcrumb, mirroring the app's location"+ (mt/with-temp [:model/Collection {parent-id :id} {:name "Parent Coll"}+ :model/Collection {child-id :id} {:name "Child Coll" :location (format "/%d/" parent-id)}]+ (let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"+ {:query (orders-query :limit 10)})+ create-resp (mt/user-http-request :rasta :post 200 "agent/v1/question"+ {:name "Nested Q"+ :query (:query construct-resp)+ :collection_id child-id})]+ (is (= "Our analytics / Parent Coll / Child Coll" (:collection_path create-resp)))+ (t2/delete! :model/Card :id (:id create-resp)))))+ (testing "Personal-collection subtrees breadcrumb under the owner's personal collection, not Our analytics"+ (let [personal-id (:id (collection/user->personal-collection (mt/user->id :rasta)))+ personal-name (collection/user->personal-collection-name (mt/user->id :rasta) :user)+ construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"+ {:query (orders-query :limit 10)})+ create-resp (mt/user-http-request :rasta :post 200 "agent/v1/question"+ {:name "Personal Q"+ :query (:query construct-resp)+ :collection_id personal-id})]+ (is (= personal-name (:collection_path create-resp)))+ (t2/delete! :model/Card :id (:id create-resp))))+ (testing "collection_path omits ancestors the caller can't read — no hidden-name leak"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {a-id :id} {:name "Visible Parent"}+ :model/Collection {b-id :id} {:name "Hidden Parent" :location (format "/%d/" a-id)}+ :model/Collection {c-id :id} {:name "Leaf Coll" :location (format "/%d/%d/" a-id b-id)}]+ ;; rasta can write the leaf and read its top ancestor, but has no access to the middle one.+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) a-id)+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) c-id)+ (let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"+ {:query (orders-query :limit 10)})+ create-resp (mt/user-http-request :rasta :post 200 "agent/v1/question"+ {:name "Perm Filtered Q"+ :query (:query construct-resp)+ :collection_id c-id})]+ ;; rasta can't read the root collection here either, so "Our analytics" is dropped too —+ ;; the point is that the unreadable middle parent never appears.+ (is (= "Visible Parent / Leaf Coll" (:collection_path create-resp)))+ (t2/delete! :model/Card :id (:id create-resp)))))))+;;; ----------------------------------------------- Create Dashboard Tests ------------------------------------------(deftest create-dashboard-test- (testing "Creates an empty dashboard"- (let [resp (mt/user-http-request :rasta :post 200 "agent/v1/dashboard"- {:name "Agent Test Dashboard"})]- (is (=? {:id pos?- :name "Agent Test Dashboard"- :collection_id nil- :description nil- :dashcard_ids []}+ (testing "Creates an empty dashboard, defaulting to the caller's personal collection"+ (let [personal-id (:id (collection/user->personal-collection (mt/user->id :rasta)))+ personal-name (collection/user->personal-collection-name (mt/user->id :rasta) :user)+ resp (mt/user-http-request :rasta :post 200 "agent/v1/dashboard"+ {:name "Agent Test Dashboard"})]+ (is (=? {:id pos?+ :name "Agent Test Dashboard"+ :collection_id personal-id+ :collection_path personal-name+ :description nil+ :dashcard_ids []}resp))(t2/delete! :model/Dashboard :id (:id resp))))(testing "Creates a dashboard with questions"@@ -543,7 +593,9 @@(let [resp (mt/user-http-request :rasta :post 200 "agent/v1/dashboard"{:name "Collection Dashboard":collection_id coll-id})]- (is (= coll-id (:collection_id resp)))+ (is (=? {:collection_id coll-id+ :collection_path "Our analytics / Agent Dashboard Collection"}+ resp))(t2/delete! :model/Dashboard :id (:id resp)))))(testing "Returns 404 when a question_id does not exist"(mt/user-http-request :rasta :post 404 "agent/v1/dashboard"@@ -621,7 +673,9 @@:display :table}](let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/question/" card-id){:collection_id dest-coll-id})]- (is (= dest-coll-id (:collection_id resp))))+ (is (=? {:collection_id dest-coll-id+ :collection_path "Our analytics / Agent Move Dest"}+ resp)))(is (= dest-coll-id (t2/select-one-fn :collection_id :model/Card :id card-id))))))(deftest update-question-archive-test@@ -777,7 +831,9 @@:dashboard_id dash-id}](let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id){:collection_id dest-coll-id})]- (is (= dest-coll-id (:collection_id resp))))+ (is (=? {:collection_id dest-coll-id+ :collection_path "Our analytics / Agent Dash Dest"}+ resp)))(is (= dest-coll-id (t2/select-one-fn :collection_id :model/Dashboard :id dash-id)));; cards on the dashboard should follow(is (= dest-coll-id (t2/select-one-fn :collection_id :model/Card :id card-id)))))diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex 61db9a8967a..89a91ddc692 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -5,6 +5,7 @@[clojure.walk :as walk][metabase.agent-api.settings :as agent-api.settings][metabase.api.macros.scope :as scope]+ [metabase.collections.models.collection :as collection][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.mcp.api :as mcp.api]@@ -704,6 +705,10 @@_ (reset! question-id (:id question-data))_ (is (= (format "https://stats.metabase.test/question/%d" @question-id)(:url question-data)))+ ;; No collection_id given → defaults to the caller's personal collection;+ ;; collection_path must survive MCP forwarding.+ _ (is (= (collection/user->personal-collection-name (mt/user->id :crowberto) :user)+ (:collection_path question-data)))_ (call-tool session-id "update_question"{:id (:id question-data):description "Smoke updated description"})