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
database agent api (#71852)
Alexander Polyankin5034e186b71f
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.cljindex 5a2251ad331..5f72f6c41b1 100644--- a/src/metabase/agent_api/api.clj+++ b/src/metabase/agent_api/api.clj@@ -194,6 +194,14 @@[:data [:sequential ::search-result-item]][:total_count :int]])+(mr/def ::database+ "Details of a database, optionally including its tables."+ [:map {:encode/api #(update-keys % metabot.u/safe->snake_case_en)}+ [:id :int]+ [:name :string]+ [:engine :string]+ [:tables {:optional true} [:maybe [:sequential ::table]]]])+;;; --------------------------------------------------- Endpoints ----------------------------------------------------(api.macros/defendpoint :get "/v1/ping" :- [:map [:message :string]]@@ -202,6 +210,40 @@[]{:message "pong"})+(api.macros/defendpoint :get "/v1/database" :- [:sequential ::database]+ "List all databases the current user has access to."+ {:scope "agent:database:read"+ :tool {:name "list_databases"}}+ []+ (check-tool-result (entity-details/list-databases)))++(api.macros/defendpoint :get "/v1/database/:id" :- ::database+ "Get details for a database by ID."+ {:scope "agent:database:read"+ :tool {:name "get_database"}}+ [{:keys [id]} :- [:map [:id ms/PositiveInt]]+ {:keys [with-tables with-fields with-field-values with-related-tables with-metrics with-measures with-segments]+ :or {with-tables false, with-fields false, with-field-values false, with-related-tables false,+ with-metrics false, with-measures false, with-segments false}}+ :- [:map+ [:with-tables {:optional true} [:maybe :boolean]]+ [:with-fields {:optional true} [:maybe :boolean]]+ [:with-field-values {: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-database-details+ {:database-id id+ :with-tables? with-tables+ :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" :- ::table"Get details for a table by ID."{:scope metabot/agent-table-readdiff --git a/src/metabase/agent_api/reference.md b/src/metabase/agent_api/reference.mdindex cbb7ee5460f..ed1400da240 100644--- a/src/metabase/agent_api/reference.md+++ b/src/metabase/agent_api/reference.md@@ -9,6 +9,8 @@ Base path: /api/agent## Key concepts+- **Databases**: Data sources connected to Metabase. Use /v1/database to list+ them, and /v1/database/{id} to inspect a database's tables.- **Tables**: Database tables visible to the user.- **Metrics**: Standalone saved queries that represent pre-defined aggregations(e.g., "Total Revenue"). Metrics are stored in collections and can be used@@ -103,6 +105,73 @@ Health check.Response: `{"message": "pong"}`+### GET /v1/database++List all databases the current user has access to.++Response:++```json+[+ {+ "id": 1,+ "name": "Production DB",+ "engine": "postgres"+ }+]+```++### GET /v1/database/{id}++Get details for a database by ID, optionally including its tables.++Query parameters (all boolean, all optional):++| Parameter | Default | Description |+|---------------------|---------|-----------------------------------------|+| with-tables | false | Include tables in this database |+| with-fields | false | Include field metadata on each table |+| with-field-values | false | Include sample values on each field |+| with-related-tables | false | Include FK-related tables |+| with-metrics | false | Include metrics defined on each table |+| with-measures | false | Include measures on each table |+| with-segments | false | Include segments defined on each table |++Response (without tables):++```json+{+ "id": 1,+ "name": "Production DB",+ "engine": "postgres"+}+```++Response (with-tables=true):++```json+{+ "id": 1,+ "name": "Production DB",+ "engine": "postgres",+ "tables": [+ {+ "type": "table",+ "id": 42,+ "name": "ORDERS",+ "display_name": "Orders",+ "database_id": 1,+ "database_engine": "postgres",+ "database_schema": "PUBLIC",+ "fields": []+ }+ ]+}+```++When with-fields, with-metrics, etc. are enabled, each table in the response+follows the same shape as GET /v1/table/{id} with the corresponding options.+### GET /v1/table/{id}Get details for a table including fields, related tables, metrics, anddiff --git a/src/metabase/metabot/tools/entity_details.clj b/src/metabase/metabot/tools/entity_details.cljindex a5247aec92e..ca574ef5030 100644--- a/src/metabase/metabot/tools/entity_details.clj+++ b/src/metabase/metabot/tools/entity_details.clj@@ -394,6 +394,51 @@{:output (ex-message e) :status-code 404}(metabot.tools.u/handle-agent-error e)))))+(defn- database-details+ "Convert a Database model to the agent API response shape."+ [db]+ {:id (:id db)+ :name (:name db)+ :engine (some-> (:engine db) name)})++(defn list-databases+ "Get a list of all databases the current user can read without including its tables."+ []+ (try+ (let [dbs (metabot.tools.u/list-databases :name :engine)]+ {:structured-output (mapv database-details dbs)})+ (catch Exception e+ (metabot.tools.u/handle-agent-error e))))++(defn get-database-details+ "Get details for a database by ID, optionally including its tables."+ [{:keys [database-id with-tables? with-fields? with-field-values? with-related-tables?+ with-metrics? with-measures? with-segments?]+ :or {with-tables? false, with-fields? false, with-field-values? false, with-related-tables? false,+ with-metrics? false, with-measures? false, with-segments? false}}]+ (try+ (lib-be/with-metadata-provider-cache+ (let [db (metabot.tools.u/get-database database-id :name :engine)+ response (database-details db)]+ {:structured-output+ (cond-> response+ with-tables?+ (assoc :tables+ (let [mp (lib-be/application-database-metadata-provider database-id)+ tables (lib.metadata/tables mp)+ opts (cond-> {:metadata-provider mp+ :with-fields? with-fields?+ :with-related-tables? with-related-tables?+ :with-metrics? with-metrics?+ :with-measures? with-measures?+ :with-segments? with-segments?}+ (not with-field-values?) (assoc :field-values-fn identity))]+ (mapv #(table-details (:id %) opts) tables))))}))+ (catch Exception e+ (if (= (:status-code (ex-data e)) 404)+ {:output (ex-message e) :status-code 404}+ (metabot.tools.u/handle-agent-error e)))))+(defn get-metric-details"Get information about the metric with ID `metric-id`."[{:keys [metric-id] :as arguments}]diff --git a/src/metabase/metabot/tools/util.clj b/src/metabase/metabot/tools/util.cljindex 2492b3a7e26..cf03039067e 100644--- a/src/metabase/metabot/tools/util.clj+++ b/src/metabase/metabot/tools/util.clj@@ -8,6 +8,7 @@[metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]+ [metabase.models.interface :as mi][metabase.premium-features.core :as premium-features][metabase.util :as u][metabase.util.log :as log]@@ -166,6 +167,12 @@(-> (t2/select-one (into [:model/Database :id] fields) id)api/read-check))+(defn list-databases+ "Get all databases the current user can read, ordered by name."+ [& fields]+ (->> (t2/select (into [:model/Database :id] fields) {:order-by [[:name :asc]]})+ (filterv mi/can-read?)))+(defn get-table"Get the `fields` of the table with ID `id`."[id & fields]diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex d44300594c1..d3886196c5e 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -150,6 +150,59 @@(is (not (contains? (get by-name "id") :effective_type)))(is (not (contains? (get by-name "name") :effective_type))))))))+(deftest list-databases-test+ (testing "Returns a list of databases"+ ;; Reference a table to ensure the test database exists+ (let [_ (mt/id :orders)]+ (is (=? [{:id (mt/id)+ :name "test-data (h2)"+ :engine "h2"}]+ (mt/user-http-request :crowberto :get 200 "agent/v1/database")))))++ (testing "User without data permissions gets empty list"+ (mt/with-no-data-perms-for-all-users!+ (is (= [] (mt/user-http-request :rasta :get 200 "agent/v1/database"))))))++(deftest get-database-details-test+ (testing "Returns database details"+ (is (=? {:id (mt/id)+ :name "test-data (h2)"+ :engine "h2"}+ (mt/user-http-request :rasta :get 200 (str "agent/v1/database/" (mt/id))))))++ (testing "Returns 404 for non-existent database"+ (is (= "Not found."+ (mt/user-http-request :rasta :get 404 "agent/v1/database/999999"))))++ (testing "Tables are included when requested"+ (let [response (mt/user-http-request :rasta :get 200+ (str "agent/v1/database/" (mt/id) "?with-tables=true"))+ orders (m/find-first #(= (mt/id :orders) (:id %)) (:tables response))]+ (is (=? {:id (mt/id :orders)+ :type "table"+ :name "ORDERS"+ :display_name "Orders"+ :database_id (mt/id)}+ orders))))++ (testing "Tables include fields when requested"+ (let [response (mt/user-http-request :rasta :get 200+ (str "agent/v1/database/" (mt/id) "?with-tables=true&with-fields=true"))+ orders (m/find-first #(= (mt/id :orders) (:id %)) (:tables response))+ total (m/find-first #(= (str (metabot.tools.u/table-field-id-prefix (mt/id :orders)) 5)+ (:field_id %))+ (:fields orders))]+ (is (=? {:field_id (str (metabot.tools.u/table-field-id-prefix (mt/id :orders)) 5)+ :name "TOTAL"+ :display_name "Total"+ :base_type "type/Float"+ :database_type "DOUBLE PRECISION"}+ total))))++ (testing "User without data permissions gets 403"+ (mt/with-no-data-perms-for-all-users!+ (mt/user-http-request :rasta :get 403 (str "agent/v1/database/" (mt/id))))))+(deftest get-metric-details-test(mt/with-temp [:model/Card metric {:name "Test Metric":type :metric