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
Add endpoint for execution of saved questions (#76720)
lbrdnk5c475f1d0678
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex f419c849ad8..8669b5eaa64 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -27,6 +27,7 @@[metabase.metabot.util :as metabot.u][metabase.queries.core :as queries][metabase.query-permissions.core :as query-perms]+ [metabase.query-processor.card :as qp.card][metabase.query-processor.core :as qp][metabase.query-processor.middleware.permissions :as qp.perms][metabase.query-processor.streaming :as qp.streaming]@@ -980,6 +981,47 @@:description (:description updated):archived (boolean (:archived updated))}))+;;; ------------------------------------------------ Execute Question -----------------------------------------------++(defn- reject-parameterized-card!+ "Agent execution does not yet supply parameter values, so refuse to run a card that declares+ user-facing parameters or input template tags (field filters / variables). Snippet and+ card-reference template tags don't count — those need no runtime input. Returns a 400 so the+ limitation surfaces clearly rather than silently running the card with defaults."+ [card]+ (when (seq (qp.card/combined-parameters-and-template-tags card))+ (throw (ex-info (str "This question takes parameters, which agent execution does not yet "+ "support. Run it in Metabase, or save a parameterless version.")+ {:status-code 400 :card-id (:id card)}))))++(api.macros/defendpoint :post "/v1/question/:id/query"+ :- (streaming-response/streaming-response-schema ::execute-query-response)+ "Run a saved question (card) and return its results.++ Executes the query stored on the card under the caller's permissions and returns rows ++ column metadata — the same response shape as /v1/execute.++ Parameterized questions are NOT supported: if the card declares parameters or input+ template tags (field filters / variables), this returns a 400. Run it in Metabase, or+ save a parameterless version."+ {:scope metabot/agent-question-execute+ :tool {:name "execute_question"+ :description (str "Run a saved question by id and return its rows with column metadata, "+ "row count, and execution time. Use this to get the current results of "+ "an existing saved question. Does NOT support parameterized questions — "+ "if the question takes parameters or template-tag input, this returns an "+ "error.")+ :annotations {:read-only? true :idempotent? true}}}+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]+ _query-params+ _body]+ (let [card (api/check-404 (t2/select-one :model/Card id))]+ (reject-parameterized-card! card)+ (qp.card/process-query-for-card+ card :api+ :context :question+ :middleware {:process-viz-settings? false})))+;;; ------------------------------------------------ Create Dashboard -----------------------------------------------(mr/def ::create-dashboard-requestdiff --git a/src/metabase/mcp/README.md b/src/metabase/mcp/README.mdindex 42b857474dc..7ad69c03126 100644--- a/src/metabase/mcp/README.md+++ b/src/metabase/mcp/README.md@@ -63,6 +63,7 @@ Access tokens are scoped to limit what tools a client can use:| `agent:sql:execute` | `execute_sql` || `agent:question:create` | `create_question` || `agent:question:update` | `update_question` (also covers "move card to collection") |+| `agent:question:execute` | `execute_question` || `agent:dashboard:create` | `create_dashboard` || `agent:dashboard:update` | `update_dashboard` || `agent:collection:create` | `create_collection` |@@ -97,6 +98,7 @@ The MCP server exposes these tools, dynamically generated from the Agent API end| `query` | Query a table or metric directly. Supports pagination via continuation tokens. || `execute_query` | Execute a previously constructed query and return results with column metadata. || `execute_sql` | Execute a raw SQL query against a database. Requires the user to have native-query permission on the target database. Can be disabled instance-wide via the `mcp-execute-sql-enabled` setting. |+| `execute_question` | Run a saved question by id and return its rows + column metadata. Runs under the caller's permissions. Parameterized questions are not supported (returns an error). |### Writediff --git a/src/metabase/metabot/core.clj b/src/metabase/metabot/core.cljindex 523d6eba7b6..8eb57f5c7fd 100644--- a/src/metabase/metabot/core.clj+++ b/src/metabase/metabot/core.clj@@ -19,6 +19,7 @@agent-query-constructagent-query-executeagent-question-create+ agent-question-executeagent-question-updateagent-resource-readagent-searchdiff --git a/src/metabase/metabot/scope.clj b/src/metabase/metabot/scope.cljindex 9a71f7b6521..19a0c10e0bd 100644--- a/src/metabase/metabot/scope.clj+++ b/src/metabase/metabot/scope.clj@@ -41,6 +41,8 @@(deferred-tru "Create saved questions"))(api-scope/defscope agent-question-update "agent:question:update"(deferred-tru "Update saved questions"))+(api-scope/defscope agent-question-execute "agent:question:execute"+ (deferred-tru "Run saved questions"));; Transforms(api-scope/defscope agent-transforms-read "agent:transforms:read"diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex ff09b8ad620..9b1071a7030 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -36,6 +36,13 @@(lib.metadata/table (mt/metadata-provider) (mt/id :orders)))(lib/aggregate (lib/count))))+(defn- orders-limit-query+ "A simple unaggregated orders query with a row limit, built via lib."+ [n]+ (let [mp (mt/metadata-provider)]+ (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))+ (lib/limit n))))+;;; ------------------------------------------------- Session Auth Tests ------------------------------------------------(deftest agent-api-session-token-auth-test@@ -681,6 +688,48 @@{:name "Should Not Save Native":query (:query construct-resp)})))))+;;; ----------------------------------------------- Execute Question ------------------------------------------------++(deftest execute-question-test+ (testing "Runs a saved question and returns rows + column metadata"+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (orders-limit-query 5)}]+ ;; Streaming response returns 202 (accepted) like the other execute endpoints.+ (let [resp (mt/user-http-request :crowberto :post 202 (format "agent/v1/question/%d/query" card-id))]+ (is (=? {:status "completed"+ :row_count 5+ :data {:cols (fn [cols] (and (seq cols) (every? :name cols) (every? :base_type cols)))+ :rows (fn [rows] (= 5 (count rows)))}}+ resp)))))+ (testing "Returns 404 for a non-existent card"+ (mt/user-http-request :crowberto :post 404+ (format "agent/v1/question/%d/query" Integer/MAX_VALUE)))+ (testing "Returns 403 when the caller lacks read permission on the card"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {coll-id :id} {:name "No-Read Coll"}+ :model/Card {card-id :id} {:collection_id coll-id+ :dataset_query (orders-limit-query 5)}]+ (mt/user-http-request :rasta :post 403+ (format "agent/v1/question/%d/query" card-id))))))++(deftest execute-question-rejects-parameterized-test+ (testing "Refuses a card with a native template-tag variable (400)"+ (mt/with-temp [:model/Card {card-id :id}+ {:dataset_query {:database (mt/id)+ :type :native+ :native {:query "SELECT {{n}} AS n"+ :template-tags {:n {:id "n" :name "n"+ :display-name "N" :type :number}}}}}]+ (is (re-find #"takes parameters"+ (str (mt/user-http-request :crowberto :post 400+ (format "agent/v1/question/%d/query" card-id)))))))+ (testing "Refuses a card with a configured parameter widget (400)"+ (mt/with-temp [:model/Card {card-id :id}+ {:dataset_query (orders-limit-query 5)+ :parameters [{:id "p1" :name "Category" :slug "category" :type :category}]}]+ (is (re-find #"takes parameters"+ (str (mt/user-http-request :crowberto :post 400+ (format "agent/v1/question/%d/query" card-id))))))))+(deftest create-question-explicit-null-collection-test(testing "An explicit null collection_id saves to the root collection, not the personal default"(let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex f2320458439..90b891502d1 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -276,6 +276,7 @@"create_dashboard""create_question""execute_query"+ "execute_question""execute_sql""query""read_resource"@@ -661,7 +662,7 @@invocation check."#{"search" "construct_query" "construct_native_query" "query" "execute_query" "execute_sql""read_resource"- "create_question" "create_dashboard"+ "create_question" "execute_question" "create_dashboard""update_question" "update_dashboard" "create_collection"})(deftest tools-call-smoke-test-covers-all-agent-api-backed-tools-test@@ -724,6 +725,8 @@_ (call-tool session-id "update_question"{:id (:id question-data):description "Smoke updated description"})+ _ (call-tool session-id "execute_question"+ {:id (:id question-data)})dash-data (call-tool session-id "create_dashboard"{:name "Smoke Dashboard"})_ (reset! dash-id (:id dash-data))