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
MCP: read_resource, write tools, execute_sql (#74458)
bryan29d703e9d264
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 3d9f579643d..a23c5895221 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -160,12 +160,15 @@metabase.agent-api.init}:uses #{apiauth-identity+ collectionsdashboardseventslib+ lib-bellmmetabotqueries+ query-permissionsquery-processorrequestserverdiff --git a/.gitignore b/.gitignoreindex 572e68c556f..90da23ba921 100644--- a/.gitignore+++ b/.gitignore@@ -188,3 +188,4 @@ __pycache__/.claude/worktrees.claude/scheduled_tasks.lock.playwright-mcp+.ci_reports/diff --git a/docs/ai/mcp.md b/docs/ai/mcp.mdindex 682b27efde6..6a3b6da84ad 100644--- a/docs/ai/mcp.md+++ b/docs/ai/mcp.md@@ -96,16 +96,25 @@ You don't need to have an [AI provider](settings.md#choose-ai-provider) configurSome clients (like Claude Desktop) will ask you to approve each tool the first time it's used. The MCP server builds on Metabase's [Agent API](./agent-api.md), and exposes the following tools. If you're building a custom integration and need full control, use the [Agent API](./agent-api.md) directly instead.-- **search**: Find tables and metrics using keyword or natural language search.-- **get_table**: Get details about a table, including its fields, related tables, and metrics.-- **get_table_field_values**: Get sample values and statistics for a field in a table.-- **get_metric**: Get details about a metric, including its queryable dimensions.-- **get_metric_field_values**: Get sample values and statistics for a field in a metric.-- **construct_query**: Construct a query against a table or metric. Returns an opaque query string that can be executed with `execute_query`.-- **execute_query**: Execute a previously constructed query and return the results with column metadata, row count, and execution time.+### Discovery and reading++- **search**: Find tables, metrics, cards, dashboards, and collections using keyword or natural language search.+- **read_resource**: Read one or more Metabase entities by `metabase://` URI. Covers database / schema / table / collection / card / dashboard / metric / transform navigation in a single tool. Up to 5 URIs per call.++### Query construction and execution++- **construct_query**: Construct a query against a table or metric. Returns an opaque query handle that can be passed to `execute_query`.- **query**: Query a table or metric and return results.-- **create_question**: Create questions.-- **create_dashboard**: Create dashboards.+- **execute_query**: Execute a previously constructed query and return the results with column metadata, row count, and execution time.+- **execute_sql**: Execute a raw SQL query against a database. Requires native-query permission on the target database. An admin can disable this tool instance-wide via the `mcp-execute-sql-enabled` setting.++### Writing++- **create_question**: Save a query as a named question (card).+- **update_question**: Update a saved question. Setting `collection_id` moves the card to another collection.+- **create_dashboard**: Create a new dashboard, optionally populated with saved questions.+- **update_dashboard**: Update a dashboard's metadata (name, description, collection, archived).+- **create_collection**: Create a new collection, optionally nested under a parent collection.## Use the MCP server with file-based developmentdiff --git a/mage/src/mage/modules.clj b/mage/src/mage/modules.cljindex 22399ef2dab..bed99f1bfb8 100644--- a/mage/src/mage/modules.clj+++ b/mage/src/mage/modules.clj@@ -88,7 +88,8 @@(def driver-affecting-overrides"These modules affect drivers when computing, but we want to override and not consider them to affect drivers."- '#{analytics+ '#{agent-api+ analyticsanalytics-interfaceapiapi-scope@@ -188,6 +189,7 @@(c/green "Driver tests " (c/bold "CAN be skipped") "")))))(defn cli-print-affected-modules+ "CLI entry point: print modules affected by changes since `git-ref`, plus driver-test guidance."[[git-ref, :as _command-line-args]](let [deps (dependencies)updated (updated-modules git-ref)@@ -337,10 +339,14 @@#{}(into #{} (map str/trim) (str/split labels-str #","))))-(defn break-quarantine-label [driver]+(defn break-quarantine-label+ "PR label string that forces driver tests for `driver` to run even when otherwise quarantined."+ [driver](str "break-quarantine-" (name driver)))-(defn run-driver-label [driver]+(defn run-driver-label+ "PR label string that opts `driver`'s test job into a given CI run."+ [driver](str "ci:run-" (name driver)))(defn- driver-decision@@ -477,7 +483,6 @@(not (contains? (:pr-labels ctx)(break-quarantine-label driver))))))all-drivers)]-(if github-output-only?;; In github-output-only mode, print just the key=value lines (no colors)(do@@ -485,7 +490,6 @@(println (str (name driver) "-should-run=" should-run)))(doseq [driver quarantined-with-changes](println (str (name driver) "-quarantine-conflict=true"))))-(do;; Print module analysis summary(println "")@@ -495,7 +499,6 @@(println "Important file changed:" (boolean important-file-changed?))(println "Drivers with file changes:" (pr-str particular-driver-changed?))(println "")-;; Print human-readable decision summary(println "=== Driver Decisions ===")(doseq [{:keys [driver should-run reason]} decisions]@@ -504,7 +507,6 @@(if should-run (c/green "RUN ") (c/yellow "SKIP"))reason)))(println "")-;; Print GITHUB_OUTPUT preview with colors(let [{drivers-to-run true drivers-to-skip false} (group-by :should-run decisions)](println (c/green (str "\n=== Drivers to Run (" (count drivers-to-run) ") ===")))@@ -513,7 +515,6 @@(println (c/yellow (str "\n=== Drivers to Skip (" (count drivers-to-skip) ") ===")))(doseq [{:keys [driver]} drivers-to-skip](println (str (name driver) "-should-run=false"))))-;; Output quarantine conflict warnings with colors(when (seq quarantined-with-changes)(println "")@@ -522,7 +523,6 @@(doseq [driver quarantined-with-changes](println (c/red (str " • " (name driver) " - add label '" (break-quarantine-label driver) "' to run tests")))(println (str (name driver) "-quarantine-conflict=true"))))))-(u/exit 0)))(defn -maindiff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex c2f4c56187d..14bebbbaaa7 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -3,26 +3,31 @@Endpoints are versioned (e.g., /v1/search) and use standard HTTP semantics."(:require[clojure.string :as str]+ [metabase.agent-api.settings :as agent-api.settings][metabase.agent-api.validation :as agent-api.validation][metabase.api.common :as api][metabase.api.macros :as api.macros][metabase.api.macros.scope :as scope][metabase.api.routes.common :as api.routes.common][metabase.auth-identity.core :as auth-identity]+ [metabase.collections.core :as collections]+ [metabase.collections.models.collection :as collection][metabase.dashboards.autoplace :as autoplace]+ [metabase.dashboards.models.dashboard :as dashboard][metabase.events.core :as events]+ [metabase.lib-be.core :as lib-be][metabase.lib.core :as lib]- [metabase.lib.schema.id :as lib.schema.id][metabase.metabot.config :as metabot.config][metabase.metabot.core :as metabot][metabase.metabot.feedback :as metabot.feedback][metabase.metabot.tools.construct :as metabot-construct]- [metabase.metabot.tools.entity-details :as entity-details]- [metabase.metabot.tools.field-stats :as field-stats]+ [metabase.metabot.tools.resources :as metabot-resources][metabase.metabot.tools.search :as metabot-search][metabase.metabot.util :as metabot.u][metabase.queries.core :as queries]+ [metabase.query-permissions.core :as query-perms][metabase.query-processor.core :as qp]+ [metabase.query-processor.middleware.permissions :as qp.perms][metabase.query-processor.streaming :as qp.streaming][metabase.request.core :as request][metabase.server.streaming-response :as streaming-response]@@ -35,10 +40,6 @@;;; --------------------------------------------------- Defaults -------------------------------------------------------(def ^:private ^:const default-field-values-limit- "Default number of field values to return when no limit is specified."- 30)-(def ^:private ^:const default-query-row-limit"Default row cap when :limit is omitted from a table query request."200)@@ -55,15 +56,6 @@;;; ---------------------------------------------------- Helpers -------------------------------------------------------(defn- check-tool-result- "Extract :structured-output from a tool result, or throw with the appropriate HTTP status code.- Tool functions return {:structured-output ...} on success,- {:output \"error\" :status-code 4xx/5xx} on failure.- Defaults to 404 if no status-code is provided for backwards compatibility."- [{:keys [structured-output output status-code]}]- (or structured-output- (api/check false [(or status-code 404) (or output "Not found.")])))-(defn submit-mcp-visualization-feedback!"Submit MCP Apps visualization feedback to Harbormaster.@@ -83,129 +75,6 @@;; - Use :encode/api transformers to convert kebab-case data from internal functions;; - Convert keyword enum values (like :table, :metric) to strings for JSON-(mr/def ::field-type- "A data type for a field derived from Metabase's type hierarchy."- [:enum :boolean :date :datetime :time :number :string])--(mr/def ::field-id- "Field id as accepted by agent_api endpoints — either a real app-DB field id (positive integer)- or a string alias for expression/aggregation columns."- [:or ::lib.schema.id/field :string])--(mr/def ::field- "A field from a table or metric. field_id is the real database field ID (integer) for concrete fields,- or a string alias for expression/aggregation columns."- [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}- [:field_id ::field-id]- [:name :string]- [:display_name :string]- [:type {:optional true} [:maybe ::field-type]]- [:description {:optional true} [:maybe :string]]- [:base_type {:optional true} [:maybe :string]]- [:effective_type {:optional true} [:maybe :string]]- [:semantic_type {:optional true} [:maybe :string]]- [:database_type {:optional true} [:maybe :string]]- [:coercion_strategy {:optional true} [:maybe :string]]- [:field_values {:optional true} [:maybe [:sequential :any]]]])--(mr/def ::entity-type- "The type of queryable entity."- [:enum :table :metric])--(mr/def ::metric-summary- "Summary of a metric associated with a table. Includes the field_id of the default time dimension for temporal breakouts."- [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:type [:= :metric]]- [:name :string]- [:description {:optional true} [:maybe :string]]- [:default_time_dimension_field_id {:optional true} [:maybe ::field-id]]])--(mr/def ::segment- "A predefined filter condition that can be applied to queries via the segment_id in filters."- [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:name :string]- [:display_name {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]])--(mr/def ::measure- "A reusable aggregation expression associated with a table. Reference via measure_id in the aggregations array."- [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:name :string]- [:display_name {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]])--(mr/def ::related-table- "A table related to the queried entity via foreign key. The related_by field indicates the FK field name."- [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:type [:= :table]]- [:name :string]- [:display_name {:optional true} [:maybe :string]]- [:database_id {:optional true} [:maybe :int]]- [:database_engine {:optional true} [:maybe :string]]- [:database_schema {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:fields {:optional true} [:maybe [:sequential ::field]]]- [:related_by {:optional true} [:maybe :string]]])--(mr/def ::table- "Full details of a table including its fields, related tables, metrics, and segments."- [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:type ::entity-type]- [:name :string]- [:display_name :string]- [:database_id :int]- [:database_engine :string]- [:database_schema {:optional true} [:maybe :string]]- [:description {:optional true} [:maybe :string]]- [:fields [:sequential ::field]]- [:related_tables {:optional true} [:maybe [:sequential ::related-table]]]- [:metrics {:optional true} [:maybe [:sequential ::metric-summary]]]- [:measures {:optional true} [:maybe [:sequential ::measure]]]- [:segments {:optional true} [:maybe [:sequential ::segment]]]])--(mr/def ::metric- "A metric with its queryable dimensions and segments. The default_time_dimension_field_id is the field_id of the recommended time dimension for temporal breakouts."- [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}- [:id :int]- [:type [:= :metric]]- [:name :string]- [:description {:optional true} [:maybe :string]]- [:default_time_dimension_field_id {:optional true} [:maybe ::field-id]]- [:verified {:optional true} [:maybe :boolean]]- [:queryable_dimensions {:optional true} [:maybe [:sequential ::field]]]- [:segments {:optional true} [:maybe [:sequential ::segment]]]])--(mr/def ::statistics- "Statistical summary of a field's values computed during database sync. Includes counts, percentages, numeric summaries (min/max/avg/quartiles/sd), and date ranges."- [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}- [:distinct_count {:optional true} [:maybe :int]]- [:percent_null {:optional true} [:maybe number?]]- [:min {:optional true} [:maybe number?]]- [:max {:optional true} [:maybe number?]]- [:avg {:optional true} [:maybe number?]]- [:q1 {:optional true} [:maybe number?]]- [:q3 {:optional true} [:maybe number?]]- [:sd {:optional true} [:maybe number?]]- [:percent_json {:optional true} [:maybe number?]]- [:percent_url {:optional true} [:maybe number?]]- [:percent_email {:optional true} [:maybe number?]]- [:percent_state {:optional true} [:maybe number?]]- [:average_length {:optional true} [:maybe number?]]- [:earliest {:optional true} [:maybe :string]]- [:latest {:optional true} [:maybe :string]]])--(mr/def ::field-values- "Statistics and sample values for a specific field."- [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}- [:field_id {:optional true} [:maybe ::field-id]]- [:statistics {:optional true} [:maybe ::statistics]]- [:values {:optional true} [:maybe [:sequential :any]]]])-(mr/def ::search-result-item"A table or metric returned from search."[:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}@@ -234,87 +103,6 @@[]{:message "pong"})-(api.macros/defendpoint :get "/v1/table/:id" :- ::table- "Get details for a table by ID."- {: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]]- {:keys [with-fields with-field-values with-related-tables with-metrics with-measures with-segments]- :or {with-fields true, with-field-values false, with-related-tables true,- with-metrics true, with-measures false, with-segments false}}- :- [:map- [:with-field-values {:optional true} [:maybe :boolean]]- [:with-fields {:optional true} [:maybe :boolean]]- [:with-related-tables {:optional true} [:maybe :boolean]]- [:with-metrics {:optional true} [:maybe :boolean]]- [:with-measures {:optional true} [:maybe :boolean]]- [:with-segments {:optional true} [:maybe :boolean]]]]- (check-tool-result- (entity-details/get-table-details- {:entity-type :table- :entity-id id- :with-fields? with-fields- :with-field-values? with-field-values- :with-related-tables? with-related-tables- :with-metrics? with-metrics- :with-measures? with-measures- :with-segments? with-segments})))--(api.macros/defendpoint :get "/v1/table/:id/field/:field-id/values" :- ::field-values- "Get statistics and sample values for a table field."- {: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- [:id ms/PositiveInt]- [:field-id {:tool/description "Field identifier in the format '<prefix><entity-id>-<field-index>', e.g. 't123-0' for a table field."}- ms/NonBlankString]]]- (check-tool-result- (field-stats/field-values- {:entity-type "table"- :entity-id id- :field-id field-id- :limit (or (request/limit) default-field-values-limit)})))--(api.macros/defendpoint :get "/v1/metric/:id" :- ::metric- "Get details for a metric by ID."- {: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]]- {:keys [with-default-temporal-breakout with-field-values with-queryable-dimensions with-segments]- :or {with-default-temporal-breakout true, with-field-values false,- with-queryable-dimensions true, with-segments false}}- :- [:map- [:with-default-temporal-breakout {:optional true} [:maybe :boolean]]- [:with-field-values {:optional true} [:maybe :boolean]]- [:with-queryable-dimensions {:optional true} [:maybe :boolean]]- [:with-segments {:optional true} [:maybe :boolean]]]]- (check-tool-result- (entity-details/get-metric-details- {:metric-id id- :with-default-temporal-breakout? with-default-temporal-breakout- :with-field-values? with-field-values- :with-queryable-dimensions? with-queryable-dimensions- :with-segments? with-segments})))--(api.macros/defendpoint :get "/v1/metric/:id/field/:field-id/values" :- ::field-values- "Get statistics and sample values for a metric field."- {: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- [:id ms/PositiveInt]- [:field-id {:tool/description "Field identifier in the format '<prefix><entity-id>-<field-index>', e.g. 'c456-2' for a metric field."}- ms/NonBlankString]]]- (check-tool-result- (field-stats/field-values- {:entity-type "metric"- :entity-id id- :field-id field-id- :limit (or (request/limit) default-field-values-limit)})))-(defn- coerce-query-list"Defensive coercion for `/v1/search`'s query arguments. Some MCP clients (notablyCodex) serialize array args through a string layer, so a caller that intended to@@ -703,16 +491,120 @@(let [query (-> encoded-queryu/decode-base64json/decode+kw)]+ ;; `/v1/execute` is gated by the `agent:query:execute` scope and is intended for MBQL.+ ;; The opaque base64 payload could carry `:type :native`, but `execute_sql` is gated by+ ;; a distinct `agent:sql:execute` scope - allowing native here would let a token with+ ;; only the broader scope run raw SQL, defeating the scope distinction. Force callers+ ;; to use `/v1/execute-sql` (correctly scoped) for native execution. Compare via the+ ;; normalized type since the decoded payload may carry the type as a string or keyword.+ (when (= :native (some-> query :type keyword))+ (throw (ex-info "Native queries are not supported on /v1/execute; use execute_sql instead."+ {:status-code 400})))(qp.streaming/streaming-response [rff :api](qp/process-query (prepare-combined-query query) rff))))+;;; --------------------------------------------------- Execute SQL --------------------------------------------------++(mr/def ::execute-sql-request+ "Request shape for /v1/execute-sql. The LLM passes a raw SQL string against a target database."+ [:map+ [:database_id ms/PositiveInt]+ [:sql ms/NonBlankString]])++(api.macros/defendpoint :post "/v1/execute-sql"+ :- (streaming-response/streaming-response-schema ::execute-query-response)+ "Execute a raw SQL query against a database. Returns rows + column metadata.++ Requires the user to have native-query permission on the target database; the QP+ middleware enforces this. The instance-level `mcp-execute-sql-enabled` setting+ must also be on (it is by default)."+ {:scope metabot/agent-sql-execute+ :tool {:name "execute_sql"+ :description (str "Execute a raw SQL query against a Metabase-connected database. "+ "Use this ONLY when MBQL via construct_query cannot express the question. "+ "User must have native-query permission on the target database. "+ "Standard userspace query limits apply.")}}+ [_route-params+ _query-params+ {:keys [database_id sql]} :- ::execute-sql-request]+ ;; Kill-switch check: refuse with 403 when the admin has disabled execute_sql.+ (when-not (agent-api.settings/mcp-execute-sql-enabled)+ (throw (ex-info "execute_sql is disabled on this instance" {:status-code 403})))+ (let [raw-query {:database database_id+ :type :native+ :native {:query sql}}]+ ;; Belt-and-suspenders: friendlier 403 from the tool layer than the QP's perms-exception.+ ;; The QP middleware (query-processor.middleware.permissions) will re-check inside process-query.+ (when-not (qp.perms/current-user-has-adhoc-native-query-perms? raw-query)+ (throw (ex-info "You do not have permission to run native queries against this database."+ {:status-code 403+ :database_id database_id})))+ ;; Run through the same userland prep the other Agent API query endpoints use, so we get+ ;; the documented row cap, QueryExecution audit row, and `{:status :failed ...}` error+ ;; shape instead of a raw 500. Review finding #1.+ (qp.streaming/streaming-response [rff :api]+ (qp/process-query (prepare-agent-query raw-query) rff))))++;;; -------------------------------------------------- Read Resource -------------------------------------------------++(mr/def ::read-resource-request+ "Request shape for /v1/read-resource. Accepts up to 5 metabase:// URIs."+ [:map+ [:uris [:sequential ms/NonBlankString]]])++(mr/def ::read-resource-item+ "One fetched resource. Either `:content` (success) or `:error` (failure) is present."+ [:map+ [:uri ms/NonBlankString]+ [:content {:optional true} [:maybe :any]]+ [:error {:optional true} [:maybe :string]]])++(mr/def ::read-resource-response+ "Response shape from /v1/read-resource. `:resources` is the per-URI result list;+ `:output` is the formatted XML string the LLM consumes."+ [:map+ [:resources [:sequential ::read-resource-item]]+ [:output :string]])++(api.macros/defendpoint :post "/v1/read-resource" :- ::read-resource-response+ "Read one or more Metabase resources via metabase:// URI patterns.++ Dispatches into the shared URI resolver in `metabase.metabot.tools.resources`,+ which validates URIs, fetches entities with per-URI permission checks, and+ returns a map of `{:resources ... :output ...}`. Up to 5 URIs per call."+ {:scope metabot/agent-resource-read+ :tool {:name "read_resource"+ :description (str "Read Metabase entities by metabase:// URI. "+ "Examples: metabase://databases, metabase://database/{id}/tables, "+ "metabase://collection/{id}/items, metabase://card/{id}, "+ "metabase://dashboard/{id}/items, metabase://table/{id}/fields. "+ "Up to 5 URIs per call. List endpoints cap at 25 items.")}}+ [_route-params+ _query-params+ body :- ::read-resource-request]+ (try+ (metabot-resources/read-resource body)+ (catch clojure.lang.ExceptionInfo e+ ;; The Metabot dispatcher's "too many URIs" guard throws ex-info without a+ ;; :status-code. Surface it as a 400 to the HTTP boundary rather than the+ ;; default 500.+ (throw (ex-info (ex-message e)+ (merge {:status-code 400} (ex-data e))+ e)))))+;;; ------------------------------------------------- Create Question ------------------------------------------------+(mr/def ::card-display+ "Display types accepted by Card. Validates LLM-passed values so a bogus+ value (e.g. `\"potato\"`) gets a 400 rather than persisting junk."+ [:enum "table" "bar" "line" "pie" "scatter" "area" "row" "combo" "pivot"+ "scalar" "smartscalar" "gauge" "progress" "funnel" "map" "waterfall" "sankey"])+(mr/def ::create-question-request[:map[:name ms/NonBlankString][:query ms/NonBlankString]- [:display {:optional true} [:maybe :string]]+ [:display {:optional true} [:maybe ::card-display]][:description {:optional true} [:maybe :string]][:collection_id {:optional true} [:maybe ms/PositiveInt]][:visualization_settings {:optional true} [:maybe :map]]])@@ -728,12 +620,13 @@(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.+ 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."{: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. "+ "Pass the `query_handle` returned by `construct_query`. ""Optionally set display type (table, bar, line, pie, etc.), ""description, and target collection.")}}[_route-params@@ -741,20 +634,145 @@{: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)}))+ (let [dataset-query (-> query u/decode-base64 json/decode+kw)]+ ;; 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+ ;; user cannot run, and (b) plant the card in a collection they cannot write to.+ ;; (REST also calls `check-if-card-can-be-saved`, which only fires for `card-type :metric`;+ ;; this endpoint always creates a question, so we omit it.)+ ;;+ ;; TODO (Bryan 2026-05-20): extract REST's create-card pre-check stack into a shared+ ;; `metabase.queries.*` helper so REST + agent-api can't drift. Branch review caught+ ;; this gap; the next person who adds a REST check will probably miss the agent side+ ;; again unless we dedup.+ (query-perms/check-run-permissions-for-query dataset-query)+ (api/create-check :model/Card {:collection_id collection_id})+ (let [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)})))++;;; ------------------------------------------------- Update Question ------------------------------------------------++(mr/def ::update-question-request+ "Patch shape for `update_question`. Every field is optional; only the fields the caller+ passes are changed. `:query` accepts a base64-encoded MBQL string (or query_handle UUID+ resolved upstream in the MCP layer)."+ [:map+ [:name {:optional true} [:maybe ms/NonBlankString]]+ [:description {:optional true} [:maybe :string]]+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]+ [:display {:optional true} [:maybe ::card-display]]+ [:visualization_settings {:optional true} [:maybe :map]]+ [:archived {:optional true} [:maybe :boolean]]+ [:query {:optional true} [:maybe ms/NonBlankString]]])++(mr/def ::update-question-response+ "Returned by `update_question` - the fields the LLM is most likely to want to read back+ 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]])++(api.macros/defendpoint :put "/v1/question/:id" :- ::update-question-response+ "Update a saved question (card). Patch semantics - only fields that you pass are changed.++ Set `collection_id` to move the card to a different collection. Set `archived: true` to archive.+ Pass `query` (a query_handle from construct_query, or a base64 MBQL string) to replace the underlying query."+ {:scope metabot/agent-question-update+ :tool {:name "update_question"+ :description (str "Update a saved question (card). Patch semantics - only fields you pass are changed. "+ "To move a card to a different collection, set collection_id. "+ "To archive, set archived true. To replace the underlying query, pass query "+ "(a query_handle from construct_query).")}}+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]+ _query-params+ body :- ::update-question-request]+ (let [card-before-update (api/write-check :model/Card id)+ raw-updates (cond-> {}+ (contains? body :name)+ (assoc :name (:name body))++ (contains? body :description)+ (assoc :description (:description body))++ (contains? body :collection_id)+ (assoc :collection_id (:collection_id body))++ (contains? body :display)+ (assoc :display (some-> (:display body) keyword))++ (contains? body :visualization_settings)+ (assoc :visualization_settings (:visualization_settings body))++ (contains? body :archived)+ (assoc :archived (boolean (:archived body)))++ (contains? body :query)+ (assoc :dataset_query+ ;; Normalize like the REST update path so downstream+ ;; helpers (cycle detection, permission check) see the+ ;; canonical MBQL shape regardless of whether the LLM+ ;; sent legacy or MBQL 5.+ (-> (:query body)+ u/decode-base64+ json/decode+kw+ lib-be/normalize-query)))+ ;; Set :archived_directly to mirror :archived (mark as Trash if explicitly archived).+ ;; The REST endpoint runs this in `update-card!` on every update; we need it too so+ ;; LLM-archived cards behave the same as UI-archived ones.+ card-updates (api/updates-with-archived-directly card-before-update raw-updates)+ ;; A move (or archive that retargets the collection) requires write on BOTH the source+ ;; and the target collection. `api/write-check :model/Card` above only covered the source+ ;; entity. Mirror the REST endpoint's `check-allowed-to-move` gate.+ _ (collection/check-allowed-to-change-collection card-before-update card-updates)+ ;; Mirror REST's `check-allowed-to-modify-query`: swapping the dataset_query requires+ ;; data perms to run the *new* query, otherwise a user with collection write on a card+ ;; can repoint it at data they cannot query. `queries/update-card!` does NOT run this+ ;; check itself, so we have to run it before calling in.+ ;;+ ;; TODO (Bryan 2026-05-20): see matching TODO above `create_question`. Extract REST's+ ;; update-card pre-check stack so REST + agent-api can't drift; this single check is+ ;; only the most recent gap we noticed.+ _ (when (api/column-will-change? :dataset_query card-before-update card-updates)+ (query-perms/check-run-permissions-for-query (:dataset_query card-updates))+ ;; Reject cycles. `lib/check-card-overwrite` throws if the new query+ ;; references this card transitively. Mirror REST's wrapping that+ ;; promotes it to HTTP 400 instead of a 500.+ (try+ (lib/check-card-overwrite id (:dataset_query card-updates))+ (catch clojure.lang.ExceptionInfo e+ ;; Don't downgrade a more specific status if the throwing fn+ ;; ever starts setting one (e.g. a 404 for a missing card).+ (let [data (ex-data e)]+ (throw (ex-info (ex-message e)+ (assoc data :status-code (or (:status-code data) 400))))))))+ _ (queries/update-card! {:card-before-update card-before-update+ :card-updates card-updates+ :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))}));;; ------------------------------------------------ Create Dashboard -----------------------------------------------@@ -818,6 +836,257 @@:description (:description dash):dashcard_ids (mapv :id (t2/select :model/DashboardCard :dashboard_id (:id dash)))}))+;;; ------------------------------------------------- Update Dashboard -----------------------------------------------++(mr/def ::dashcard-mutation+ "One dashcard mutation. Discriminated on `:action`:+ - `add` : requires `card_id`. Auto-positioned. Optional `display_size`(\"wide\", \"tall\", or \"full\").+ - `remove` : requires `dashcard_id`.+ - `move` : requires `dashcard_id` and `position` (\"top\" or \"bottom\")."+ [:multi {:dispatch :action}+ ["add" [:map+ [:action [:= "add"]]+ [:card_id ms/PositiveInt]+ [:display_size {:optional true} [:maybe [:enum "wide" "tall" "full"]]]]]+ ["remove" [:map+ [:action [:= "remove"]]+ [:dashcard_id ms/PositiveInt]]]+ ["move" [:map+ [:action [:= "move"]]+ [:dashcard_id ms/PositiveInt]+ [:position [:enum "top" "bottom"]]]]])++(mr/def ::update-dashboard-request+ "Patch shape for `update_dashboard`. Metadata fields and an optional `dashcards` list of+ add/remove/move mutations applied in order."+ [:map+ [:name {:optional true} [:maybe ms/NonBlankString]]+ [:description {:optional true} [:maybe :string]]+ [:collection_id {:optional true} [:maybe ms/PositiveInt]]+ [:archived {:optional true} [:maybe :boolean]]+ [:dashcards {:optional true} [:maybe [:sequential ::dashcard-mutation]]]])++(mr/def ::update-dashboard-response+ "Returned by `update_dashboard`. `:dashcard_ids` is the post-mutation list of dashcard+ ids 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]]])++(defn- size-override+ "Optional explicit size from the LLM. Returns {:width :height} or nil to fall back to defaults."+ [display-size]+ (case display-size+ "wide" {:width 18 :height 6}+ "tall" {:width 9 :height 12}+ "full" {:width 24 :height 9}+ nil))++(defn- apply-dashcard-mutations!+ "Apply a sequence of LLM-friendly dashcard mutations. Returns {:added [...] :removed [...] :moved [...]}.++ Errors:+ - `card_id` that doesn't exist or the user can't read -> 404 / 403 via `api/read-check`.+ - `dashcard_id` that isn't on this dashboard -> 404 via `api/check-404`.++ Autoplace state walks the current dashcards list as we add, so each new card gets a unique slot."+ [dashboard-id mutations]+ (let [current (t2/select :model/DashboardCard :dashboard_id dashboard-id)+ state (atom {:placed (vec current)+ :added []+ :removed []+ :moved []})]+ (doseq [[mutation-index {:keys [action card_id dashcard_id display_size position] :as mutation}]+ (map-indexed vector mutations)]+ (try+ (case action+ "add"+ (let [card (api/read-check :model/Card card_id)+ display (or (:display card) :table)+ override (size-override display_size)+ position-fields (if override+ (autoplace/get-position-for-new-dashcard+ (:placed @state) (:width override) (:height override)+ autoplace/default-grid-width)+ (autoplace/get-position-for-new-dashcard+ (:placed @state) display))+ new-dashcard (first (t2/insert-returning-instances!+ :model/DashboardCard+ (merge position-fields+ {:dashboard_id dashboard-id+ :card_id card_id})))]+ (swap! state #(-> %+ (update :placed conj position-fields)+ (update :added conj new-dashcard))))++ "remove"+ (let [existing (api/check-404+ (t2/select-one :model/DashboardCard+ :id dashcard_id :dashboard_id dashboard-id))]+ (t2/delete! :model/DashboardCard :id dashcard_id)+ (swap! state #(-> %+ (update :placed (fn [cards] (vec (remove (comp #{dashcard_id} :id) cards))))+ (update :removed conj existing))))++ "move"+ (let [existing (api/check-404+ (t2/select-one :model/DashboardCard+ :id dashcard_id :dashboard_id dashboard-id))+ ;; Strip the moved card from the placed list while we recompute its position,+ ;; otherwise autoplace will treat it as still occupying its old slot.+ other-placed (vec (remove (comp #{dashcard_id} :id) (:placed @state)))+ new-pos (case position+ "top" {:row 0 :col 0+ :size_x (:size_x existing) :size_y (:size_y existing)}+ "bottom" (autoplace/get-position-for-new-dashcard+ other-placed+ (:size_x existing) (:size_y existing)+ autoplace/default-grid-width))]+ ;; "top" parks the card at row 0; everything else has to shift down by the+ ;; moved card's height or we get overlapping dashcards (review finding #2).+ (when (= position "top")+ (let [shift (:size_y existing)]+ (doseq [{:keys [id row]} other-placed]+ (t2/update! :model/DashboardCard id {:row (+ row shift)}))))+ (t2/update! :model/DashboardCard dashcard_id+ (select-keys new-pos [:row :col]))+ (swap! state #(-> %+ (assoc :placed+ (conj (if (= position "top")+ (mapv (fn [c] (update c :row + (:size_y existing)))+ other-placed)+ other-placed)+ (merge existing (select-keys new-pos [:row :col]))))+ (update :moved conj (merge existing new-pos))))))+ (catch Exception e+ ;; Re-throw with the mutation index so the LLM can tell which entry failed when+ ;; submitting a batch. The whole batch rolls back via the surrounding transaction.+ (throw (ex-info (str "Dashcard mutation #" mutation-index " (" action ") failed: "+ (ex-message e))+ (assoc (ex-data e)+ :mutation-index mutation-index+ :mutation mutation)+ e)))))+ (select-keys @state [:added :removed :moved])))++(api.macros/defendpoint :put "/v1/dashboard/:id" :- ::update-dashboard-response+ "Update a dashboard. Patch semantics - only fields you pass are changed.++ Metadata: `name`, `description`, `collection_id`, `archived`. Dashcard mutations+ are submitted under `dashcards` as a list of `{action: add|remove|move, ...}`+ entries applied in order. `add` requires `card_id`; `remove` and `move` require+ `dashcard_id`."+ {:scope metabot/agent-dashboard-update+ :tool {:name "update_dashboard"+ :description (str "Update a dashboard. Patch semantics - only fields you pass are changed. "+ "Set collection_id to move it. Set archived true to archive. "+ "Use dashcards to add, remove, or move cards: "+ "[{\"action\":\"add\",\"card_id\":42},{\"action\":\"remove\",\"dashcard_id\":101}]. "+ "Get dashcard_ids by reading metabase://dashboard/{id}/items via read_resource.")}}+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]+ _query-params+ body :- ::update-dashboard-request]+ (let [current-dash (api/write-check :model/Dashboard id)+ updates (cond-> {}+ (contains? body :name) (assoc :name (:name body))+ (contains? body :description) (assoc :description (:description body))+ (contains? body :collection_id) (assoc :collection_id (:collection_id body))+ (contains? body :archived) (assoc :archived (boolean (:archived body))))+ ;; A move requires write on BOTH source and target collection. `api/write-check :model/Dashboard`+ ;; above only covered the source entity. Mirror the REST endpoint's gate.+ _ (collection/check-allowed-to-change-collection current-dash updates)+ mutations (:dashcards body)+ result (t2/with-transaction [_conn]+ (when (seq updates)+ (dashboard/cascade-card-state-from-dashboard-update! current-dash updates)+ (t2/update! :model/Dashboard id updates)+ ;; Fire :event/collection-touch with the *target* collection id so the+ ;; activity feed records the right collection. Note: the dashboards-rest+ ;; PUT-dashboard endpoint passes the dashboard id here instead, which+ ;; appears to be a bug - the other collection-touch publishers+ ;; (collections_rest, queries_rest, collections/models/collection) all+ ;; pass the real collection id. Filed for follow-up.+ (when (contains? updates :collection_id)+ (events/publish-event! :event/collection-touch+ {:collection-id (:collection_id updates)+ :user-id api/*current-user-id*})))+ (when (seq mutations)+ (apply-dashcard-mutations! id mutations)))]+ ;; Publish dashcard events outside the transaction, matching the REST endpoint's ordering.+ (when (seq (:added result))+ (events/publish-event! :event/dashboard-add-cards+ {:object current-dash+ :user-id api/*current-user-id*+ :dashcards (:added result)}))+ (when (seq (:removed result))+ (events/publish-event! :event/dashboard-remove-cards+ {:object current-dash+ :user-id api/*current-user-id*+ :dashcards (:removed result)}))+ (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))})))++;;; ------------------------------------------------ Create Collection -----------------------------------------------++(mr/def ::create-collection-request+ "Request shape for `create_collection`. `:parent_collection_id` is named separately from+ the internal `:parent_id` field to make the LLM-facing API less ambiguous (the caller is+ saying \"put it under this parent\", not echoing back a server-set field)."+ [:map+ [:name ms/NonBlankString]+ [:description {:optional true} [:maybe :string]]+ [:parent_collection_id {:optional true} [:maybe ms/PositiveInt]]])++(mr/def ::create-collection-response+ "Returned by `create_collection`. Exposes the materialized-path `:location` so callers+ can sanity-check nesting without a follow-up read."+ [:map+ [:id ms/PositiveInt]+ [:name ms/NonBlankString]+ [:parent_id [:maybe ms/PositiveInt]]+ [:location ms/NonBlankString]+ [:description [:maybe :string]]])++(api.macros/defendpoint :post "/v1/collection" :- ::create-collection-response+ "Create a new Collection.++ Pass `parent_collection_id` to nest under another collection; omit for a root-level collection.+ The caller must have write access to the parent (or root, if no parent given)."+ {:scope metabot/agent-collection-create+ :tool {:name "create_collection"+ :description (str "Create a new collection in Metabase. "+ "Set parent_collection_id to nest under another collection; "+ "omit it for a root-level collection.")}}+ [_route-params+ _query-params+ {:keys [description parent_collection_id]+ collection-name :name}+ :- ::create-collection-request]+ ;; Delegate to collections/create-collection! so MCP-created collections behave the same as+ ;; UI/REST-created ones: namespace/type/is_remote_synced inheritance from parent, the+ ;; authority-level check, the tenant-collection validation, and both :event/collection-create+ ;; and :event/collection-touch firings all live in one place.+ (let [coll (collections/create-collection!+ (cond-> {:name collection-name}+ description (assoc :description description)+ parent_collection_id (assoc :parent_id parent_collection_id)))]+ {:id (:id coll)+ :name (:name coll)+ :parent_id parent_collection_id+ :location (:location coll)+ :description (:description coll)}))+;;; ------------------------------------------------- Authentication -------------------------------------------------;;;; The Agent API supports two authentication modes:diff --git a/src/metabase/agent_api/reference.md b/src/metabase/agent_api/reference.mdindex 425332b8f34..6306136e715 100644--- a/src/metabase/agent_api/reference.md+++ b/src/metabase/agent_api/reference.md@@ -2,7 +2,7 @@The Agent API is a REST API for building headless, agentic BI applications ontop of Metabase's semantic layer. It supports discovering tables and metrics,-inspecting their fields, constructing queries, and executing them — all scoped+inspecting their fields, constructing queries, and executing them - all scopedto the authenticated user's permissions.Base path: /api/agent@@ -13,15 +13,16 @@ Base path: /api/agent- **Metrics**: Standalone saved queries that represent pre-defined aggregations(e.g., "Total Revenue"). Metrics are stored in collections and can be usedas a data source in the API. They have a fixed aggregation, but can be- filtered and grouped by their queryable dimensions. Use /v1/metric/{id} to- inspect a metric's dimensions, and reference the metric in a representations- JSON query as `"aggregation": [["metric", {}, "<portable_entity_id>"]]` (see- the representations format reference linked from /v2/construct-query).+ filtered and grouped by their queryable dimensions. Read+ `metabase://metric/{id}/dimensions` via POST /v1/read-resource to inspect a+ metric's dimensions, and POST /v2/construct-query with a program whose+ `source` is `{"type": "metric", "id": <id>}` to query one.- **Measures**: Lightweight, reusable aggregation expressions (e.g.,`SUM(total)`) associated with a specific table. Unlike metrics, measures are- not standalone queries — they are building blocks that can be referenced in+ not standalone queries - they are building blocks that can be referenced intable queries via `["measure", id]` inside an `aggregate` operation. Discover- available measures for a table via GET /v1/table/{id}?with-measures=true.+ available measures by reading `metabase://table/{id}/fields` via+ POST /v1/read-resource.- **Segments**: Pre-defined filter conditions (e.g., "Active Users") that canbe applied to queries via `["filter", ["segment", id]]`.- **Field IDs**: Integer identifiers for database columns. These are the real@@ -44,14 +45,14 @@ Authorization: Bearer <jwt>The JWT must be signed with the shared secret configured in Metabase. Requiredclaims:-| Claim | Type | Required | Description |-|---------|--------|----------|--------------------------------------|-| iat | int | Yes | Issued-at time (Unix seconds). JWT |-| | | | must be <180 seconds old. |-| email | string | Yes | Email matching a Metabase user. The |-| | | | claim name is configurable via the |-| | | | jwt-attribute-email admin setting |-| | | | (default: "email"). |+| Claim | Type | Required | Description |+| ----- | ------ | -------- | ----------------------------------- |+| iat | int | Yes | Issued-at time (Unix seconds). JWT |+| | | | must be <180 seconds old. |+| email | string | Yes | Email matching a Metabase user. The |+| | | | claim name is configurable via the |+| | | | jwt-attribute-email admin setting |+| | | | (default: "email"). |Optional claims: first_name, last_name, groups (for group sync).@@ -100,146 +101,81 @@ Health check.Response: `{"message": "pong"}`-### GET /v1/table/{id}+### POST /v1/read-resource-Get details for a table including fields, related tables, metrics, and-segments.+Read one or more Metabase entities by `metabase://` URI. Replaces the older+per-entity GET endpoints (`/v1/table/{id}`, `/v1/metric/{id}`, the+`*_field_values` endpoints, and various GET browse endpoints) with a single+unified surface.-Query parameters (all boolean, all optional):--| Parameter | Default | Description |-|---------------------|---------|-----------------------------------------|-| with-fields | true | Include field metadata |-| with-field-values | false | Include sample values on each field |-| with-related-tables | true | Include FK-related tables |-| with-metrics | true | Include metrics defined on this table |-| with-measures | false | Include measures |-| with-segments | false | Include segments defined on this table |--Response:+Request:```json{- "type": "table",- "id": 42,- "name": "ORDERS",- "display_name": "Orders",- "database_id": 1,- "database_engine": "postgres",- "database_schema": "PUBLIC",- "description": "All customer orders",- "fields": [- {- "field_id": 301,- "name": "ID",- "display_name": "ID",- "description": "Primary key",- "base_type": "type/BigInteger",- "semantic_type": "type/PK",- "database_type": "BIGINT",- "field_values": [1, 2, 3]- },- {- "field_id": 302,- "name": "TOTAL",- "type": "number",- "description": "Order total",- "database_type": "FLOAT"- }- ],- "related_tables": [- {- "id": 43,- "type": "table",- "name": "PRODUCTS",- "display_name": "Products",- "database_id": 1,- "related_by": "PRODUCT_ID"- }- ],- "metrics": [- {- "id": 10,- "type": "metric",- "name": "Total Revenue",- "default_time_dimension_field_id": 305- }- ],- "measures": [- {"id": 5, "name": "Sum of Total", "description": "Sum of the total column"}- ],- "segments": [- {"id": 1, "name": "Active Users", "description": "Users who logged in within 30 days"}- ]+ "uris": ["metabase://table/42", "metabase://metric/10/dimensions"]}```-### GET /v1/metric/{id}+Up to 5 URIs per call. List endpoints (e.g. `metabase://databases`,+`metabase://collection/{id}/items`) cap at 25 items and signal `truncated`+plus `total` when more are available; drill into specific URIs or refine+via `/v1/search`.-Get details for a metric including its queryable dimensions.+#### URI catalog-Query parameters (all boolean, all optional):+**Navigation (top-level lists):**-| Parameter | Default | Description |-|---------------------------------|---------|---------------------------------------|-| with-default-temporal-breakout | true | Include default time dimension |-| with-field-values | false | Include sample values on dimensions |-| with-queryable-dimensions | true | Include dimensions for group_by |-| with-segments | false | Include applicable segments |+- `metabase://databases`+- `metabase://collections` (add `?tree=true` for the full hierarchy)+- `metabase://user/recent-items`-Response:+**Database drill-down:**-```json-{- "type": "metric",- "id": 10,- "name": "Total Revenue",- "description": "Sum of order totals",- "default_time_dimension_field_id": 305,- "verified": true,- "queryable_dimensions": [- {- "field_id": 305,- "name": "CREATED_AT",- "display_name": "Created At",- "base_type": "type/DateTime"- }- ],- "segments": []-}-```+- `metabase://database/{id}`+- `metabase://database/{id}/tables`+- `metabase://database/{id}/models`+- `metabase://database/{id}/schemas`+- `metabase://database/{id}/schemas/{schemaName}/tables`-### GET /v1/table/{id}/field/{field-id}/values-### GET /v1/metric/{id}/field/{field-id}/values+**Collection drill-down:**-Get statistics and sample values for a field. The `field-id` is the integer-field ID from the detail endpoints. Accepts optional `limit` query-parameter (default: 30).+- `metabase://collection/{id}` (`id` may be an integer or `"root"` / `"trash"`)+- `metabase://collection/{id}/items`+- `metabase://collection/{id}/subcollections`++**Entity drill-down:**++- `metabase://table/{id}` (`/fields`, `/fields/{field_id}`, `/derived`)+- `metabase://model/{id}` (`/fields`, `/fields/{field_id}`, `/sources`)+- `metabase://question/{id}` (`/fields`, `/fields/{field_id}`, `/sources`)+- `metabase://metric/{id}` (`/dimensions`, `/dimensions/{dimension_id}`)+- `metabase://transform/{id}` (`/sources`, `/target`)+- `metabase://dashboard/{id}` (`/items`)Response:```json{- "field_id": 302,- "statistics": {- "distinct_count": 200,- "percent_null": 0.02,- "min": 1.5,- "max": 500.0,- "avg": 75.3,- "q1": 25.0,- "q3": 120.0,- "sd": 45.2,- "earliest": "2020-01-01T00:00:00Z",- "latest": "2024-12-31T23:59:59Z"- },- "values": ["Gadget", "Widget", "Doohickey"]+ "resources": [+ {"uri": "metabase://table/42", "content": { ... }},+ {"uri": "metabase://metric/10/dimensions", "content": { ... }}+ ],+ "output": "<resources>...</resources>"}```-Statistics fields vary by field type. Numeric fields include min/max/avg/q1/q3/sd.-Date fields include earliest/latest. String fields include average_length and-percent_email/percent_url/percent_state/percent_json.+Per-URI permission checks happen inside the dispatcher: single-entity URIs+return `:error` when `mi/can-read?` denies, list endpoints silently filter+unreadable items.++`:output` is an XML-shaped string formatted for LLM consumption. Programmatic+callers should rely on the `:resources` array.++Errors:++- 400 when more than 5 URIs are provided.+- The endpoint never raises 404 for a single-URI miss; per-URI errors are+ reported inside the response under `resources[].error`.### POST /v1/search@@ -333,7 +269,7 @@ Minimal example:#### Response```json-{"query": "eyJkYXRhYmFzZSI6MSwi..."}+{ "query": "eyJkYXRhYmFzZSI6MSwi..." }```The value is a base64-encoded resolved MBQL 5 query map suitable for@@ -395,7 +331,7 @@ Response (HTTP 202, streaming):To fetch the next page:```json-{"continuation_token": "eyJxdWVyeSI6ey..."}+{ "continuation_token": "eyJxdWVyeSI6ey..." }```### POST /v1/execute@@ -404,20 +340,20 @@ Execute a query returned by /v2/construct-query.**Important: streaming response.** This endpoint streams results, so the HTTPstatus code (202) is sent before query execution completes. A 202 status does-NOT guarantee the query succeeded — you must check the `status` field in the+NOT guarantee the query succeeded - you must check the `status` field in theresponse body. If the query fails mid-execution, the response body will contain`"status": "failed"` with an error message, even though the HTTP status was 202.Request:```json-{"query": "eyJkYXRhYmFzZSI6MSwi..."}+{ "query": "eyJkYXRhYmFzZSI6MSwi..." }```Response (HTTP 202):The response body may contain additional fields beyond those documented here.-Ignore any fields not listed below — they are internal metadata and not part of+Ignore any fields not listed below - they are internal metadata and not part ofthe stable API contract.On success:@@ -427,11 +363,21 @@ On success:"status": "completed","data": {"cols": [- {"name": "CREATED_AT", "base_type": "type/DateTime", "effective_type": "type/DateTime", "display_name": "Created At"},- {"name": "sum", "base_type": "type/Float", "effective_type": "type/Float", "display_name": "Sum of Total"}+ {+ "name": "CREATED_AT",+ "base_type": "type/DateTime",+ "effective_type": "type/DateTime",+ "display_name": "Created At"+ },+ {+ "name": "sum",+ "base_type": "type/Float",+ "effective_type": "type/Float",+ "display_name": "Sum of Total"+ }],"rows": [- ["2024-01-01T00:00:00Z", 15234.50],+ ["2024-01-01T00:00:00Z", 15234.5],["2024-02-01T00:00:00Z", 18102.75]]},@@ -441,7 +387,7 @@ On success:```| Field | Description |-|--------------|-----------------------------------------------------------------|+| ------------ | --------------------------------------------------------------- || status | `"completed"` on success, `"failed"` on error || data.cols | Column metadata (name, base_type, effective_type, display_name) || data.rows | Array of row arrays, in the same order as cols |@@ -451,112 +397,206 @@ On success:On failure:```json-{"status": "failed", "error": "Query error message"}+{ "status": "failed", "error": "Query error message" }```Row limits:+- Simple queries (no aggregation): 2000 rows max- Aggregated queries: 10000 rows max+### POST /v1/execute-sql++Execute a raw SQL query against a database. Streams results in the same+format as `/v1/execute`. Use this only when MBQL via `/v2/construct-query`+cannot express the question.++Requires the caller to have native-query permission on the target database;+the QP middleware enforces this, with a friendly belt-and-suspenders check+at the tool layer. Returns 403 when the user lacks permission or when the+instance setting `mcp-execute-sql-enabled` is `false` (default `true`).++Request:++```json+{ "database_id": 1, "sql": "SELECT count(*) FROM orders" }+```++Response: identical shape to `/v1/execute`.+### POST /v1/question-Save a previously constructed query as a named question (card).+Save a previously constructed query as a named question (card). Pass the+`query_handle` returned by `/v2/construct-query` as the `query` field+(the MCP layer transparently resolves handles for clients connected via+MCP; direct REST callers may instead pass the base64 query string).Request:```json{- "name": "Q3 Revenue by Region",- "query": "eyJkYXRhYmFzZSI6MSwi...",- "display": "bar",- "description": "Sum of order totals grouped by region",+ "name": "Monthly Revenue",+ "query": "<query_handle or base64>",+ "display": "line",+ "description": "Revenue by month","collection_id": 7,"visualization_settings": {}}```-| Field | Required | Description |-|------------------------|----------|----------------------------------------------------------------------------------------------|-| name | yes | Question name |-| query | yes | Base64-encoded query string returned by /v2/construct-query |-| display | no | Visualization type (`table`, `bar`, `line`, `pie`, etc.). Defaults to `table`. |-| description | no | Free-text description |-| collection_id | no | Target collection. Omit / null to save at the user's personal-collection root. |-| visualization_settings | no | Map of viz settings |+Response:++```json+{+ "id": 42,+ "name": "Monthly Revenue",+ "display": "line",+ "collection_id": 7,+ "description": "Revenue by month"+}+```++### PUT /v1/question/{id}++Update a saved question (card). Patch semantics - only fields you pass are+changed. Subsumes "move card to collection" - setting `collection_id` moves+the card. Setting `archived: true` archives it. Passing `query` replaces the+underlying `dataset_query`.++Request:++```json+{+ "name": "Renamed Question",+ "description": "Updated description",+ "collection_id": 7,+ "display": "bar",+ "visualization_settings": {},+ "archived": false,+ "query": "<query_handle or base64>"+}+```Response:```json{"id": 42,- "name": "Q3 Revenue by Region",+ "name": "Renamed Question","display": "bar","collection_id": 7,- "description": "Sum of order totals grouped by region"+ "description": "Updated description",+ "archived": false}```### POST /v1/dashboard-Create a new dashboard, optionally populated with existing saved questions.-When `question_ids` is provided, cards are auto-placed on the grid based on-their display type.+Create a new dashboard, optionally populated with saved questions.Request:```json{- "name": "Q3 Revenue Overview",- "description": "Top-line Q3 metrics",+ "name": "Revenue Dashboard",+ "description": "...","collection_id": 7,- "question_ids": [42, 43, 44]+ "question_ids": [42, 43]}```-| Field | Required | Description |-|---------------|----------|----------------------------------------------------------------------------|-| name | yes | Dashboard name |-| description | no | Free-text description |-| collection_id | no | Target collection. Omit / null to save at the user's personal-collection root. |-| question_ids | no | Existing card IDs to add as dashcards. User must have read access to each. |+When `question_ids` is provided, cards are auto-positioned on the grid based+on each card's display type.Response:```json{- "id": 11,- "name": "Q3 Revenue Overview",+ "id": 7,+ "name": "Revenue Dashboard","collection_id": 7,- "description": "Top-line Q3 metrics",- "dashcard_ids": [101, 102, 103]+ "description": "...",+ "dashcard_ids": [101, 102]+}+```++### PUT /v1/dashboard/{id}++Update a dashboard's metadata. Patch semantics. Setting `collection_id`+moves the dashboard (and its cards). Setting `archived: true` archives the+dashboard and cascades to its cards.++Request:++```json+{+ "name": "Renamed Dashboard",+ "description": "...",+ "collection_id": 7,+ "archived": false+}+```++Response:++```json+{+ "id": 7,+ "name": "Renamed Dashboard",+ "collection_id": 7,+ "description": "...",+ "archived": false+}+```++### POST /v1/collection++Create a new collection. Optionally nested under another collection via+`parent_collection_id`.++Request:++```json+{ "name": "Marketing", "description": "...", "parent_collection_id": 1 }+```++Response:++```json+{+ "id": 12,+ "name": "Marketing",+ "parent_id": 1,+ "location": "/1/",+ "description": "..."}```## Typical workflow-1. **Search** — POST /v1/search to find relevant tables or metrics-2. **Inspect** — GET /v1/table/{id} or /v1/metric/{id} to get the column-name /- schema / portable-FK info needed to write a query-3. **Explore field values** — GET /v1/table/{id}/field/{field-id}/values if- you need to know valid filter values or field statistics-4. **Build query** — POST /v2/construct-query with a representations JSON+1. **Search** - POST /v1/search to find relevant tables, metrics, cards, or dashboards+2. **Navigate** - POST /v1/read-resource with `metabase://` URIs to drill into+ databases, schemas, tables, fields, collections, dashboards, etc.+3. **Build query** - POST /v2/construct-query with a representations JSONpayload (`{"query": <external-query-object>}`); see the`construct_notebook_query` tool prompt for the format reference-5. **Execute** — POST /v1/execute with the base64-encoded query, or use+4. **Execute** - POST /v1/execute with the base64-encoded query, or usePOST /v2/query to construct and execute in one round-trip with pagination-6. **Iterate** — Adjust the query and repeat steps 4-5-7. **Save (optional)** — POST /v1/question to persist the query as a card, and- POST /v1/dashboard to assemble saved cards into a dashboard+5. **Save (optional)** - POST /v1/question to persist the query as a saved+ question; PUT /v1/question/{id} to update one; POST /v1/dashboard to+ bundle questions into a dashboard; POST /v1/collection to create a+ collection+6. **Iterate** - Adjust the query and repeat steps 3-4## Error handling-| HTTP Status | Meaning |-|-------------|----------------------------------------------------------------------|-| 200 | Success (GET endpoints, construct-query) |-| 202 | Success (execute / query — streaming response) |-| 400 | Invalid representations query (validation, repair, or resolution failure; `:agent-error?` paths) |-| 401 | Authentication failure |-| 403 | Insufficient permissions |-| 404 | Entity not found (GET endpoints only) |+| HTTP Status | Meaning |+|-------------|----------------------------------------------------------------------------------------------------|+| 200 | Success (GET endpoints, construct-query) |+| 202 | Success (execute / query - streaming response) |+| 400 | Invalid representations query (validation, repair, or resolution failure; `:agent-error?` paths) |+| 401 | Authentication failure |+| 403 | Insufficient permissions |+| 404 | Entity not found |---diff --git a/src/metabase/agent_api/settings.clj b/src/metabase/agent_api/settings.cljindex bfab4d53d07..aa23bada2b6 100644--- a/src/metabase/agent_api/settings.clj+++ b/src/metabase/agent_api/settings.clj@@ -13,3 +13,11 @@(setting/get-value-of-type :boolean :agent-api-enabled?)):export? true:doc false)++(defsetting mcp-execute-sql-enabled+ (deferred-tru "Whether the MCP `execute_sql` tool is available. Disable to remove the tool entirely; underlying native-query permissions still apply when enabled.")+ :type :boolean+ :visibility :public+ :default true+ :export? true+ :doc false)diff --git a/src/metabase/collections/core.clj b/src/metabase/collections/core.cljindex f7783e0f80d..199002d2c5d 100644--- a/src/metabase/collections/core.clj+++ b/src/metabase/collections/core.clj@@ -1,15 +1,19 @@(ns metabase.collections.core"Main namespace for interacting with collections"(:require+ [metabase.collections.create][metabase.collections.models.collection][metabase.collections.util][potemkin :as p]))(comment+ metabase.collections.create/keep-memetabase.collections.models.collection/keep-memetabase.collections.util/keep-me)(p/import-vars+ [metabase.collections.create+ create-collection!][metabase.collections.models.collectionhas-remote-synced-collection?check-for-remote-sync-updatediff --git a/src/metabase/collections/create.clj b/src/metabase/collections/create.cljnew file mode 100644index 00000000000..0e6edfea9b8--- /dev/null+++ b/src/metabase/collections/create.clj@@ -0,0 +1,93 @@+(ns metabase.collections.create+ "Create-collection business logic, shared between the REST endpoint+ (`metabase.collections-rest.api`) and other callers like the agent API. Lives in the+ `collections` module so non-REST consumers can use it without crossing the+ module-linter's non-rest -> rest barrier."+ (:require+ [malli.util]+ [metabase.api.common :as api]+ [metabase.collections.models.collection :as collection]+ [metabase.events.core :as events]+ [metabase.premium-features.core :as premium-features :refer [defenterprise]]+ [metabase.util :as u]+ [metabase.util.i18n :refer [tru]]+ [metabase.util.malli :as mu]+ [metabase.util.malli.schema :as ms]+ [toucan2.core :as t2]))++(defn- parent-or-root+ "From a create request return either the parent collection or the root collection."+ [{collection-id :parent_id collection-namespace :namespace}]+ (if collection-id+ (t2/select-one :model/Collection :id collection-id)+ (collection/root-collection-with-ui-details collection-namespace)))++(defn- write-check-authority-level+ "Check that a superuser is creating this collection if they are setting the authority level."+ [{authority-level :authority_level :as coll}]+ (when (some? authority-level)+ ;; make sure only admin and an EE token is present to be able to create an Official token+ (premium-features/assert-has-feature :official-collections (tru "Official Collections"))+ (api/check-superuser))+ coll)++(defenterprise validate-new-tenant-collection!+ "OSS version. Throws API exceptions if the passed collection is an invalid tenant collection,+ which in OSS means 'any tenant collection.'"+ metabase-enterprise.tenants.core+ [collection]+ (when (collection/shared-tenant-collection? collection)+ (throw (ex-info "Cannot create tenant collection on OSS." {:status-code 400})))+ collection)++(def ^:private CreateCollectionArguments+ "The arguments to a create-collection call — what the public API surface accepts."+ [:map+ [:name ms/NonBlankString]+ [:description {:optional true} [:maybe ms/NonBlankString]]+ [:parent_id {:optional true} [:maybe ms/PositiveInt]]+ [:namespace {:optional true} [:maybe ms/NonBlankString]]+ [:authority_level {:optional true} [:maybe collection/AuthorityLevel]]])++(def ^:private NewCollectionArguments+ "What we use internally to actually create a collection — what `t2/insert!` needs."+ (-> CreateCollectionArguments+ (malli.util/dissoc :parent_id)+ (malli.util/assoc :location [:maybe ms/NonBlankString])+ (malli.util/assoc :namespace [:maybe [:or :keyword ms/NonBlankString]])+ (malli.util/assoc :is_remote_synced [:maybe :boolean])+ (malli.util/assoc :type [:enum "trash" "library" "library-data" "library-metrics"])+ (malli.util/optional-keys [:location :type])+ (malli.util/closed-schema)))++(mu/defn apply-defaults-to-collection :- NewCollectionArguments+ "Converts `CreateCollectionArguments` into `NewCollectionArguments` — i.e. translates what the API+ gets into what toucan needs to create a collection. Inherits `:namespace`, `:type` (excluding+ `\"trash\"`), and `:is_remote_synced` from the parent collection."+ [coll-data :- CreateCollectionArguments]+ (let [parent-coll (parent-or-root coll-data)]+ ;; `api/write-check` handles both branches - a real collection and the root sentinel+ ;; returned by `parent-or-root` when no parent_id is given.+ (api/write-check parent-coll)+ (-> (cond-> coll-data+ (and (:namespace parent-coll)+ (nil? (:namespace coll-data))) (assoc :namespace (:namespace parent-coll))+ parent-coll (assoc :location (collection/children-location parent-coll))+ (and (:type parent-coll)+ (not= (:type parent-coll) "trash")) (assoc :type (:type parent-coll)))+ (assoc :is_remote_synced (boolean (:is_remote_synced parent-coll)))+ (select-keys (malli.util/keys NewCollectionArguments)))))++(mu/defn create-collection!+ "Create a new collection. Applies parent-inheritance defaults, runs the authority-level+ superuser/feature check, runs the EE tenant-collection validation, and publishes both the+ create and touch events. The single source of truth for collection creation; REST and agent+ callers both go through here."+ [coll-data]+ (u/prog1 (t2/insert-returning-instance!+ :model/Collection+ (-> (apply-defaults-to-collection coll-data)+ write-check-authority-level+ validate-new-tenant-collection!))+ (events/publish-event! :event/collection-create {:object <> :user-id api/*current-user-id*})+ (events/publish-event! :event/collection-touch {:collection-id (:id <>) :user-id api/*current-user-id*})))diff --git a/src/metabase/collections_rest/api.clj b/src/metabase/collections_rest/api.cljindex 6a368f2a875..654f09d2c4f 100644--- a/src/metabase/collections_rest/api.clj+++ b/src/metabase/collections_rest/api.clj@@ -1391,82 +1391,11 @@;;; ----------------------------------------- Creating/Editing a Collection -------------------------------------------(defn- parent-or-root- "From a create request return either the parent collection or the root collection"- [{collection-id :parent_id collection-namespace :namespace}]- (if collection-id- (t2/select-one :model/Collection :id collection-id)- (collection/root-collection-with-ui-details collection-namespace)))--(defn- write-check-collection-or-root-collection- "Check that you're allowed to write Collection with `collection-id`; if `collection-id` is `nil`, check that you have- Root Collection perms."- [parent-coll]- (api/write-check parent-coll))--(defn- write-check-authority-level- "Check that a superuser is creating this collection if they are setting the authority level."- [{authority-level :authority_level :as coll}]- (when (some? authority-level)- ;; make sure only admin and an EE token is present to be able to create an Official token- (premium-features/assert-has-feature :official-collections (tru "Official Collections"))- (api/check-superuser))- coll)--(defenterprise validate-new-tenant-collection!- "OSS version. Throws API exceptions if the passed collection is an invalid tenant collection, which in OSS- means 'any tenant collection.'"- metabase-enterprise.tenants.core- [collection]- (when (collection/shared-tenant-collection? collection)- (throw (ex-info "Cannot create tenant collection on OSS." {:status-code 400})))- collection)--(def ^:private CreateCollectionArguments- "The arguments to the `POST /api/collection` endpoint, i.e. what the API needs to create a collection."- [:map- [:name ms/NonBlankString]- [:description {:optional true} [:maybe ms/NonBlankString]]- [:parent_id {:optional true} [:maybe ms/PositiveInt]]- [:namespace {:optional true} [:maybe ms/NonBlankString]]- [:authority_level {:optional true} [:maybe collection/AuthorityLevel]]])--(def ^:private NewCollectionArguments- "What we use internally to actually create a collection, i.e. what `t2/insert!` needs to create a collection."- (-> CreateCollectionArguments- (malli.util/dissoc :parent_id)- (malli.util/assoc :location [:maybe ms/NonBlankString])- (malli.util/assoc :namespace [:maybe [:or :keyword ms/NonBlankString]])- (malli.util/assoc :is_remote_synced [:maybe :boolean])- (malli.util/assoc :type [:enum "trash" "library" "library-data" "library-metrics"])- (malli.util/optional-keys [:location :type])- (malli.util/closed-schema)))--(mu/defn- apply-defaults-to-collection :- NewCollectionArguments- "Converts `CreateCollectionArguments` into `NewCollectionArguments` - i.e. translates what the API gets into what- toucan needs to create a collection."- [coll-data :- CreateCollectionArguments]- (let [parent-coll (parent-or-root coll-data)]- (write-check-collection-or-root-collection parent-coll)- (-> (cond-> coll-data- (and (:namespace parent-coll)- (nil? (:namespace coll-data))) (assoc :namespace (:namespace parent-coll))- parent-coll (assoc :location (collection/children-location parent-coll))- (and (:type parent-coll)- (not= (:type parent-coll) "trash")) (assoc :type (:type parent-coll)))- (assoc :is_remote_synced (boolean (:is_remote_synced parent-coll)))- (select-keys (malli.util/keys NewCollectionArguments)))))--(mu/defn create-collection!- "Create a new collection."- [coll-data]- (u/prog1 (t2/insert-returning-instance!- :model/Collection- (-> (apply-defaults-to-collection coll-data)- write-check-authority-level- validate-new-tenant-collection!))- (events/publish-event! :event/collection-create {:object <> :user-id api/*current-user-id*})- (events/publish-event! :event/collection-touch {:collection-id (:id <>) :user-id api/*current-user-id*})))+;; Create-collection business logic lives in `metabase.collections.create` so that non-REST+;; callers (notably the agent API's MCP `create_collection` tool) can use the same entry point+;; without crossing the module-linter's non-rest -> rest barrier. Re-exported through+;; `metabase.collections.core` as `create-collection!`, `apply-defaults-to-collection`,+;; `validate-new-tenant-collection!`, etc.;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to;; use our API + we will need it when we make auto-TypeScript-signature generation happen@@ -1482,7 +1411,7 @@[:parent_id {:optional true} [:maybe ms/PositiveInt]][:namespace {:optional true} [:maybe ms/NonBlankString]][:authority_level {:optional true} [:maybe collection/AuthorityLevel]]]]- (create-collection! body))+ (collections/create-collection! body))(defn- maybe-send-archived-notifications!"When a collection is archived, all of it's cards are also marked as archived, but this is down in the model layerdiff --git a/src/metabase/dashboards/models/dashboard.clj b/src/metabase/dashboards/models/dashboard.cljindex d6d751c2b8e..4125b78c7a4 100644--- a/src/metabase/dashboards/models/dashboard.clj+++ b/src/metabase/dashboards/models/dashboard.clj@@ -210,6 +210,30 @@(when-let [ids (seq internal-dashboard-questions-to-unarchive)](t2/update! :model/Card :id [:in ids] {:archived false :archived_directly false}))))+(defn cascade-card-state-from-dashboard-update!+ "Mirror dashboard-level state changes onto the dashboard's cards. Specifically:+ - Archiving the dashboard archives its (non-`archived_directly`) cards. Un-archiving restores them.+ - Moving the dashboard into a new collection moves its cards into the same collection.++ Shared between the REST `update-dashboard!` and the MCP `update_dashboard` tool so they+ don't drift. Call inside the same transaction as the dashboard update itself."+ [current-dash updates]+ (let [id (:id current-dash)]+ (when (api/column-will-change? :archived current-dash updates)+ (if (:archived updates)+ (t2/update! :model/Card+ :dashboard_id id+ :archived false+ {:archived true :archived_directly false})+ (t2/update! :model/Card+ :dashboard_id id+ :archived true+ :archived_directly false+ {:archived false})))+ (when (api/column-will-change? :collection_id current-dash updates)+ (t2/update! :model/Card :dashboard_id id+ {:collection_id (:collection_id updates)}))))+;;; +----------------------------------------------------------------------------------------------------------------+;;; | OTHER CRUD FNS |;;; +----------------------------------------------------------------------------------------------------------------+diff --git a/src/metabase/dashboards_rest/api.clj b/src/metabase/dashboards_rest/api.cljindex 2735ca3ad34..5857b728c43 100644--- a/src/metabase/dashboards_rest/api.clj+++ b/src/metabase/dashboards_rest/api.clj@@ -996,19 +996,7 @@:present #{:description :position :width :collection_id :collection_position :cache_ttl :archived_directly :embedding_type}:non-nil #{:name :parameters :caveats :points_of_interest :show_in_getting_started :enable_embedding:embedding_params :archived :auto_apply_filters}))]- (when (api/column-will-change? :archived current-dash dash-updates)- (if (:archived dash-updates)- (t2/update! :model/Card- :dashboard_id id- :archived false- {:archived true :archived_directly false})- (t2/update! :model/Card- :dashboard_id id- :archived true- :archived_directly false- {:archived false})))- (when (api/column-will-change? :collection_id current-dash dash-updates)- (t2/update! :model/Card :dashboard_id id {:collection_id (:collection_id dash-updates)}))+ (dashboard/cascade-card-state-from-dashboard-update! current-dash dash-updates)(t2/update! :model/Dashboard id updates)(when (contains? updates :collection_id)(events/publish-event! :event/collection-touch {:collection-id id :user-id api/*current-user-id*}))diff --git a/src/metabase/mcp/README.md b/src/metabase/mcp/README.mdindex 0c5019093d9..d7a42b29945 100644--- a/src/metabase/mcp/README.md+++ b/src/metabase/mcp/README.md@@ -3,8 +3,8 @@Metabase includes a built-in [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that lets AIclients connect directly to a Metabase instance. It uses the [Streamable HTTPtransport](https://modelcontextprotocol.io/specification/2025-03-26/basic/transports#streamable-http) and builds on-Metabase's [Agent API](../agent_api/) to expose tools for searching, exploring, querying, and visualizing data — all-scoped to the connecting user's permissions.+Metabase's [Agent API](../agent_api/) to expose tools for searching, navigating, querying, visualizing, and+creating/updating content - all scoped to the connecting user's permissions.## Endpoint@@ -33,7 +33,7 @@ https://{your-metabase.example.com}/api/mcp## Authentication-MCP clients authenticate via **OAuth 2.0**. Metabase runs its own embedded OAuth server — no external provider is+MCP clients authenticate via **OAuth 2.0**. Metabase runs its own embedded OAuth server - no external provider isneeded.The flow for a first-time connection:@@ -49,16 +49,19 @@ Browser-based sessions (cookie auth) are also supported and receive unrestrictedAccess tokens are scoped to limit what tools a client can use:-| Scope | Grants access to |-| ----------------------- | --------------------------------------- |-| `agent:table:read` | `get_table`, `get_table_field_values` |-| `agent:metric:read` | `get_metric`, `get_metric_field_values` |-| `agent:search` | `search` |-| `agent:query:construct` | `construct_query` |-| `agent:query` | `query` |-| `agent:query:execute` | `execute_query` |-| `agent:question:create` | `create_question` |-| `agent:dashboard:create`| `create_dashboard` |+| Scope | Grants access to |+| ------------------------- | -------------------------------------------------------------------------------------------------------------- |+| `agent:search` | `search` |+| `agent:resource:read` | `read_resource` (always granted to any authenticated caller; per-URI perm checks happen inside the dispatcher) |+| `agent:query:construct` | `construct_query` |+| `agent:query` | `query` |+| `agent:query:execute` | `execute_query` |+| `agent:sql:execute` | `execute_sql` |+| `agent:question:create` | `create_question` |+| `agent:question:update` | `update_question` (also covers "move card to collection") |+| `agent:dashboard:create` | `create_dashboard` |+| `agent:dashboard:update` | `update_dashboard` |+| `agent:collection:create` | `create_collection` |Wildcard patterns (e.g. `agent:*`) match any scope with that prefix.@@ -74,30 +77,51 @@ By default our consent screen grants access to all scopes without the opportunitThe MCP server exposes these tools, dynamically generated from the Agent API endpoint metadata:-| Tool | Description |-| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |-| `search` | Search for tables and metrics using keyword or natural language search. |-| `get_table` | Get details about a table including its fields, related tables, and metrics. |-| `get_table_field_values` | Get sample values and statistics for a field in a table. |-| `get_metric` | Get details about a metric including its queryable dimensions. |-| `get_metric_field_values` | Get sample values and statistics for a field in a metric. |-| `construct_query` | Construct a query against a table or metric. Accepts the user's original `prompt` when available. Returns an opaque `query_handle` for use with `execute_query` or `visualize_query`. |-| `execute_query` | Execute a previously constructed query and return results with column metadata. |-| `query` | Query a table or metric directly. Supports pagination via continuation tokens. |-| `create_question` | Save a constructed query as a named question (card). Takes the base64 `query` from `construct_query`, plus optional `display`, `description`, `collection_id`, `visualization_settings`. |-| `create_dashboard` | Create a dashboard, optionally populated with saved questions via `question_ids`. Cards are auto-positioned on the grid by display type. |+### Discovery + read++| Tool | Description |+| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `search` | Search for tables, metrics, cards, dashboards, and collections using keyword or natural-language queries. |+| `read_resource` | Read one or more Metabase entities by `metabase://` URI. Covers database/schema/table/collection/card/dashboard/metric/transform navigation. Up to 5 URIs per call. |++### Query construction + execution++| Tool | Description |+| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `construct_query` | Construct a query against a table or metric. Accepts the user's original `prompt` when available. Returns an opaque `query_handle` for use with `execute_query` or `visualize_query`. |+| `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. |++### Write++| Tool | Description |+| ------------------- | ----------------------------------------------------------------------------------------------------------------- |+| `create_question` | Save a query as a named question (card). Accepts a `query_handle` from `construct_query`. |+| `update_question` | Update a saved question. Patch semantics. Setting `collection_id` moves the card. Setting `archived` archives it. |+| `create_dashboard` | Create a new dashboard, optionally populated with saved questions (auto-positioned on the grid). |+| `update_dashboard` | Update a dashboard's metadata (name, description, collection, archived). |+| `create_collection` | Create a new collection. Optionally nested under a `parent_collection_id`. |Query results are limited to 200 rows per request. When more rows are available, the response includes a`continuation_token` that can be passed back to fetch the next page.+`read_resource` list responses cap at 25 items with `truncated` / `total` signals; drill into specific URIs to see+more, or refine via `search`.+## ResourcesThe server exposes MCP [resources](https://modelcontextprotocol.io/specification/2025-03-26/server/resources) soclients can fetch supplementary content by URI without inflating tool descriptions.-| Resource URI | Description |-| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |-| `metabase://docs/construct-query.md` | Format reference for `construct_query` and `query` — top-level / stage shape, field references, filter / aggregation / temporal operators, joins, expressions, multi-stage queries, worked examples, pitfalls. |+| Resource URI | Description |+| ------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |+| `metabase://docs/construct-query.md` | Program syntax for `construct_query` and `query`: sources, operations, operator forms, worked examples, pitfalls. |++The `read_resource` **tool** (above) uses a separate URI scheme to navigate Metabase entities (`metabase://card/{id}`,+`metabase://database/{id}/tables`, etc.). The two URI namespaces are independent: `metabase://docs/...` is for static+reference content fetched via MCP `resources/read`, while `metabase://table/...` and friends are entity URIs passed+to the `read_resource` tool.## Supported JSON-RPC methods@@ -118,31 +142,31 @@ Requests can be sent individually or as a JSON-RPC batch. The server responds wiThe implementation lives in these files:-- **[`api.clj`](api.clj)** — The HTTP handler. Parses JSON-RPC requests, validates authentication and session headers,+- **[`api.clj`](api.clj)** - The HTTP handler. Parses JSON-RPC requests, validates authentication and session headers,enforces origin checks (DNS rebinding protection), and dispatches to the appropriate method. Supports both JSON andSSE response formats.-- **[`tools.clj`](tools.clj)** — Tool dispatch and manifest generation. Builds the tool list from Agent API endpoint+- **[`tools.clj`](tools.clj)** - Tool dispatch and manifest generation. Builds the tool list from Agent API endpointmetadata, checks scopes, and routes tool calls through synthetic Agent API requests.-- **[`resources.clj`](resources.clj)** — MCP resource registry and handlers. Holds documentation resources (like+- **[`resources.clj`](resources.clj)** - MCP resource registry and handlers. Holds documentation resources (likethe `construct_query` reference) keyed by URI, with scope-based access control on `resources/list` and`resources/read`.-- **[`scope.clj`](scope.clj)** — Scope matching logic. Supports exact matches, wildcard patterns, and the+- **[`scope.clj`](scope.clj)** - Scope matching logic. Supports exact matches, wildcard patterns, and the`::unrestricted` sentinel for session-based auth.### Request flow```MCP client- → POST /api/mcp (JSON-RPC)- → Origin + session validation- → Auth: OAuth bearer token or browser session- → Scope check against requested tool- → Synthetic request to Agent API endpoint- → Response materialized as MCP content- → JSON or SSE back to client+ -> POST /api/mcp (JSON-RPC)+ -> Origin + session validation+ -> Auth: OAuth bearer token or browser session+ -> Scope check against requested tool+ -> Synthetic request to Agent API endpoint+ -> Response materialized as MCP content+ -> JSON or SSE back to client```## Further readingdiff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.cljindex a5a7d9ec2ef..c9184ae464d 100644--- a/src/metabase/mcp/tools.clj+++ b/src/metabase/mcp/tools.clj@@ -293,7 +293,7 @@;; Tools that accept :query_handle as an alternative to a raw base64 :query string.(def ^:private tools-accepting-query-handle- #{"execute_query" "visualize_query"})+ #{"execute_query" "visualize_query" "create_question" "update_question"});;; ------------------------------------------------- Tool Dispatch -------------------------------------------------@@ -328,8 +328,8 @@(defn- deliver-agent-api-response"Dispatch to agent API routes and deliver response to promise.- For POST requests, `params` is sent as the request body.- For GET/DELETE requests, `params` is sent as parsed query params.+ For POST/PUT/PATCH requests, `params` is sent as the request body.+ For other methods (GET/DELETE), `params` is sent as parsed query params.Materializes StreamingResponse bodies in-process before delivering."[result method path token-scopes params](agent-api/routes@@ -337,8 +337,9 @@:uri path:metabase-user-id api/*current-user-id*:token-scopes token-scopes}- (and (seq params) (= :post method)) (assoc :body params)- (and (seq params) (not= :post method)) (assoc :query-params params))+ ;; POST/PUT/PATCH carry params in the body; GET/DELETE carry them as query params.+ (and (seq params) (#{:post :put :patch} method)) (assoc :body params)+ (and (seq params) (not (#{:post :put :patch} method))) (assoc :query-params params))(fn [{resp-body :body :as response}](deliver result (if (instance? StreamingResponse resp-body)(capture-streaming-response resp-body)@@ -352,7 +353,8 @@(defn- invoke-agent-api"Invoke an Agent API endpoint with a synthetic Ring request.Returns MCP content (text-content on success, error-content on failure).- For POST, `params` becomes the request body; for GET/DELETE, `params` becomes query-params.+ For POST/PUT/PATCH, `params` becomes the request body; otherwise (GET/DELETE)+ `params` becomes query-params.Propagates `token-scopes` from the original MCP request so that scope restrictionsare preserved through the synthetic request.@@ -400,8 +402,9 @@(defn- dispatch-via-agent-api"Generic dispatch for tools whose responseFormat is \"json\".Looks up method/path from the tool definition, interpolates path params,- and calls `invoke-agent-api`. For POST requests, remaining args are sent as the- request body. For GET/DELETE requests, remaining args are sent as query params."+ and calls `invoke-agent-api`. For POST/PUT/PATCH requests, remaining args are+ sent as the request body. For other methods (GET/DELETE), remaining args are+ sent as query params."[tool-def arguments token-scopes session-id](let [{:keys [method path]} (:endpoint tool-def)tool-name (:name tool-def)diff --git a/src/metabase/metabot/core.clj b/src/metabase/metabot/core.cljindex 2547661f838..3dffd95f9ed 100644--- a/src/metabase/metabot/core.clj+++ b/src/metabase/metabot/core.clj@@ -12,14 +12,17 @@metabase-provider?provider-and-model->provider][metabase.metabot.scope+ agent-collection-createagent-dashboard-create- agent-metric-read- agent-question-create+ agent-dashboard-updateagent-queryagent-query-constructagent-query-execute+ agent-question-create+ agent-question-update+ agent-resource-readagent-search- agent-table-read]+ agent-sql-execute][metabase.metabot.search-modelsentity-type->search-modelsearch-model->entity-type])diff --git a/src/metabase/metabot/scope.clj b/src/metabase/metabot/scope.cljindex cb73afccdfd..cacf38cddeb 100644--- a/src/metabase/metabot/scope.clj+++ b/src/metabase/metabot/scope.clj@@ -37,6 +37,8 @@;; Question (saved cards via Agent API)(api-scope/defscope agent-question-create "agent:question:create"(deferred-tru "Create saved questions"))+(api-scope/defscope agent-question-update "agent:question:update"+ (deferred-tru "Update saved questions"));; Transforms(api-scope/defscope agent-transforms-read "agent:transforms:read"@@ -51,9 +53,19 @@;; Dashboard(api-scope/defscope agent-dashboard-create "agent:dashboard:create"(deferred-tru "Create dashboards"))+(api-scope/defscope agent-dashboard-update "agent:dashboard:update"+ (deferred-tru "Update dashboards"))(api-scope/defscope agent-dashboard-subscribe "agent:dashboard:subscribe"(deferred-tru "Subscribe to dashboard alerts"))+;; Collection+(api-scope/defscope agent-collection-create "agent:collection:create"+ (deferred-tru "Create collections"))++;; SQL execution (MCP execute_sql tool, distinct from execute_query)+(api-scope/defscope agent-sql-execute "agent:sql:execute"+ (deferred-tru "Execute raw SQL queries"))+;; Document(api-scope/defscope agent-document-read "agent:document:read"(deferred-tru "View documents"))@@ -96,14 +108,6 @@(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;;; ──────────────────────────────────────────────────────────────────@@ -151,8 +155,9 @@"Map from metabot permission type to the wildcard scope strings granted whenthat permission is `:yes`."{:permission/metabot-sql-generation #{"agent:sql:*" "agent:transforms:*" "agent:snippets:*"}- :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:*"}})+ :permission/metabot-nlq #{"agent:notebook:*" "agent:query:*" "agent:question:*"}+ :permission/metabot-other-tools #{"agent:viz:*" "agent:dashboard:*" "agent:document:*" "agent:alert:*"+ "agent:collection:*"}})(def always-granted-scopes"Scopes granted to every user regardless of permissions."diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex c19a3f9ec09..3006ac6d8c0 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -2,15 +2,18 @@"Agent API functional tests using session-based authentication.JWT and scope-related tests live in metabase-enterprise.agent-api.api-test."(:require+ [clojure.string :as str][clojure.test :refer :all][environ.core :as env][java-time.api :as t]- [medley.core :as m][metabase.agent-api.api :as agent-api.api][metabase.agent-api.settings :as agent-api.settings][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.lib.normalize :as lib.normalize]+ [metabase.permissions.core :as perms]+ [metabase.permissions.models.data-permissions :as data-perms]+ [metabase.permissions.models.permissions-group :as perms-group][metabase.search.ingestion :as search.ingestion][metabase.search.test-util :as search.tu][metabase.session.models.session :as session.models]@@ -19,7 +22,6 @@[metabase.test.http-client :as client][metabase.util :as u][metabase.util.json :as json]- [metabase.warehouse-schema.models.field-values :as field-values][toucan2.core :as t2]))(set! *warn-on-reflection* true)@@ -85,131 +87,6 @@;;; ------------------------------------------------- Functional Tests ---------------------------------------------------(deftest get-table-details-test- (testing "Returns table details for valid table ID"- (let [table-id (mt/id :orders)]- (is (=? {:type "table"- :id table-id- :name "ORDERS"- :display_name "Orders"- :database_id (mt/id)- :fields sequential?- :related_tables sequential?}- (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" table-id))))))- (testing "Returns 404 for non-existent table"- (is (= "Not found."- (mt/user-http-request :rasta :get 404 "agent/v1/table/999999"))))- (testing "Respects query parameters"- (let [table-id (mt/id :orders)]- (is (=? {:type "table"- :id table-id- :fields empty?}- (mt/user-http-request :rasta :get 200- (str "agent/v1/table/" table-id "?with-fields=false&with-related-tables=false"))))))- (testing "Field values are excluded by default"- (let [table-id (mt/id :orders)- table (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" table-id))]- (is (every? #(nil? (:field_values %)) (:fields table)))))- (testing "Field values are included when explicitly requested"- (let [table-id (mt/id :orders)- table (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" table-id "?with-field-values=true"))]- (is (some #(seq (:field_values %)) (:fields table))))))--(deftest get-table-details-field-types-test- (testing "Field metadata (base_type, effective_type, semantic_type, coercion_strategy) is returned correctly"- (mt/with-temp [:model/Database {db-id :id} {}- :model/Table {table-id :id} {:db_id db-id, :name "t", :active true}- :model/Field _ {:table_id table-id, :name "id"- :base_type :type/BigInteger- :semantic_type :type/PK}- :model/Field _ {:table_id table-id, :name "name"- :base_type :type/Text}- :model/Field _ {:table_id table-id, :name "created_at"- :base_type :type/Text- :effective_type :type/DateTime- :coercion_strategy :Coercion/ISO8601->DateTime}]- (let [fields (-> (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" table-id))- :fields)- by-name (m/index-by :name fields)]- (testing "base_type is always set"- (is (= "type/BigInteger" (get-in by-name ["id" :base_type])))- (is (= "type/Text" (get-in by-name ["name" :base_type])))- (is (= "type/Text" (get-in by-name ["created_at" :base_type]))))- (testing "semantic_type is returned when set"- (is (= "type/PK" (get-in by-name ["id" :semantic_type])))- (is (nil? (get-in by-name ["name" :semantic_type]))))- (testing "effective_type and coercion_strategy are returned when coerced"- (is (= "type/DateTime" (get-in by-name ["created_at" :effective_type])))- (is (= "Coercion/ISO8601->DateTime" (get-in by-name ["created_at" :coercion_strategy]))))- (testing "effective_type is omitted when it equals base_type"- (is (not (contains? (get by-name "id") :effective_type)))- (is (not (contains? (get by-name "name") :effective_type))))))))--(deftest get-metric-details-test- (mt/with-temp [:model/Card metric {:name "Test Metric"- :type :metric- :database_id (mt/id)- :dataset_query (orders-count-query)}]- (testing "Returns metric details for valid metric ID"- (is (=? {:type "metric"- :id (:id metric)- :name "Test Metric"- :queryable_dimensions sequential?}- (mt/user-http-request :rasta :get 200 (str "agent/v1/metric/" (:id metric))))))- (testing "Respects query parameters"- (is (=? {:type "metric"- :id (:id metric)}- (mt/user-http-request :rasta :get 200- (str "agent/v1/metric/" (:id metric)- "?with-queryable-dimensions=false&with-field-values=false")))))- (testing "Returns 404 for non-existent metric"- (is (= "Not found."- (mt/user-http-request :rasta :get 404 "agent/v1/metric/999999"))))))--(defn- ensure-fresh-field-values!- "Ensure field values exist for a field by deleting any existing ones and recreating them."- [field-id]- (t2/delete! :model/FieldValues :field_id field-id :type :full)- (field-values/get-or-create-full-field-values! (t2/select-one :model/Field :id field-id)))--(defn- visible-field-id- "Find the real field ID for a field by display name within a table's visible columns."- [table-id field-display-name]- (let [mp (mt/metadata-provider)- query (lib/query mp (lib.metadata/table mp table-id))- visible-cols (lib/visible-columns query)]- (->> visible-cols- (filter #(= (lib/display-name query %) field-display-name))- first- :id)))--(deftest get-table-field-values-test- ;; Ensure field values exist for the field we'll test- (ensure-fresh-field-values! (mt/id :people :state))- (testing "Returns field statistics and values with default limit of 30"- (let [table-id (mt/id :people)- field-id (visible-field-id table-id "State")]- (is (some? field-id) "Should find the State field")- (let [result (mt/user-http-request :crowberto :get 200- (format "agent/v1/table/%d/field/%s/values" table-id field-id))]- (is (=? {:value_metadata {:statistics {:distinct-count 49}- :field_values sequential?}}- result))- (is (<= (count (:values result)) 30) "Should apply default limit of 30"))))- (testing "Respects explicit limit parameter"- (let [table-id (mt/id :people)- field-id (visible-field-id table-id "State")]- (is (=? {:value_metadata {:field_values #(= 5 (count %))}}- (mt/user-http-request :crowberto :get 200- (format "agent/v1/table/%d/field/%s/values?limit=5" table-id field-id))))))- (testing "Returns 404 for non-existent table"- (is (= "Not found."- (mt/user-http-request :crowberto :get 404 "agent/v1/table/999999/field/999999/values"))))- (testing "Returns 404 for non-existent field"- (let [table-id (mt/id :people)]- (is (= "Field 999999 not found"- (mt/user-http-request :crowberto :get 404 (format "agent/v1/table/%d/field/999999/values" table-id)))))))-(deftest search-test(binding [search.ingestion/*force-sync* true](search.tu/with-new-search-if-available-otherwise-legacy@@ -424,29 +301,18 @@execute-resp (mt/user-http-request :rasta :post 202 "agent/v1/execute"{:query (:query construct-resp)})](is (=? {:status "completed" :row_count 200}- execute-resp)))))--(deftest get-metric-field-values-test- (ensure-fresh-field-values! (mt/id :orders :quantity))- (mt/with-temp [:model/Card metric {:name "Test Metric"- :type :metric- :database_id (mt/id)- :dataset_query (orders-count-query)}]- (testing "Returns field statistics for a field that has statistics"- (let [metric-details (mt/user-http-request :rasta :get 200 (str "agent/v1/metric/" (:id metric)))- quantity-field (m/find-first #(= (:name %) "QUANTITY") (:queryable_dimensions metric-details))]- (is (some? quantity-field) "Quantity field should be in queryable_dimensions")- (when-let [field-id (:field_id quantity-field)]- (is (=? {:value_metadata {:statistics map?- :field_values sequential?}}- (mt/user-http-request :rasta :get 200- (format "agent/v1/metric/%d/field/%s/values" (:id metric) field-id)))))))- (testing "Returns 404 for non-existent metric"- (is (= "Not found."- (mt/user-http-request :rasta :get 404 "agent/v1/metric/999999/field/999999/values"))))- (testing "Returns 404 for non-existent field on metric"- (is (= "Field 999999 not found"- (mt/user-http-request :rasta :get 404 (format "agent/v1/metric/%d/field/999999/values" (:id metric))))))))+ execute-resp))))+ (testing "Rejects native queries with 400; force callers onto /v1/execute-sql"+ ;; The scope `agent:query:execute` gates /v1/execute; `agent:sql:execute` gates+ ;; /v1/execute-sql. If /v1/execute accepted a base64 payload carrying :type :native,+ ;; a token with only the broader scope could run raw SQL, defeating the scope split.+ (let [native-query {:database (mt/id)+ :type "native"+ :native {:query "select 1"}}+ base64-query (u/encode-base64 (json/encode native-query))+ resp (mt/user-http-request :rasta :post 400 "agent/v1/execute"+ {:query base64-query})]+ (is (re-find #"Native queries are not supported" (str resp))))))(deftest construct-metric-query-test(mt/with-temp [:model/Card metric {:name "Test Metric"@@ -491,24 +357,6 @@(let [decoded (decode-query response)](is (seq (lib/filters decoded)) "Query should have filters")))))-(deftest get-table-details-with-measures-test- (let [measure-def (-> (lib/query (mt/metadata-provider)- (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))- (lib/aggregate (lib/sum (lib.metadata/field (mt/metadata-provider) (mt/id :orders :total)))))]- (mt/with-temp [:model/Measure {measure-id :id} {:name "Total Revenue"- :table_id (mt/id :orders)- :definition measure-def}]- (testing "with-measures=false (default) does not include measures"- (let [table (mt/user-http-request :rasta :get 200 (str "agent/v1/table/" (mt/id :orders)))]- (is (nil? (:measures table)))))- (testing "with-measures=true includes measures for the table"- (let [table (mt/user-http-request :rasta :get 200- (str "agent/v1/table/" (mt/id :orders) "?with-measures=true"))]- (is (sequential? (:measures table)))- (is (=? [{:id measure-id- :name "Total Revenue"}]- (:measures table))))))))-(deftest combined-query-test(testing "Returns results for a table query that fits in a single page"(let [response (mt/user-http-request :rasta :post 202 "agent/v2/query"@@ -628,7 +476,31 @@:collection_id coll-id:description "A test question"}create-resp))- (t2/delete! :model/Card :id (:id create-resp))))))+ (t2/delete! :model/Card :id (:id create-resp)))))+ (testing "Returns 403 when caller cannot run the proposed query"+ ;; Mirrors retro's data-perms-bypass repro: collection write does not imply the right+ ;; to save a card whose query references data the user cannot run.+ (mt/with-restored-data-perms!+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {writable-id :id} {:name "Writable For Create-Q"}]+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) writable-id)+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :blocked)+ (let [construct-resp (mt/user-http-request :crowberto :post 200 "agent/v2/construct-query"+ {:query (orders-query :limit 10)})]+ (mt/user-http-request :rasta :post 403 "agent/v1/question"+ {:name "Should Not Save"+ :query (:query construct-resp)+ :collection_id writable-id}))))))+ (testing "Returns 403 when caller cannot write to target collection"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {locked-id :id} {:name "Locked For Create-Q"}]+ ;; rasta has data perms by default in test setup, but no write on `locked-id`.+ (let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"+ {:query (orders-query :limit 10)})]+ (mt/user-http-request :rasta :post 403 "agent/v1/question"+ {:name "Should Not Save"+ :query (:query construct-resp)+ :collection_id locked-id}))))));;; ----------------------------------------------- Create Dashboard Tests ------------------------------------------@@ -677,3 +549,455 @@(mt/user-http-request :rasta :post 404 "agent/v1/dashboard"{:name "Bad Dashboard":question_ids [999999]})))++(deftest create-collection-test+ (testing "Creates a root-level collection"+ (mt/with-current-user (mt/user->id :crowberto)+ (let [resp (mt/user-http-request :crowberto :post 200 "agent/v1/collection"+ {:name "Agent Root Coll"})]+ (is (=? {:id pos?+ :name "Agent Root Coll"+ :parent_id nil+ :location "/"+ :description nil}+ resp))+ (t2/delete! :model/Collection :id (:id resp)))))+ (testing "Creates a nested collection under a parent"+ (mt/with-temp [:model/Collection {parent-id :id} {:name "Agent Parent Coll"}]+ (let [resp (mt/user-http-request :crowberto :post 200 "agent/v1/collection"+ {:name "Agent Nested Coll"+ :description "Nested under parent"+ :parent_collection_id parent-id})]+ (is (=? {:id pos?+ :name "Agent Nested Coll"+ :parent_id parent-id+ :description "Nested under parent"}+ resp))+ ;; location should encode the parent's id in the materialized path+ (is (= (str "/" parent-id "/") (:location resp)))+ (t2/delete! :model/Collection :id (:id resp)))))+ (testing "Returns 404 when parent_collection_id does not exist"+ (mt/user-http-request :crowberto :post 404 "agent/v1/collection"+ {:name "Bad Parent Coll"+ :parent_collection_id 999999}))+ (testing "Returns 403 when caller lacks write access on the parent"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {parent-id :id} {:name "Locked Parent"}]+ ;; Non-admin groups have no perms on the new collection by default.+ (mt/user-http-request :rasta :post 403 "agent/v1/collection"+ {:name "Should Fail"+ :parent_collection_id parent-id}))))+ ;; Parent-inheritance behaviors (:namespace, :type "library*", :is_remote_synced, exclusion of+ ;; :type "trash") are unit-tested directly against `apply-defaults-to-collection` in+ ;; `metabase.collections.create-test`, since the HTTP boundary is gated by other checks+ ;; (library collections refuse writes, snippet-namespace collections require explicit perms)+ ;; that make end-to-end coverage redundant.+ )++;;; ----------------------------------------------- Update Question Tests ------------------------------------------++(deftest update-question-patch-fields-test+ (testing "Patches simple fields (name, description, archived)"+ (mt/with-temp [:model/Card {card-id :id} {:name "Agent Update Q Original"+ :dataset_query (orders-count-query)+ :display :table}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/question/" card-id)+ {:name "Renamed by Agent"+ :description "Set by agent"})]+ (is (=? {:id card-id+ :name "Renamed by Agent"+ :description "Set by agent"+ :archived false}+ resp)))+ ;; verify persisted+ (is (= "Renamed by Agent" (t2/select-one-fn :name :model/Card :id card-id)))+ (is (= "Set by agent" (t2/select-one-fn :description :model/Card :id card-id))))))++(deftest update-question-move-test+ (testing "Moving a card sets collection_id (subsumes move_card)"+ (mt/with-temp [:model/Collection {dest-coll-id :id} {:name "Agent Move Dest"}+ :model/Card {card-id :id} {:name "Card To Move"+ :dataset_query (orders-count-query)+ :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 (= dest-coll-id (t2/select-one-fn :collection_id :model/Card :id card-id))))))++(deftest update-question-archive-test+ (testing "Archiving a card also sets :archived_directly so it lands in the Trash"+ (mt/with-temp [:model/Card {card-id :id} {:name "Card To Archive"+ :dataset_query (orders-count-query)+ :display :table}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/question/" card-id)+ {:archived true})]+ (is (true? (:archived resp))))+ (is (true? (t2/select-one-fn :archived :model/Card :id card-id)))+ ;; Mirrors the REST archive flow -- without :archived_directly the card would only show up+ ;; as inherited-from-trash and stay invisible in the Trash UI.+ (is (true? (t2/select-one-fn :archived_directly :model/Card :id card-id))))))++(deftest update-question-replace-query-test+ (testing "Replacing the underlying query via :query (base64)"+ (mt/with-temp [:model/Card {card-id :id} {:name "Card To Re-query"+ :dataset_query (orders-count-query)+ :display :table}]+ (let [products-id (mt/id :products)+ products-fk [(db-name) "PUBLIC" "PRODUCTS"]+ new-query (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"+ {:query {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table products-fk+ :limit 5}]}})+ base64-query (:query new-query)+ _resp (mt/user-http-request :rasta :put 200 (str "agent/v1/question/" card-id)+ {:query base64-query})+ persisted (t2/select-one-fn :dataset_query :model/Card :id card-id)+ stages (:stages persisted)+ source-table (some :source-table stages)]+ ;; Query was replaced - source-table changed from orders to products.+ ;; Construct sends portable FKs over the wire, but the persisted dataset_query is the+ ;; resolved MBQL 5 map with numeric IDs.+ (is (some? persisted))+ (is (= products-id source-table)+ (str "Expected persisted dataset_query :source-table to be the products table id "+ products-id ", got " source-table))))))++(deftest update-question-not-found-test+ (testing "Returns 404 when card does not exist"+ (mt/user-http-request :rasta :put 404 "agent/v1/question/999999"+ {:name "doesn't matter"})))++(deftest update-question-write-perm-test+ (testing "Returns 403 when caller lacks write access on the card"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {locked-coll-id :id} {:name "Locked Coll"}+ :model/Card {card-id :id} {:name "Hidden Card"+ :dataset_query (orders-count-query)+ :display :table+ :collection_id locked-coll-id}]+ (mt/user-http-request :rasta :put 403 (str "agent/v1/question/" card-id)+ {:name "Forbidden Rename"})))))++(deftest update-question-target-perm-test+ (testing "Returns 403 when caller can write source collection but not target"+ ;; Guard against an LLM moving a card into a collection the user can't normally write.+ ;; api/write-check on the card covers the source side; collection/check-allowed-to-change-+ ;; collection covers the target side.+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {writable-id :id} {:name "Writable Src"}+ :model/Collection {locked-id :id} {:name "Locked Dest"}+ :model/Card {card-id :id} {:name "Card In Writable"+ :dataset_query (orders-count-query)+ :display :table+ :collection_id writable-id}]+ (perms/grant-collection-readwrite-permissions!+ (perms-group/all-users) writable-id)+ (mt/user-http-request :rasta :put 403 (str "agent/v1/question/" card-id)+ {:collection_id locked-id})))))++(deftest update-question-display-validation-test+ (testing "Rejects unknown :display values with 400"+ (mt/with-temp [:model/Card {card-id :id} {:name "Card Display Validation"+ :dataset_query (orders-count-query)+ :display :table}]+ ;; The Malli enum on ::card-display should reject "potato" with a validation error.+ (mt/user-http-request :rasta :put 400 (str "agent/v1/question/" card-id)+ {:display "potato"}))))++(deftest update-question-cycle-rejection-test+ (testing "Returns 400 when swapping :query introduces a self-referencing cycle"+ ;; Mirror REST's `lib/check-card-overwrite` gate. A query whose source is the very+ ;; card being updated would persist a cyclic card otherwise (branch review A1).+ (mt/with-temp [:model/Card {card-id :id} {:name "Card About To Cycle"+ :dataset_query (orders-count-query)+ :display :table}]+ (let [cycle-query {:database (mt/id)+ :type :query+ :query {:source-table (str "card__" card-id)}}+ base64-query (u/encode-base64 (json/encode cycle-query))]+ (mt/user-http-request :rasta :put 400 (str "agent/v1/question/" card-id)+ {:query base64-query}))+ ;; Persisted query unchanged - source-table still the orders table id, not the card.+ (let [persisted (t2/select-one-fn :dataset_query :model/Card :id card-id)]+ (is (= (mt/id :orders) (some :source-table (:stages persisted)))+ "dataset_query should not have been swapped to a card__ reference")))))++(deftest update-question-query-perm-test+ (testing "Returns 403 when swapping :query to one referencing data the caller cannot run"+ ;; Guard against the gap retro identified in branch review:+ ;; collection write on a card does NOT grant the right to repoint it at forbidden data.+ ;; REST's `check-allowed-to-modify-query` runs in the REST wrapper above `queries/update-card!`;+ ;; the agent endpoint calls `update-card!` directly, so we have to gate it ourselves.+ (mt/with-restored-data-perms!+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {writable-id :id} {:name "Writable For Q-Swap"}+ :model/Card {card-id :id} {:name "Card With Allowed Query"+ :dataset_query (orders-count-query)+ :display :table+ :collection_id writable-id}]+ (perms/grant-collection-readwrite-permissions! (perms-group/all-users) writable-id)+ ;; Block data access on the sample DB for the All Users group.+ (data-perms/set-database-permission! (perms-group/all-users) (mt/id) :perms/view-data :blocked)+ (let [products-fk [(db-name) "PUBLIC" "PRODUCTS"]+ new-query (mt/user-http-request :crowberto :post 200 "agent/v2/construct-query"+ {:query {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table products-fk+ :limit 5}]}})+ base64-query (:query new-query)]+ (mt/user-http-request :rasta :put 403 (str "agent/v1/question/" card-id)+ {:query base64-query}))+ ;; Persisted query unchanged - dataset_query.stages[0].source-table is the orders table id.+ (let [persisted (t2/select-one-fn :dataset_query :model/Card :id card-id)]+ (is (= (mt/id :orders) (some :source-table (:stages persisted)))+ "dataset_query should not have been swapped")))))))++;;; ---------------------------------------------- Update Dashboard Tests ------------------------------------------++(deftest update-dashboard-test+ (testing "Patches name and description"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Original Name"}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:name "Renamed by Agent"+ :description "Set by agent"})]+ (is (=? {:id dash-id+ :name "Renamed by Agent"+ :description "Set by agent"+ :archived false}+ resp)))+ (is (= "Renamed by Agent" (t2/select-one-fn :name :model/Dashboard :id dash-id)))+ (is (= "Set by agent" (t2/select-one-fn :description :model/Dashboard :id dash-id)))))+ (testing "Moving a dashboard sets collection_id and moves its cards"+ (mt/with-temp [:model/Collection {dest-coll-id :id} {:name "Agent Dash Dest"}+ :model/Dashboard {dash-id :id} {:name "Dash To Move"}+ :model/Card {card-id :id} {:name "Card On Dash"+ :dataset_query (orders-count-query)+ :display :table+ :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 (= 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)))))+ (testing "Archiving a dashboard cascades to its cards"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Dash To Archive"}+ :model/Card {card-id :id} {:name "Cascading Card"+ :dataset_query (orders-count-query)+ :display :table+ :dashboard_id dash-id}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:archived true})]+ (is (true? (:archived resp))))+ (is (true? (t2/select-one-fn :archived :model/Dashboard :id dash-id)))+ (is (true? (t2/select-one-fn :archived :model/Card :id card-id)))))+ (testing "Returns 404 when dashboard does not exist"+ (mt/user-http-request :rasta :put 404 "agent/v1/dashboard/999999"+ {:name "doesn't matter"}))+ (testing "Returns 403 when caller lacks write access on the dashboard"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {locked-coll-id :id} {:name "Locked Coll For Dash"}+ :model/Dashboard {dash-id :id} {:name "Hidden Dash"+ :collection_id locked-coll-id}]+ (mt/user-http-request :rasta :put 403 (str "agent/v1/dashboard/" dash-id)+ {:name "Forbidden Rename"}))))+ (testing "Returns 403 when caller can write source collection but not target"+ (mt/with-non-admin-groups-no-root-collection-perms+ (mt/with-temp [:model/Collection {writable-id :id} {:name "Writable Dash Src"}+ :model/Collection {locked-id :id} {:name "Locked Dash Dest"}+ :model/Dashboard {dash-id :id} {:name "Dash In Writable"+ :collection_id writable-id}]+ (perms/grant-collection-readwrite-permissions!+ (perms-group/all-users) writable-id)+ (mt/user-http-request :rasta :put 403 (str "agent/v1/dashboard/" dash-id)+ {:collection_id locked-id})))))++(deftest update-dashboard-dashcards-add-test+ (testing "Add a card to the dashboard (autoplaced)"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Add Target"}+ :model/Card {card-id :id} {:name "Card to add"+ :dataset_query (orders-count-query)+ :display :table}]+ (let [resp (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add" :card_id card-id}]})]+ (is (= 1 (count (:dashcard_ids resp))))+ (let [dashcards (t2/select :model/DashboardCard :dashboard_id dash-id)]+ (is (= 1 (count dashcards)))+ (is (= card-id (:card_id (first dashcards))))+ ;; Autoplaced - row and col are set even though we didn't provide them.+ (is (nat-int? (:row (first dashcards))))+ (is (nat-int? (:col (first dashcards)))))))))++(deftest update-dashboard-dashcards-multi-add-test+ (testing "Add multiple cards in one call - each one autoplaced w/o overlap"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Multi-add"}+ :model/Card {c1 :id} {:name "C1" :dataset_query (orders-count-query) :display :table}+ :model/Card {c2 :id} {:name "C2" :dataset_query (orders-count-query) :display :table}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add" :card_id c1}+ {:action "add" :card_id c2}]})+ (let [dashcards (t2/select :model/DashboardCard :dashboard_id dash-id)+ positions (map (juxt :row :col) dashcards)]+ (is (= 2 (count dashcards)))+ (is (= 2 (count (set positions))) "Each dashcard should have a unique row/col")))))++(deftest update-dashboard-dashcards-remove-test+ (testing "Remove a dashcard"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Remove"}+ :model/Card {card-id :id} {:name "to remove" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard {dashcard-id :id} {:dashboard_id dash-id :card_id card-id+ :row 0 :col 0 :size_x 12 :size_y 9}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "remove" :dashcard_id dashcard-id}]})+ (is (zero? (count (t2/select :model/DashboardCard :dashboard_id dash-id)))))))++(deftest update-dashboard-dashcards-move-top-test+ (testing "Move a dashcard to the top"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Move"}+ :model/Card {card-id :id} {:name "movable" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard {dashcard-id :id} {:dashboard_id dash-id :card_id card-id+ :row 5 :col 3 :size_x 12 :size_y 9}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "move" :dashcard_id dashcard-id :position "top"}]})+ (let [moved (t2/select-one :model/DashboardCard :id dashcard-id)]+ (is (= 0 (:row moved)))+ (is (= 0 (:col moved)))))))++(deftest update-dashboard-dashcards-move-top-reflow-test+ (testing "Move to top shifts other cards down by the moved card's :size_y - no overlap"+ ;; Regression for branch review #2: previously slammed the moved card at {:row 0 :col 0}+ ;; without reflowing the rest, leaving cards on top of each other.+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Move-Top Reflow"}+ :model/Card {a-card :id} {:name "A" :dataset_query (orders-count-query) :display :table}+ :model/Card {b-card :id} {:name "B" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard {a-dc :id} {:dashboard_id dash-id :card_id a-card+ :row 0 :col 0 :size_x 12 :size_y 6}+ :model/DashboardCard {b-dc :id} {:dashboard_id dash-id :card_id b-card+ :row 6 :col 0 :size_x 12 :size_y 6}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "move" :dashcard_id b-dc :position "top"}]})+ (let [a (t2/select-one :model/DashboardCard :id a-dc)+ b (t2/select-one :model/DashboardCard :id b-dc)]+ ;; b lands at row 0; a shifts down by b's :size_y (6).+ (is (= 0 (:row b)))+ (is (= 6 (:row a)))+ ;; Bounding boxes don't intersect.+ (is (>= (:row a) (+ (:row b) (:size_y b)))+ "A should sit entirely below B after the move-to-top reflow")))))++(deftest update-dashboard-dashcards-mixed-test+ (testing "Mix add + remove + metadata patch in a single call"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Mix"}+ :model/Card {keep-card :id} {:name "keep" :dataset_query (orders-count-query) :display :table}+ :model/Card {add-card :id} {:name "add" :dataset_query (orders-count-query) :display :table}+ :model/Card {drop-card :id} {:name "drop" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard {keep-dc :id} {:dashboard_id dash-id :card_id keep-card+ :row 0 :col 0 :size_x 6 :size_y 4}+ :model/DashboardCard {drop-dc :id} {:dashboard_id dash-id :card_id drop-card+ :row 4 :col 0 :size_x 6 :size_y 4}]+ (mt/user-http-request :rasta :put 200 (str "agent/v1/dashboard/" dash-id)+ {:description "Mixed patch"+ :dashcards [{:action "remove" :dashcard_id drop-dc}+ {:action "add" :card_id add-card}]})+ (let [dashcards (t2/select :model/DashboardCard :dashboard_id dash-id)+ card-ids (set (map :card_id dashcards))]+ (is (= #{keep-card add-card} card-ids))+ (is (some #(= keep-dc (:id %)) dashcards) "Untouched dashcard survives")+ (is (= "Mixed patch" (t2/select-one-fn :description :model/Dashboard :id dash-id)))))))++(deftest update-dashboard-dashcards-add-missing-card-test+ (testing "Returns 404 when add references a missing card"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Missing Card"}]+ (mt/user-http-request :rasta :put 404 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "add" :card_id 999999}]}))))++(deftest update-dashboard-dashcards-remove-missing-dashcard-test+ (testing "Returns 404 when remove references a dashcard not on this dashboard"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Wrong Dashcard"}]+ (mt/user-http-request :rasta :put 404 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "remove" :dashcard_id 999999}]}))))++(deftest update-dashboard-dashcards-move-validation-test+ (testing "Move requires :position - omitting it returns 400"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Phase B Move Validation"}+ :model/Card {card-id :id} {:name "x" :dataset_query (orders-count-query) :display :table}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id+ :row 0 :col 0 :size_x 6 :size_y 4}]+ (mt/user-http-request :rasta :put 400 (str "agent/v1/dashboard/" dash-id)+ {:dashcards [{:action "move" :dashcard_id dc-id}]}))))++;;; ------------------------------------------------- Execute SQL Tests --------------------------------------------++(deftest execute-sql-test+ (testing "Admin can run a native SQL query (default perms)"+ (let [resp (mt/user-http-request :crowberto :post 202 "agent/v1/execute-sql"+ {:database_id (mt/id)+ :sql "SELECT 1 AS one"})]+ (is (= "completed" (:status resp)))+ (is (= [[1]] (-> resp :data :rows)))))+ (testing "Returns 403 when the user lacks native-query permission"+ (mt/with-no-data-perms-for-all-users!+ (mt/user-http-request :rasta :post 403 "agent/v1/execute-sql"+ {:database_id (mt/id)+ :sql "SELECT 1"})))+ (testing "Returns 403 when the kill-switch setting is disabled"+ (mt/with-temporary-setting-values [mcp-execute-sql-enabled false]+ (mt/user-http-request :crowberto :post 403 "agent/v1/execute-sql"+ {:database_id (mt/id)+ :sql "SELECT 1"})))+ (testing "Malformed SQL returns the userland :failed envelope (HTTP 400), not a raw 500"+ ;; Regression for branch review #1: previously bypassed userland middleware, so a+ ;; bad query threw `ExceptionInfo` and surfaced as HTTP 500. Now goes through+ ;; `prepare-agent-query`, which wraps errors in the documented `:failed` envelope+ ;; and surfaces them as a 400 with a structured body.+ (let [resp (mt/user-http-request :crowberto :post 400 "agent/v1/execute-sql"+ {:database_id (mt/id)+ :sql "SELECT * FROM table_that_does_not_exist"})]+ ;; The streaming pipeline wraps the failure in :via[0]/:status.+ (is (= "failed" (some-> resp :via first :status)))+ (is (string? (some-> resp :via first :error)))))+ (testing "A successful query records a QueryExecution audit row tagged :agent"+ ;; Bypass-of-userland regression (#1): without `prepare-agent-query` no audit row was+ ;; written. Verify a row lands and carries the agent context. The QueryExecution+ ;; insert is async, so poll for the new row.+ (let [before (t2/count :model/QueryExecution)]+ (mt/user-http-request :crowberto :post 202 "agent/v1/execute-sql"+ {:database_id (mt/id)+ :sql "SELECT 1 AS audit_probe"})+ (let [latest (u/poll {:thunk (fn [] (t2/select-one :model/QueryExecution+ {:order-by [[:started_at :desc]]}))+ :done? (fn [_qe] (> (t2/count :model/QueryExecution) before))+ :timeout-ms 5000+ :interval-ms 50})]+ (is (some? latest) "QueryExecution row should be inserted within 5s")+ (is (= :agent (:context latest)))))))++;;; ------------------------------------------------- Read Resource Tests -----------------------------------------++(deftest read-resource-test+ (testing "Dispatches a top-level URI through the shared resolver"+ (let [resp (mt/user-http-request :crowberto :post 200 "agent/v1/read-resource"+ {:uris ["metabase://databases"]})]+ (is (=? {:resources [(fn [r] (and (= "metabase://databases" (:uri r))+ (some? (:content r))))]+ :output string?}+ resp))+ ;; Output is XML-shaped for LLM consumption.+ (is (str/includes? (:output resp) "<resources>"))+ (is (str/includes? (:output resp) "metabase://databases"))))+ (testing "Fetches a single-entity URI"+ (let [resp (mt/user-http-request :crowberto :post 200 "agent/v1/read-resource"+ {:uris [(str "metabase://table/" (mt/id :orders))]})]+ (is (= 1 (count (:resources resp))))+ (is (some? (-> resp :resources first :content)))))+ (testing "Returns 400 when too many URIs"+ (let [uris (vec (repeat 10 "metabase://databases"))]+ (mt/user-http-request :crowberto :post 400 "agent/v1/read-resource"+ {:uris uris})))+ (testing "Reports a per-URI error rather than failing the whole call"+ (let [resp (mt/user-http-request :crowberto :post 200 "agent/v1/read-resource"+ {:uris ["metabase://nonsense/path"]})]+ (is (= 1 (count (:resources resp))))+ (is (nil? (-> resp :resources first :content)))+ (is (some? (-> resp :resources first :error))))))diff --git a/test/metabase/collections/create_test.clj b/test/metabase/collections/create_test.cljnew file mode 100644index 00000000000..a21d810e1ed--- /dev/null+++ b/test/metabase/collections/create_test.clj@@ -0,0 +1,81 @@+(ns metabase.collections.create-test+ "Unit tests for the parent-inheritance behavior in `apply-defaults-to-collection`.++ End-to-end coverage at the HTTP boundary is awkward because library collections refuse writes+ and snippet-namespace parents require explicit perms -- both of which would short-circuit before+ the inheritance code runs. These tests bypass write-check via with-redefs so the+ inheritance logic itself is exercised in isolation."+ (:require+ [clojure.test :refer :all]+ [metabase.api.common :as api]+ [metabase.collections.create :as collections.create]+ [metabase.test :as mt]+ [toucan2.core :as t2]))++(set! *warn-on-reflection* true)++(deftest apply-defaults-to-collection-test+ (testing "Child inherits :namespace from a non-default-namespace parent"+ (mt/with-temp [:model/Collection parent {:name "Snippet Parent" :namespace "snippets"}]+ (with-redefs [api/write-check (fn [& _])]+ (let [defaulted (collections.create/apply-defaults-to-collection+ {:name "Snippet Child" :parent_id (:id parent)})]+ (is (= :snippets (:namespace defaulted))+ "Namespace propagates from parent when child doesn't specify one")))))+ (testing "Caller's explicit :namespace wins over parent's"+ (mt/with-temp [:model/Collection parent {:name "Snippet Parent 2" :namespace "snippets"}]+ (with-redefs [api/write-check (fn [& _])]+ ;; Caller-provided namespace overrides parent inheritance — REST behavior we mirror.+ (let [defaulted (collections.create/apply-defaults-to-collection+ {:name "Explicit NS Child" :parent_id (:id parent) :namespace "default"})]+ (is (= "default" (:namespace defaulted)))))))+ (testing "Child inherits :type from a library-typed parent"+ (mt/with-temp [:model/Collection parent {:name "Library Parent" :type "library"}]+ (with-redefs [api/write-check (fn [& _])]+ (let [defaulted (collections.create/apply-defaults-to-collection+ {:name "Library Child" :parent_id (:id parent)})]+ (is (= "library" (:type defaulted))+ "Library type propagates so the child stays inside the library hierarchy")))))+ (testing "Child does NOT inherit :type \"trash\" from a trash parent"+ (mt/with-temp [:model/Collection parent {:name "Trashy Parent" :type "trash"}]+ (with-redefs [api/write-check (fn [& _])]+ ;; "trash" is a sentinel for the Trash collection; only library types propagate.+ (let [defaulted (collections.create/apply-defaults-to-collection+ {:name "Not-Trash Child" :parent_id (:id parent)})]+ (is (nil? (:type defaulted))+ "Trash type does not propagate to children")))))+ (testing "Child inherits :is_remote_synced from a remote-synced parent"+ (mt/with-temp [:model/Collection parent {:name "RS Parent" :is_remote_synced true}]+ (with-redefs [api/write-check (fn [& _])]+ (let [defaulted (collections.create/apply-defaults-to-collection+ {:name "RS Child" :parent_id (:id parent)})]+ (is (true? (:is_remote_synced defaulted))+ "Remote-synced flag propagates so the child participates in remote sync")))))+ (testing "Plain parent: child gets is_remote_synced=false, no type, no namespace"+ (mt/with-temp [:model/Collection parent {:name "Plain Parent"}]+ (with-redefs [api/write-check (fn [& _])]+ (let [defaulted (collections.create/apply-defaults-to-collection+ {:name "Plain Child" :parent_id (:id parent)})]+ (is (false? (:is_remote_synced defaulted)))+ (is (not (contains? defaulted :type)))+ (is (not (contains? defaulted :namespace)))))))+ (testing "Location reflects parent path"+ (mt/with-temp [:model/Collection parent {:name "Path Parent"}]+ (with-redefs [api/write-check (fn [& _])]+ (let [defaulted (collections.create/apply-defaults-to-collection+ {:name "Path Child" :parent_id (:id parent)})]+ (is (= (str "/" (:id parent) "/") (:location defaulted))))))))++(deftest create-collection!-test+ (testing "Creates a collection and persists inheritance defaults"+ (mt/with-temp [:model/Collection parent {:name "Persist Parent" :is_remote_synced true}]+ (with-redefs [api/write-check (fn [& _])]+ (let [coll (collections.create/create-collection!+ {:name "Persist Child" :parent_id (:id parent)})]+ (try+ (is (pos-int? (:id coll)))+ (is (= "Persist Child" (:name coll)))+ (is (true? (:is_remote_synced (t2/select-one :model/Collection :id (:id coll))))+ "Persisted child carries the inherited is_remote_synced flag")+ (finally+ (t2/delete! :model/Collection :id (:id coll)))))))))diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.cljindex 92a5231ba11..daa7c9b96c7 100644--- a/test/metabase/mcp/api_test.clj+++ b/test/metabase/mcp/api_test.clj@@ -227,16 +227,17 @@(def ^:private all-tool-names#{"construct_query"+ "create_collection""create_dashboard""create_question""execute_query"- "get_metric"- "get_metric_field_values"- "get_table"- "get_table_field_values"+ "execute_sql""query"+ "read_resource""render_drill_through""search"+ "update_dashboard"+ "update_question""visualize_query"})(deftest tools-list-all-tools-declare-required-hints-test@@ -268,18 +269,18 @@(testing "tools that declare outputSchema emit structuredContent — guards the regression where Claude Desktop got 500s because we declared outputSchema without matching structuredContent"(let [[session-id _] (initialize!)response (mcp-request (jsonrpc-request "tools/call"- {:name "get_table"- :arguments {:id (mt/id :orders)}})+ {:name "read_resource"+ :arguments {:uris ["metabase://databases"]}}){"mcp-session-id" session-id})result (get-in response [:body :result])](is (= 200 (:status response)))(is (not (:isError result))- (str "get_table should succeed: " (some-> result :content first :text)))+ (str "read_resource should succeed: " (some-> result :content first :text)))(is (contains? result :structuredContent)- "get_table declares outputSchema → MUST emit structuredContent")+ "read_resource declares outputSchema → MUST emit structuredContent")(is (map? (:structuredContent result))"structuredContent should be the parsed response object, not a string")- (is (= "ORDERS" (-> result :structuredContent :name))+ (is (sequential? (-> result :structuredContent :resources))"structuredContent should mirror the endpoint response shape"))))(deftest tools-list-strict-shape-test@@ -476,30 +477,6 @@(is (= 400 (:status response)))(is (= -32600 (get-in response [:body :error :code]))))))-;;; --------------------------------------------- Type-Safe Responses -------------------------------------------------(deftest type-safe-get-table-test- (testing "get_table response has properly encoded keys from Agent API"- (let [[session-id _] (initialize!)- response (mcp-request (jsonrpc-request "tools/call"- {:name "get_table"- :arguments {:id (mt/id :orders)}})- {"mcp-session-id" session-id})- result (get-in response [:body :result])- ;; Use first+:text since :content is a lazy seq (not indexable by get-in)- content-text (:text (first (:content result)))]- (is (= 200 (:status response)))- (is (nil? (:isError result)))- (is (string? content-text))- ;; Parse the content text as JSON and verify snake_case keys from Malli encoding- (let [table-data (json/decode+kw content-text)]- (is (=? {:name string?- :display_name string?- :database_id int?- :type "table"- :fields sequential?}- table-data))))))-(deftest initialized-notification-compatibility-test(testing "requests succeed without notifications/initialized"(let [response (mcp-request (jsonrpc-request "initialize"))@@ -545,7 +522,7 @@(testing "tools/call with missing path params returns an error"(let [[session-id _] (initialize!)response (mcp-request (jsonrpc-request "tools/call"- {:name "get_table" :arguments {}})+ {:name "update_question" :arguments {}}){"mcp-session-id" session-id})result (get-in response [:body :result])](is (= 200 (:status response)))@@ -559,8 +536,8 @@"\"Agent API error: <status>\".")(let [[session-id _] (initialize!)response (mcp-request (jsonrpc-request "tools/call"- {:name "get_table"- :arguments {:id 999999}})+ {:name "update_question"+ :arguments {:id 999999 :name "Bogus"}}){"mcp-session-id" session-id})result (get-in response [:body :result])message (:text (first (:content result)))]@@ -589,22 +566,6 @@(is (not (contains? schema k))(str (:name tool) " should have no top-level " k))))))))))-(deftest tools-call-get-table-query-params-test- (testing "get_table passes query params correctly (with-fields default true)"- (let [result (mt/with-current-user (mt/user->id :crowberto)- (mcp.tools/call-tool nil nil "get_table" {:id (mt/id :orders)}))]- (is (not (:isError result)))- (let [table-data (json/decode+kw (:text (first (:content result))))]- (is (seq (:fields table-data))- "with-fields defaults to true, so fields should be present"))))- (testing "get_table with with-fields=false omits fields"- (let [result (mt/with-current-user (mt/user->id :crowberto)- (mcp.tools/call-tool nil nil "get_table" {:id (mt/id :orders) :with-fields false}))]- (is (not (:isError result)))- (let [table-data (json/decode+kw (:text (first (:content result))))]- (is (empty? (:fields table-data))- "with-fields=false should return no fields")))))-(defn- orders-count-query"Simple count query on the orders table — used as the dataset_query for smoke-test metrics."[]@@ -617,9 +578,10 @@below) — the test compares this set against the Agent API-backed tools andfails when they diverge, ensuring no Agent API tool ships without a basicinvocation check."- #{"get_table" "get_table_field_values" "get_metric" "get_metric_field_values"- "search" "construct_query" "query" "execute_query"- "create_question" "create_dashboard"})+ #{"search" "construct_query" "query" "execute_query" "execute_sql"+ "read_resource"+ "create_question" "create_dashboard"+ "update_question" "update_dashboard" "create_collection"})(deftest tools-call-smoke-test(testing "every Agent API-backed tool is exercised by the smoke test"@@ -629,12 +591,11 @@"Add the missing tool to `smoke-tested-tools` and the call sequence below."))(testing "every tool returns a successful response with valid parameters"(search.tu/with-legacy-search- (mt/with-temp [:model/Card metric {:name "Smoke Metric"- :type :metric- :database_id (mt/id)- :dataset_query (orders-count-query)}]+ (mt/with-temp [:model/Card _metric {:name "Smoke Metric"+ :type :metric+ :database_id (mt/id)+ :dataset_query (orders-count-query)}](let [[session-id _] (initialize!)- orders-id (mt/id :orders)db-name (t2/select-one-fn :name :model/Database (mt/id))orders-query {:lib/type "mbql/query":stages [{:lib/type "mbql.stage/mbql"@@ -643,23 +604,21 @@;; Track write-tool outputs in atoms so the `finally` cleanup runs even if an;; assertion in `call-tool` fails partway through the sequence.question-id (atom nil)- dash-id (atom nil)]+ dash-id (atom nil)+ coll-id (atom nil)](try- (let [;; Read tools — call-tool helper asserts (not :isError) internally.- table-data (call-tool session-id "get_table" {:id orders-id})- table-fid (-> table-data :fields first :field_id)- _ (call-tool session-id "get_table_field_values"- {:id orders-id :field-id (str table-fid)})- metric-data (call-tool session-id "get_metric" {:id (:id metric)})- metric-fid (-> metric-data :queryable_dimensions first :field_id)- _ (call-tool session-id "get_metric_field_values"- {:id (:id metric) :field-id (str metric-fid)})+ (let [;; Discovery tools — call-tool helper asserts (not :isError) internally._ (call-tool session-id "search" {:term_queries ["orders"]});; Query construction + executionconstruct-data (call-tool session-id "construct_query" {:query orders-query})_ (call-tool session-id "query" {:query orders-query})_ (call-tool session-id "execute_query"{:query_handle (:query_handle construct-data)})+ _ (call-tool session-id "execute_sql"+ {:database_id (mt/id)+ :sql "SELECT 1"})+ _ (call-tool session-id "read_resource"+ {:uris ["metabase://databases"]});; Write tools — record IDs as soon as they're known so the `finally` block;; can clean up even if a later step throws.question-data (call-tool session-id "create_question"@@ -668,12 +627,22 @@(mt/user->id :crowberto)(:query_handle construct-data))})_ (reset! question-id (:id question-data))+ _ (call-tool session-id "update_question"+ {:id (:id question-data)+ :description "Smoke updated description"})dash-data (call-tool session-id "create_dashboard"- {:name "Smoke Dashboard"})]- (reset! dash-id (:id dash-data)))+ {:name "Smoke Dashboard"})+ _ (reset! dash-id (:id dash-data))+ _ (call-tool session-id "update_dashboard"+ {:id (:id dash-data)+ :description "Smoke updated dashboard"})+ coll-data (call-tool session-id "create_collection"+ {:name "Smoke Collection"})]+ (reset! coll-id (:id coll-data)))(finally(when-let [qid @question-id] (t2/delete! :model/Card :id qid))- (when-let [did @dash-id] (t2/delete! :model/Dashboard :id did)))))))))+ (when-let [did @dash-id] (t2/delete! :model/Dashboard :id did))+ (when-let [cid @coll-id] (t2/delete! :model/Collection :id cid)))))))))(deftest tools-call-visualize-query-direct-test(testing "visualize_query returns UI structured content"@@ -707,6 +676,135 @@:rows (fn [rows] (= 5 (count rows)))}}execute-data)))))))+(deftest tools-call-create-question-accepts-query-handle-test+ (testing "create_question resolves query_handle through the MCP layer instead of requiring raw base64"+ (let [[session-id _] (initialize!)+ db-name (t2/select-one-fn :name :model/Database (mt/id))+ construct-data (call-tool session-id "construct_query"+ {:query {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table [db-name "PUBLIC" "ORDERS"]+ :limit 5}]}})+ question-id (atom nil)]+ (try+ (let [question-data (call-tool session-id "create_question"+ {:name "Handle-Path Question"+ :query_handle (:query_handle construct-data)})]+ (reset! question-id (:id question-data))+ (is (pos-int? (:id question-data)))+ (is (= "Handle-Path Question" (:name question-data)))+ ;; Card was actually persisted with a dataset_query (handle resolved correctly).+ (is (some? (t2/select-one-fn :dataset_query :model/Card :id (:id question-data)))))+ (finally+ (when-let [qid @question-id] (t2/delete! :model/Card :id qid)))))))++(deftest tools-call-update-question-accepts-query-handle-test+ (testing "update_question resolves query_handle through the MCP layer"+ (mt/with-temp [:model/Card {card-id :id} {:name "Card To Re-query via Handle"+ :dataset_query (-> (lib/query (mt/metadata-provider)+ (lib.metadata/table (mt/metadata-provider)+ (mt/id :orders)))+ (lib/aggregate (lib/count)))+ :display :table}]+ (let [db-name (t2/select-one-fn :name :model/Database (mt/id))+ products-id (mt/id :products)+ products-fk [db-name "PUBLIC" "PRODUCTS"]+ [session-id _] (initialize!)+ construct-data (call-tool session-id "construct_query"+ {:query {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table products-fk+ :limit 5}]}})+ update-data (call-tool session-id "update_question"+ {:id card-id+ :query_handle (:query_handle construct-data)})+ persisted (t2/select-one-fn :dataset_query :model/Card :id card-id)+ persisted-table (some :source-table (:stages persisted))]+ (is (= card-id (:id update-data)))+ ;; Handle was resolved and applied to the card. Construct sends portable FKs over the+ ;; wire; the persisted dataset_query is the resolved MBQL 5 map with numeric IDs.+ (is (= products-id persisted-table)+ (str "Expected handle-resolved query's :source-table = products id " products-id+ ", got " persisted-table))))))++(deftest tools-call-update-question-stale-query-handle-test+ (testing "An unknown query_handle returns a tool-level error rather than 500"+ (mt/with-temp [:model/Card {card-id :id} {:name "Stale-Handle Target"+ :dataset_query (-> (lib/query (mt/metadata-provider)+ (lib.metadata/table (mt/metadata-provider)+ (mt/id :orders)))+ (lib/aggregate (lib/count)))+ :display :table}]+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "tools/call"+ {:name "update_question"+ :arguments {:id card-id+ :query_handle (str (random-uuid))}})+ {"mcp-session-id" session-id})+ result (get-in response [:body :result])]+ ;; JSON-RPC: HTTP 200, result.isError, friendly message.+ (is (= 200 (:status response)))+ (is (nil? (get-in response [:body :error])))+ (is (true? (:isError result)))+ (is (str/includes? (-> result :content first :text) "Query handle not found")+ "Stale handle should surface the dedicated message from mcp/tools.clj")+ ;; Card should be unchanged - still pointed at orders, not whatever the stale handle would have meant.+ (let [persisted (t2/select-one-fn :dataset_query :model/Card :id card-id)]+ (is (= (mt/id :orders) (some :source-table (:stages persisted)))+ "A stale handle must not mutate the card's source table."))))))++(deftest tools-call-update-dashboard-move-without-position-test+ (testing "Missing required field on a discriminated mutation surfaces as a tool error, not a JSON-RPC error"+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "MCP move validation"}+ :model/Card {card-id :id} {:name "x" :dataset_query (-> (lib/query (mt/metadata-provider)+ (lib.metadata/table (mt/metadata-provider)+ (mt/id :orders)))+ (lib/aggregate (lib/count)))+ :display :table}+ :model/DashboardCard {dc-id :id} {:dashboard_id dash-id :card_id card-id+ :row 0 :col 0 :size_x 6 :size_y 4}]+ (let [[session-id _] (initialize!)+ response (mcp-request (jsonrpc-request "tools/call"+ {:name "update_dashboard"+ :arguments {:id dash-id+ :dashcards [{:action "move" :dashcard_id dc-id}]}})+ {"mcp-session-id" session-id})+ result (get-in response [:body :result])]+ ;; JSON-RPC layer: HTTP 200, response in `result` not `error`. Bad-input is a tool-level error.+ (is (= 200 (:status response)))+ (is (nil? (get-in response [:body :error])))+ (is (true? (:isError result))+ "missing :position on move should surface as a tool error")))))++(deftest tools-call-read-resource-test+ (testing "read_resource returns the shared dispatcher's response shape"+ (let [[session-id _] (initialize!)+ result (call-tool session-id "read_resource"+ {:uris ["metabase://databases"]})]+ ;; `result` is the parsed MCP text-content JSON, which is the dispatcher's+ ;; full return map (`:resources` per-URI + formatted `:output` string).+ (is (sequential? (:resources result)))+ (is (= 1 (count (:resources result))))+ (is (= "metabase://databases" (-> result :resources first :uri)))+ (is (some? (-> result :resources first :content))+ "Top-level navigation URI must come back with :content (no :error)")+ (is (string? (:output result)))+ (is (str/includes? (:output result) "<resources>")+ "Output is XML-shaped for LLM consumption")))+ (testing "read_resource fetches a single-entity URI"+ (let [[session-id _] (initialize!)+ uri (str "metabase://table/" (mt/id :orders))+ result (call-tool session-id "read_resource" {:uris [uri]})]+ (is (= [uri] (mapv :uri (:resources result))))+ (is (some? (-> result :resources first :content)))))+ (testing "read_resource reports a per-URI error rather than failing the whole call"+ (let [[session-id _] (initialize!)+ result (call-tool session-id "read_resource"+ {:uris ["metabase://nonsense/path"]})]+ (is (= 1 (count (:resources result))))+ (is (nil? (-> result :resources first :content)))+ (is (some? (-> result :resources first :error))))))+;;; ----------------------------------------------- Drill Handles ---------------------------------------------------(deftest render-drill-through-publishes-its-own-resource-uri-test@@ -1083,7 +1181,7 @@;; Should include search (matches scope)(is (contains? tool-names "search"));; Should NOT include tools with other scopes- (is (not (contains? tool-names "get_table")))+ (is (not (contains? tool-names "update_question")))(is (not (contains? tool-names "construct_query")))))(testing "tools/list with wildcard scope matches all agent and UI tools"(let [tools (mcp.tools/list-tools #{"agent:*"})]@@ -1125,22 +1223,28 @@response)))))))(deftest tools-call-scope-enforcement-test- (testing "tool call is rejected when token scopes don't include the required scope"- (let [result (mt/with-current-user (mt/user->id :crowberto)- (mcp.tools/call-tool #{"agent:search"} nil "get_table" {:id (mt/id :orders)}))]- (is (=? {:isError true} result))- (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"} nil "get_table" {:id (mt/id :orders)}))]- (is (not (:isError result)))))- (testing "tool call with empty scopes is rejected for scoped tools"- (let [result (mt/with-current-user (mt/user->id :crowberto)- (mcp.tools/call-tool #{} nil "get_table" {:id (mt/id :orders)}))]- (is (=? {:isError true} result))- (is (str/includes? (-> result :content first :text) "Insufficient scope")- "Scope enforcement error from defendpoint middleware"))))+ (mt/with-temp [:model/Card {card-id :id} {:name "Scope Test Card"+ :dataset_query (orders-count-query)+ :display :table}]+ (testing "tool call is rejected when token scopes don't include the required scope"+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ (mcp.tools/call-tool #{"agent:search"} nil "update_question"+ {:id card-id :name "Renamed"}))]+ (is (=? {:isError true} result))+ (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:question:update"} nil "update_question"+ {:id card-id :name "Renamed Again"}))]+ (is (not (:isError result)))))+ (testing "tool call with empty scopes is rejected for scoped tools"+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ (mcp.tools/call-tool #{} nil "update_question"+ {:id card-id :name "Nope"}))]+ (is (=? {:isError true} result))+ (is (str/includes? (-> result :content first :text) "Insufficient scope")+ "Scope enforcement error from defendpoint middleware")))))(deftest check-resource-access-test(testing "returns :ok for a known URI with matching scope"@@ -1167,29 +1271,36 @@(deftest agent-api-preserves-token-scopes-test(testing "scoped token restrictions are enforced by the Agent API layer (defense-in-depth)"- (testing "restricted scopes that don't match the endpoint are rejected by Agent API"- (let [result (mt/with-current-user (mt/user->id :crowberto)- ;; Bypass the MCP scope check by calling invoke-agent-api directly- ;; with scopes that don't match the endpoint's required scope (agent:table:read)- (#'mcp.tools/invoke-agent-api :get (str "/v1/table/" (mt/id :orders)) #{"agent:search"} nil))]- (is (=? {:isError true} result)- "Agent API should reject when token scopes don't include the required scope")))- (testing "matching scopes are accepted by Agent API"- (let [result (mt/with-current-user (mt/user->id :crowberto)- (#'mcp.tools/invoke-agent-api :get (str "/v1/table/" (mt/id :orders)) #{"agent:table:read"} nil))]- (is (not (:isError result))- "Agent API should accept when token scopes include the required scope")))- (testing "unrestricted scopes are accepted by Agent API"- (let [result (mt/with-current-user (mt/user->id :crowberto)- (#'mcp.tools/invoke-agent-api :get (str "/v1/table/" (mt/id :orders)) #{::scope/unrestricted} nil))]- (is (not (:isError result))- "Agent API should accept unrestricted scopes")))))+ (mt/with-temp [:model/Card {card-id :id} {:name "Scope Probe Card"+ :dataset_query (orders-count-query)+ :display :table}]+ (testing "restricted scopes that don't match the endpoint are rejected by Agent API"+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ ;; Bypass the MCP scope check by calling invoke-agent-api directly+ ;; with scopes that don't match the endpoint's required scope (agent:question:update)+ (#'mcp.tools/invoke-agent-api :put (str "/v1/question/" card-id) #{"agent:search"}+ {:name "Probe"}))]+ (is (=? {:isError true} result)+ "Agent API should reject when token scopes don't include the required scope")))+ (testing "matching scopes are accepted by Agent API"+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ (#'mcp.tools/invoke-agent-api :put (str "/v1/question/" card-id) #{"agent:question:update"}+ {:name "Probe"}))]+ (is (not (:isError result))+ "Agent API should accept when token scopes include the required scope")))+ (testing "unrestricted scopes are accepted by Agent API"+ (let [result (mt/with-current-user (mt/user->id :crowberto)+ (#'mcp.tools/invoke-agent-api :put (str "/v1/question/" card-id) #{::scope/unrestricted}+ {:name "Probe"}))]+ (is (not (:isError result))+ "Agent API should accept unrestricted scopes"))))))(deftest mcp-does-not-depend-on-external-agent-api-setting-test(testing "MCP tool calls still work when the external Agent API is disabled"(mt/with-temporary-setting-values [agent-api.settings/agent-api-enabled? false](let [result (mt/with-current-user (mt/user->id :crowberto)- (mcp.tools/call-tool #{::scope/unrestricted} nil "get_table" {:id (mt/id :orders)}))]+ (mcp.tools/call-tool #{::scope/unrestricted} nil "read_resource"+ {:uris ["metabase://databases"]}))](is (not (:isError result)))))));;; ------------------------------------------------- Throttling ---------------------------------------------------diff --git a/test/metabase/metabot/scope_resolution_test.clj b/test/metabase/metabot/scope_resolution_test.cljindex 6d641c5e2cf..4b493909b5d 100644--- a/test/metabase/metabot/scope_resolution_test.clj+++ b/test/metabase/metabot/scope_resolution_test.clj@@ -17,15 +17,14 @@(is (not (contains? scopes "agent:viz:*"))))))(deftest user-metabot-perms-nql-scopes-test- (testing "nql :yes grants notebook, query, table, metric scopes"+ (testing "nql :yes grants notebook, query, question 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 (contains? scopes "agent:question:*"))(is (not (contains? scopes "agent:sql:*"))))))(deftest user-metabot-perms-other-tools-scopes-testdiff --git a/test/metabase/metabot/scope_test.clj b/test/metabase/metabot/scope_test.cljindex 413d494b3ed..4e6fccc7b36 100644--- a/test/metabase/metabot/scope_test.clj+++ b/test/metabase/metabot/scope_test.clj@@ -51,8 +51,7 @@(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:*"))))+ (is (contains? scopes "agent:question:*"))))(deftest ^:parallel perms->scopes-other-tools-test(let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-other-tools :yes})]@@ -113,6 +112,47 @@(testing "returns nil for unregistered scope"(is (nil? (api-scope/scope-description "agent:nonexistent:scope")))))+;;; ──────────────────────────────────────────────────────────────────+;;; New scopes added for MCP write tools+;;; ──────────────────────────────────────────────────────────────────++(deftest ^:parallel mcp-write-scopes-registered-test+ (testing "new MCP write-tool scopes are registered"+ (is (api-scope/registered-scope? "agent:question:update"))+ (is (api-scope/registered-scope? "agent:dashboard:update"))+ (is (api-scope/registered-scope? "agent:collection:create"))+ (is (api-scope/registered-scope? "agent:sql:execute"))))++(deftest ^:parallel mcp-write-scopes-defscope-vars-test+ (testing "new scope vars resolve to their string"+ (is (= "agent:question:update" scope/agent-question-update))+ (is (= "agent:dashboard:update" scope/agent-dashboard-update))+ (is (= "agent:collection:create" scope/agent-collection-create))+ (is (= "agent:sql:execute" scope/agent-sql-execute))))++(deftest ^:parallel mcp-write-scopes-granted-by-toggles-test+ (testing "agent:question:update granted via metabot-nlq wildcard"+ (let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-nlq :yes})]+ (is (api-scope/scope-matches? scopes "agent:question:update"))))+ (testing "agent:dashboard:update granted via metabot-other-tools wildcard"+ (let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-other-tools :yes})]+ (is (api-scope/scope-matches? scopes "agent:dashboard:update"))))+ (testing "agent:collection:create granted via new agent:collection:* wildcard under metabot-other-tools"+ (let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-other-tools :yes})]+ (is (contains? scopes "agent:collection:*"))+ (is (api-scope/scope-matches? scopes "agent:collection:create"))))+ (testing "agent:sql:execute granted via existing agent:sql:* wildcard under metabot-sql-generation"+ (let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-sql-generation :yes})]+ (is (api-scope/scope-matches? scopes "agent:sql:execute"))))+ (testing "MCP write scopes not granted when corresponding toggle is :no"+ (let [scopes (scope/user-metabot-perms->scopes {:permission/metabot-nlq :no+ :permission/metabot-other-tools :no+ :permission/metabot-sql-generation :no})]+ (is (not (api-scope/scope-matches? scopes "agent:question:update")))+ (is (not (api-scope/scope-matches? scopes "agent:dashboard:update")))+ (is (not (api-scope/scope-matches? scopes "agent:collection:create")))+ (is (not (api-scope/scope-matches? scopes "agent:sql:execute"))))))+;;; ──────────────────────────────────────────────────────────────────;;; parse-scopes;;; ──────────────────────────────────────────────────────────────────diff --git a/test_resources/serialization_baseline/settings.yaml b/test_resources/serialization_baseline/settings.yamlindex 92f02afead7..69506836068 100644--- a/test_resources/serialization_baseline/settings.yaml+++ b/test_resources/serialization_baseline/settings.yaml@@ -56,6 +56,7 @@ metabot-quota-reached-message: nullmetabot-show-illustrations: nullmetabot-sql-system-prompt: nullmcp-enabled?: null+mcp-execute-sql-enabled: nullnative-query-autocomplete-match-style: nullno-data-illustration: nullno-data-illustration-custom: null