Skip to content

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

Add create_question and create_dashboard MCP tools (#72742)

bryan66118921ecc9
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index cdb041d610b..07eafd11983 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -160,15 +160,21 @@
:uses #{agent-lib
api
auth-identity
+ dashboards
+ events
lib
llm
metabot
+ queries
query-processor
request
server
settings
util}
- :model-imports #{:model/User}}
+ :model-imports #{:model/Card
+ :model/Dashboard
+ :model/DashboardCard
+ :model/User}}
agent-lib
{:team "Metabot"
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index 0dbd0e06ed0..4473d70fa1c 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -10,6 +10,8 @@
[metabase.api.macros.scope :as scope]
[metabase.api.routes.common :as api.routes.common]
[metabase.auth-identity.core :as auth-identity]
+ [metabase.dashboards.autoplace :as autoplace]
+ [metabase.events.core :as events]
[metabase.lib.core :as lib]
[metabase.lib.schema.id :as lib.schema.id]
[metabase.metabot.core :as metabot]
@@ -18,6 +20,7 @@
[metabase.metabot.tools.field-stats :as field-stats]
[metabase.metabot.tools.search :as metabot-search]
[metabase.metabot.util :as metabot.u]
+ [metabase.queries.core :as queries]
[metabase.query-processor.core :as qp]
[metabase.query-processor.streaming :as qp.streaming]
[metabase.request.core :as request]
@@ -602,6 +605,118 @@
(qp.streaming/streaming-response [rff :api]
(qp/process-query (prepare-combined-query query) rff))))
+;;; ------------------------------------------------- Create Question ------------------------------------------------
+
+(mr/def ::create-question-request
+ [:map
+ [:name ms/NonBlankString]
+ [:query ms/NonBlankString]
+ [:display {:optional true} [:maybe :string]]
+ [:description {:optional true} [:maybe :string]]
+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]
+ [:visualization_settings {:optional true} [:maybe :map]]])
+
+(mr/def ::create-question-response
+ [:map
+ [:id ms/PositiveInt]
+ [:name ms/NonBlankString]
+ [:display :string]
+ [:collection_id [:maybe ms/PositiveInt]]
+ [: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 should be a base64-encoded string returned by construct_query.
+ Optionally specify display type, description, collection, and visualization settings."
+ {:scope metabot/agent-question-create
+ :tool {:name "create_question"
+ :description (str "Save a query as a named question in Metabase. "
+ "Pass the base64 query string from construct_query. "
+ "Optionally set display type (table, bar, line, pie, etc.), "
+ "description, and target collection.")}}
+ [_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)
+ card (queries/create-card!
+ {:name question-name
+ :dataset_query dataset-query
+ :display (keyword (or display "table"))
+ :description description
+ :collection_id collection_id
+ :visualization_settings (or visualization_settings {})}
+ {:id api/*current-user-id*})]
+ {:id (:id card)
+ :name (:name card)
+ :display (name (:display card))
+ :collection_id (:collection_id card)
+ :description (:description card)}))
+
+;;; ------------------------------------------------ Create Dashboard -----------------------------------------------
+
+(mr/def ::create-dashboard-request
+ [:map
+ [:name ms/NonBlankString]
+ [:description {:optional true} [:maybe :string]]
+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]
+ [:question_ids {:optional true} [:maybe [:sequential ms/PositiveInt]]]])
+
+(mr/def ::create-dashboard-response
+ [:map
+ [:id ms/PositiveInt]
+ [:name ms/NonBlankString]
+ [:collection_id [:maybe ms/PositiveInt]]
+ [: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."
+ {: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.")}}
+ [_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)
+ :collection_id (:collection_id dash)
+ :description (:description dash)
+ :dashcard_ids (mapv :id (t2/select :model/DashboardCard :dashboard_id (:id dash)))}))
+
;;; ------------------------------------------------- Authentication -------------------------------------------------
;;
;; The Agent API supports two authentication modes:
diff --git a/src/metabase/metabot/core.clj b/src/metabase/metabot/core.clj
index 537b3774c0e..85ecb871bdd 100644
--- a/src/metabase/metabot/core.clj
+++ b/src/metabase/metabot/core.clj
@@ -12,7 +12,9 @@
metabase-provider?
provider-and-model->provider]
[metabase.metabot.scope
+ agent-dashboard-create
agent-metric-read
+ agent-question-create
agent-query-construct
agent-query-execute
agent-search
diff --git a/src/metabase/metabot/scope.clj b/src/metabase/metabot/scope.clj
index 74f256ca2f8..b28df573149 100644
--- a/src/metabase/metabot/scope.clj
+++ b/src/metabase/metabot/scope.clj
@@ -34,6 +34,10 @@
(api-scope/defscope agent-query-execute "agent:query:execute"
(deferred-tru "Execute queries"))
+;; Question (saved cards via Agent API)
+(api-scope/defscope agent-question-create "agent:question:create"
+ (deferred-tru "Create saved questions"))
+
;; Transforms
(api-scope/defscope agent-transforms-read "agent:transforms:read"
(deferred-tru "View transforms"))
@@ -143,7 +147,7 @@
"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-nlq #{"agent:notebook:*" "agent:query:*" "agent:table:*" "agent:metric:*" "agent:question:*"}
:permission/metabot-other-tools #{"agent:viz:*" "agent:dashboard:*" "agent:document:*" "agent:alert:*"}})
(def always-granted-scopes
diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.clj
index 497e9f9e749..397e477485e 100644
--- a/test/metabase/agent_api/api_test.clj
+++ b/test/metabase/agent_api/api_test.clj
@@ -488,3 +488,92 @@
:total_count 1}
(mt/user-http-request :rasta :post 200 "agent/v1/search"
{:term_queries ["AgentSearchTestMetric"]}))))))))
+
+;;; ------------------------------------------------ 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"
+ {:source {:type "table" :id (mt/id :orders)}
+ :operations [["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}
+ create-resp))
+ (is (t2/exists? :model/Card :id (:id create-resp)))
+ (t2/delete! :model/Card :id (:id create-resp))))
+
+ (testing "Creates a question with optional fields"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Agent Question Collection"}]
+ (let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
+ {:source {:type "table" :id (mt/id :orders)}
+ :operations [["limit" 10]]})
+ create-resp (mt/user-http-request :rasta :post 200 "agent/v1/question"
+ {:name "Agent Question With Options"
+ :query (:query construct-resp)
+ :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"}
+ 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 []}
+ resp))
+ (t2/delete! :model/Dashboard :id (:id resp))))
+
+ (testing "Creates a dashboard with questions"
+ (mt/with-temp [:model/Card {card1-id :id} {:name "DashQ1"
+ :dataset_query (orders-count-query)
+ :display :table}
+ :model/Card {card2-id :id} {:name "DashQ2"
+ :dataset_query (orders-count-query)
+ :display :bar}]
+ (let [resp (mt/user-http-request :rasta :post 200 "agent/v1/dashboard"
+ {:name "Dashboard With Questions"
+ :description "Test dashboard"
+ :question_ids [card1-id card2-id]})]
+ (is (=? {:id pos?
+ :name "Dashboard With Questions"
+ :description "Test dashboard"
+ :dashcard_ids #(= 2 (count %))}
+ resp))
+ ;; Verify dashcards reference the correct cards and have valid positions
+ (let [dashcards (t2/select :model/DashboardCard :dashboard_id (:id resp))]
+ (is (= #{card1-id card2-id} (set (map :card_id dashcards))))
+ (is (every? #(and (nat-int? (:col %)) (nat-int? (:row %))
+ (pos? (:size_x %)) (pos? (:size_y %)))
+ dashcards)))
+ (t2/delete! :model/Dashboard :id (:id resp)))))
+
+ (testing "Creates a dashboard in a specific collection"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Agent Dashboard Collection"}]
+ (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)))
+ (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"
+ {:name "Bad Dashboard"
+ :question_ids [999999]})))
diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.clj
index f30c5f94879..80e62c05800 100644
--- a/test/metabase/mcp/api_test.clj
+++ b/test/metabase/mcp/api_test.clj
@@ -168,7 +168,7 @@
(is (= 200 (:status post-response))))))
(deftest tools-list-test
- (testing "tools/list returns the 8 agent tools"
+ (testing "tools/list returns the 10 agent tools"
(let [[session-id _] (initialize!)
response (mcp-request (jsonrpc-request "tools/list")
{"mcp-session-id" session-id})
@@ -176,7 +176,8 @@
(is (= 200 (:status response)))
(is (pos? (count tools)))
(is (= #{"search" "get_table" "get_metric" "get_table_field_values"
- "get_metric_field_values" "construct_query" "execute_query" "query"}
+ "get_metric_field_values" "construct_query" "execute_query" "query"
+ "create_question" "create_dashboard"}
(set (map :name tools))))
(testing "each tool has a description and inputSchema"
(doseq [tool tools]
@@ -493,7 +494,7 @@
(deftest tools-list-scope-filtering-test
(testing "tools/list with unrestricted scopes returns all tools"
(let [tools (mcp.tools/list-tools #{::scope/unrestricted})]
- (is (= 8 (count tools)))))
+ (is (= 10 (count tools)))))
(testing "tools/list with specific scope only returns matching tools"
(let [tools (mcp.tools/list-tools #{"agent:search"})
@@ -506,11 +507,11 @@
(testing "tools/list with wildcard scope matches all agent tools"
(let [tools (mcp.tools/list-tools #{"agent:*"})]
- (is (= 8 (count tools)))))
+ (is (= 10 (count tools)))))
(testing "tools/list with nil scopes returns all tools"
(let [tools (mcp.tools/list-tools nil)]
- (is (= 8 (count tools)))))
+ (is (= 10 (count tools)))))
(testing "tools/list with empty scopes does not return all tools"
(let [tools (mcp.tools/list-tools #{})]