The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Add pagination to read_resource (#74966)
lbrdnk928e9098e24d
diff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.cljindex c676af61a0a..e082e44cfb2 100644--- a/src/metabase/metabot/tools/resources.clj+++ b/src/metabase/metabot/tools/resources.clj@@ -17,6 +17,11 @@- metabase://collections?tree=true - flat list of all collections (hierarchy via :location)- metabase://user/recent-items - current user's recent items+ Pagination:+ List responses are capped at page-size items per page. When :truncated is true, use ?page=N to+ fetch subsequent pages, e.g. metabase://database/1/tables?page=2. The response includes+ :page (current, 1-indexed) and :pages (total).+Database drill-down:- metabase://database/{id} - one database- metabase://database/{id}/tables - tables in the database@@ -73,31 +78,43 @@"Maximum number of URIs that can be fetched in a single call."5)-(def ^:private max-list-items- "Maximum number of items returned in a single list response. When exceeded the response- includes :truncated true and :total so the agent knows there are more items it can drill into."+(def ^:private page-size+ "Page size for list responses."25)-(defn- truncate-list- "Cap a sequence of items at `max-list-items`, returning {:items :total :truncated}."- [items]+(defn- paginate-list+ "Return one page of items. `page-str` is a 1-indexed string (from a URI query param), defaults to 1.+ Page size is always `page-size`. Throws if `page-str` parses to a page number outside [1, pages]+ rather than silently clamping, so a caller (the agent) finds out it passed a bad value."+ [items page-str](let [items (vec items)- total (count items)]- {:items (vec (take max-list-items items))- :total total- :truncated (> total max-list-items)}))+ total (count items)+ pages (max 1 (int (Math/ceil (/ (double total) page-size))))+ page (or (some-> page-str parse-long) 1)+ _ (when (or (< page 1) (> page pages))+ (throw (ex-info (str "Invalid page " page ". This list has " pages+ (if (= pages 1) " page." " pages."))+ {:page page :pages pages})))+ start (* (dec page) page-size)]+ {:items (vec (take page-size (drop start items)))+ :total total+ :page page+ :pages pages}))(defn- list-result"Build a structured-output map for a list of items.- `list-type` is a keyword like :databases, :collection-items, :recents, etc."- [list-type items]- (let [{:keys [items total truncated]} (truncate-list items)]- {:structured-output- {:result-type :metabot-list- :list-type list-type- :items items- :total total- :truncated truncated}}))+ `list-type` is a keyword like :databases, :collection-items, :recents, etc.+ `query-params` is the parsed URI query-param map; `:page` selects the page (1-indexed string)."+ ([list-type items] (list-result list-type items nil))+ ([list-type items query-params]+ (let [{:keys [items total page pages]} (paginate-list items (:page query-params))]+ {:structured-output+ {:result-type :metabot-list+ :list-type list-type+ :items items+ :total total+ :page page+ :pages pages}})))(defn- entity-result"Build a structured-output map for a single entity (databases, collections, etc.)."@@ -247,17 +264,17 @@;; ----- Fetch handlers (one per URI shape) ------(defn- fetch-databases-list []+(defn- fetch-databases-list [query-params](let [dbs (->> (t2/select [:model/Database :id :name :engine :description :is_audit]:is_audit false{:order-by [[:%lower.name :asc]]})(filter mi/can-read?)(mapv present-database))]- (list-result :databases dbs)))+ (list-result :databases dbs query-params)))(defn- fetch-collections-list"metabase://collections (root only) and metabase://collections?tree=true (flat list of all)."- [{:keys [tree] :as _query-params}]+ [{:keys [tree] :as query-params}](let [tree? (= "true" tree)where (cond-> [:and[:= :archived false]@@ -280,8 +297,14 @@path-of (fn [coll](str/join "/" (concat (keep id->name (ancestors coll))[(:name coll)])))- items (mapv (fn [c] (present-collection c (when tree? (path-of c)))) colls)]- (list-result (if tree? :collections-tree :collections-root) items)))+ ;; Build items and, for tree mode, re-sort by computed path name.+ ;; The DB ORDER BY location ASC sorts path strings lexicographically — "/10/" sorts+ ;; before "/2/", interleaving children of high-ID parents incorrectly. Sorting by+ ;; the human-readable path ("Analytics/Reports") is stable and groups children+ ;; directly under their parents.+ items (cond-> (mapv (fn [c] (present-collection c (when tree? (path-of c)))) colls)+ tree? (->> (sort-by :path) vec))]+ (list-result (if tree? :collections-tree :collections-root) items query-params)))(defn- fetch-user-recents [](let [recents (or (-> (activity-feed/get-recents api/*current-user-id* [:views])@@ -306,7 +329,7 @@(let [db (api/read-check :model/Database (parse-long id-str))](entity-result (present-database db))))-(defn- fetch-database-tables [id-str]+(defn- fetch-database-tables [id-str query-params](let [db-id (parse-long id-str)_ (api/read-check :model/Database db-id)tables (->> (t2/select [:model/Table :id :name :display_name :schema :db_id :description]@@ -315,9 +338,9 @@{:order-by [[:%lower.schema :asc] [:%lower.name :asc]]})(filter mi/can-read?)(mapv present-table))]- (list-result :database-tables tables)))+ (list-result :database-tables tables query-params)))-(defn- fetch-database-models [id-str]+(defn- fetch-database-models [id-str query-params](let [db-id (parse-long id-str)_ (api/read-check :model/Database db-id)models (->> (t2/select [:model/Card :id :name :type :description :card_schema@@ -328,9 +351,9 @@{:order-by [[:%lower.name :asc]]})(filter mi/can-read?)(mapv present-card))]- (list-result :database-models models)))+ (list-result :database-models models query-params)))-(defn- fetch-database-schemas [id-str]+(defn- fetch-database-schemas [id-str query-params](let [db-id (parse-long id-str)_ (api/read-check :model/Database db-id)rows (t2/query@@ -345,9 +368,9 @@:name s:database_id db-id:uri (llm-shape/metabase-uri :database db-id "schemas" s "tables")})))]- (list-result :database-schemas schemas)))+ (list-result :database-schemas schemas query-params)))-(defn- fetch-database-schema-tables [id-str schema-name]+(defn- fetch-database-schema-tables [id-str schema-name query-params](let [db-id (parse-long id-str)_ (api/read-check :model/Database db-id)tables (->> (t2/select [:model/Table :id :name :display_name :schema :db_id :description]@@ -357,7 +380,7 @@{:order-by [[:%lower.name :asc]]})(filter mi/can-read?)(mapv present-table))]- (list-result :database-schema-tables tables)))+ (list-result :database-schema-tables tables query-params)));; ----- Collection drill-down -----@@ -365,7 +388,7 @@(let [coll (api/read-check :model/Collection (parse-long id-str))](entity-result (present-collection coll))))-(defn- fetch-collection-items [id-str]+(defn- fetch-collection-items [id-str query-params](let [coll-id (parse-long id-str)coll (api/read-check :model/Collection coll-id)cards (->> (t2/select [:model/Card :id :name :type :description :card_schema@@ -387,9 +410,9 @@items (concat (map present-collection subcollections)(map present-card cards)(map present-dashboard dashboards))]- (list-result :collection-items items)))+ (list-result :collection-items items query-params)))-(defn- fetch-collection-subcollections [id-str]+(defn- fetch-collection-subcollections [id-str query-params](let [coll-id (parse-long id-str)coll (api/read-check :model/Collection coll-id)subs (->> (t2/select [:model/Collection :id :name :location :authority_level@@ -399,7 +422,7 @@{:order-by [[:%lower.name :asc]]})(filter mi/can-read?)(mapv present-collection))]- (list-result :collection-subcollections subs)))+ (list-result :collection-subcollections subs query-params)));; ----- Table -----@@ -427,7 +450,7 @@:field-id field-id:limit 30}))-(defn- fetch-table-derived [id-str]+(defn- fetch-table-derived [id-str query-params](let [table-id (parse-long id-str)table (api/read-check :model/Table table-id)db-id (:db_id table)@@ -450,7 +473,7 @@(filter (fn [t] (some #{table-id} (transform-source-table-ids t))))(filter mi/can-read?)(mapv present-transform)))]- (list-result :table-derived (concat cards transforms))))+ (list-result :table-derived (concat cards transforms) query-params)));; ----- Card (model / question) -----@@ -536,7 +559,7 @@{:structured-output (assoc dashboard :result-type :entity)}{:status-code 404 :output (:output result)})))-(defn- fetch-dashboard-items [id-str]+(defn- fetch-dashboard-items [id-str query-params](let [dashboard-id (parse-long id-str)_ (api/read-check :model/Dashboard dashboard-id)cards (->> (t2/select [:model/Card :id :name :type :description :card_schema@@ -551,7 +574,7 @@:order-by [[:%lower.name :asc]]})(filter mi/can-read?)(mapv present-card))]- (list-result :dashboard-items cards)))+ (list-result :dashboard-items cards query-params)));; ----- Dispatch -----@@ -565,27 +588,27 @@(let [{:keys [segments query-params]} (parse-uri uri)](match/match-one segments;; Navigation- ["databases"] (fetch-databases-list)+ ["databases"] (fetch-databases-list query-params)["collections"] (fetch-collections-list query-params)["user" "recent-items"] (fetch-user-recents);; Database drill-down["database" id] (fetch-database id)- ["database" id "tables"] (fetch-database-tables id)- ["database" id "models"] (fetch-database-models id)- ["database" id "schemas"] (fetch-database-schemas id)- ["database" id "schemas" schema "tables"] (fetch-database-schema-tables id schema)+ ["database" id "tables"] (fetch-database-tables id query-params)+ ["database" id "models"] (fetch-database-models id query-params)+ ["database" id "schemas"] (fetch-database-schemas id query-params)+ ["database" id "schemas" schema "tables"] (fetch-database-schema-tables id schema query-params);; Collection drill-down["collection" id] (fetch-collection id)- ["collection" id "items"] (fetch-collection-items id)- ["collection" id "subcollections"] (fetch-collection-subcollections id)+ ["collection" id "items"] (fetch-collection-items id query-params)+ ["collection" id "subcollections"] (fetch-collection-subcollections id query-params);; Table["table" id] (fetch-table id)["table" id "fields"] (fetch-table-fields id)["table" id "fields" & rst] (fetch-table-field id (str/join "/" rst))- ["table" id "derived"] (fetch-table-derived id)+ ["table" id "derived"] (fetch-table-derived id query-params);; Card (model / question — share handlers, dispatch on the type segment)[(t :guard #{"model" "question"}) id] (fetch-card t id)@@ -605,7 +628,7 @@;; Dashboard["dashboard" id] (fetch-dashboard id)- ["dashboard" id "items"] (fetch-dashboard-items id)+ ["dashboard" id "items"] (fetch-dashboard-items id query-params);; Default — required to make match non-recursive_ (throw (ex-info (str "Unsupported URI: " uri)@@ -701,8 +724,9 @@the instance and drill into specific entities. URIs returned by `search` and otherread_resource calls can be fed directly back here.- Up to 5 URIs may be requested in one call. List responses are capped at 25 items; if- truncated, drill into individual items via their URIs or refine via `search`.+ Up to 5 URIs may be requested in one call. List responses are capped at 25 items per page.+ When :truncated is true, append ?page=N to fetch the next page (e.g. metabase://database/1/tables?page=2).+ The response includes :page (current, 1-indexed) and :pages (total page count).NAVIGATION (top-level lists):- metabase://databases - all databasesdiff --git a/src/metabase/metabot/tools/shared/llm_shape.clj b/src/metabase/metabot/tools/shared/llm_shape.cljindex 3b13cddeb8f..35733ef1a12 100644--- a/src/metabase/metabot/tools/shared/llm_shape.clj+++ b/src/metabase/metabot/tools/shared/llm_shape.clj@@ -808,22 +808,25 @@{:list-type :databases ; keyword, becomes the type attribute:items [{:type \"database\" :id 1 :name \"Sample\" :uri \"...\" :description \"...\"} ...]:total 5- :truncated false}+ :page 1+ :pages 1}Output shape:- <list type=\"databases\" total=\"5\" truncated=\"false\">+ <list type=\"databases\" total=\"5\" page=\"1\" pages=\"1\" showing=\"5\" truncated=\"false\"><item type=\"database\" id=\"1\" name=\"Sample\" uri=\"metabase://database/1\">Description</item>...</list>"- [{:keys [list-type items total truncated]}]+ [{:keys [list-type items total page pages]}](let [type-attr (clojure.core/name (or list-type :items))item-xml (str/join "\n" (map list-item->xml items))showing (count items)+ truncated (< page pages)note (when truncated- (str "<truncation-note>Showing " showing " of " total ". "- "More items exist — read individual items via their URIs above "- "or refine via search.</truncation-note>"))]+ (str "<truncation-note>Page " page " of " pages " (" showing " of " total " items). "+ "Append ?page=" (inc page) " to the URI to fetch the next page.</truncation-note>"))](str "<list type=\"" type-attr "\" total=\"" total+ "\" page=\"" (or page 1)+ "\" pages=\"" (or pages 1)"\" showing=\"" showing"\" truncated=\"" (boolean truncated) "\">\n"(when (seq items) (str item-xml "\n"))diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.cljindex 487cb930ed6..9fe0e35095e 100644--- a/test/metabase/metabot/tools/resources_test.clj+++ b/test/metabase/metabot/tools/resources_test.clj@@ -78,28 +78,32 @@to the dispatch should mean adding one row here. Args are positional and string-typedthe way the dispatch passes them to the handler."[;; ----- Top-level navigation ------ ["metabase://databases" :databases-list []]+ ["metabase://databases" :databases-list [nil]]+ ["metabase://databases?page=2" :databases-list [{:page "2"}]]["metabase://collections" :collections-list [nil]]["metabase://collections?tree=true" :collections-list [{:tree "true"}]]["metabase://collections?tree=true&foo=bar" :collections-list [{:tree "true" :foo "bar"}]]+ ["metabase://collections?page=2" :collections-list [{:page "2"}]]["metabase://user/recent-items" :user-recents []];; ----- Database drill-down -----["metabase://database/1" :database ["1"]]- ["metabase://database/1/tables" :database-tables ["1"]]- ["metabase://database/1/models" :database-models ["1"]]- ["metabase://database/1/schemas" :database-schemas ["1"]]- ["metabase://database/1/schemas/PUBLIC/tables" :database-schema-tables ["1" "PUBLIC"]]- ["metabase://database/1/schemas/lower_case/tables" :database-schema-tables ["1" "lower_case"]]+ ["metabase://database/1/tables" :database-tables ["1" nil]]+ ["metabase://database/1/tables?page=2" :database-tables ["1" {:page "2"}]]+ ["metabase://database/1/models" :database-models ["1" nil]]+ ["metabase://database/1/schemas" :database-schemas ["1" nil]]+ ["metabase://database/1/schemas/PUBLIC/tables" :database-schema-tables ["1" "PUBLIC" nil]]+ ["metabase://database/1/schemas/lower_case/tables" :database-schema-tables ["1" "lower_case" nil]];; ----- Collection drill-down -----["metabase://collection/2" :collection ["2"]]- ["metabase://collection/2/items" :collection-items ["2"]]- ["metabase://collection/2/subcollections" :collection-subcollections ["2"]]+ ["metabase://collection/2/items" :collection-items ["2" nil]]+ ["metabase://collection/2/items?page=3" :collection-items ["2" {:page "3"}]]+ ["metabase://collection/2/subcollections" :collection-subcollections ["2" nil]];; ----- Table -----["metabase://table/3" :table ["3"]]["metabase://table/3/fields" :table-fields ["3"]]["metabase://table/3/fields/42" :table-field ["3" "42"]]["metabase://table/3/fields/c75/17" :table-field ["3" "c75/17"]]- ["metabase://table/3/derived" :table-derived ["3"]]+ ["metabase://table/3/derived" :table-derived ["3" nil]];; ----- Model (a card type) -----["metabase://model/4" :card ["model" "4"]]["metabase://model/4/fields" :card-fields ["model" "4"]]@@ -121,7 +125,8 @@["metabase://transform/7/target" :transform-target ["7"]];; ----- Dashboard -----["metabase://dashboard/8" :dashboard ["8"]]- ["metabase://dashboard/8/items" :dashboard-items ["8"]]])+ ["metabase://dashboard/8/items" :dashboard-items ["8" nil]]+ ["metabase://dashboard/8/items?page=2" :dashboard-items ["8" {:page "2"}]]])(deftest dispatch-routing-test(testing "every supported URI pattern routes to the expected handler with the expected args"@@ -582,11 +587,13 @@(is (str/includes? output "<list type=\"recent-items\""))))))(deftest read-list-shape-test- (testing "list responses always carry total/showing/truncated attrs in the rendered XML"+ (testing "list responses carry total/page/pages/showing/truncated attrs in the rendered XML"(mt/with-current-user (mt/user->id :crowberto)(let [{:keys [output]} (read-resource/read-resource {:uris ["metabase://databases"]})](is (str/includes? output "<list type=\"databases\""))(is (str/includes? output "total="))+ (is (str/includes? output "page="))+ (is (str/includes? output "pages="))(is (str/includes? output "showing="))(is (str/includes? output "truncated="))))))@@ -749,3 +756,112 @@(is (=? {:fields [{:display_name "Category"}{:display_name "Count"}]}structured))))))))++;; ===== Pagination =====++(deftest paginate-list-test+ (testing "page 1 returns first 25 items"+ (let [items (mapv (fn [i] {:id i}) (range 1 51))+ result (#'read-resource/paginate-list items nil)]+ (is (= 1 (:page result)))+ (is (= 2 (:pages result)))+ (is (= 50 (:total result)))+ (is (= 25 (count (:items result))))+ (is (= 1 (-> result :items first :id)))+ (is (= 25 (-> result :items last :id)))))+ (testing "page 2 returns second 25 items"+ (let [items (mapv (fn [i] {:id i}) (range 1 51))+ result (#'read-resource/paginate-list items "2")]+ (is (= 2 (:page result)))+ (is (= 26 (-> result :items first :id)))+ (is (= 50 (-> result :items last :id)))))+ (testing "out-of-range page throws instead of clamping"+ (let [items (mapv (fn [i] {:id i}) (range 1 11))]+ (is (thrown-with-msg? Exception #"Invalid page 999\. This list has 1 page\."+ (#'read-resource/paginate-list items "999")))+ (is (thrown-with-msg? Exception #"Invalid page 0\. This list has 1 page\."+ (#'read-resource/paginate-list items "0")))+ (is (thrown-with-msg? Exception #"Invalid page -3\. This list has 1 page\."+ (#'read-resource/paginate-list items "-3")))))+ (testing "list shorter than one page"+ (let [items (mapv (fn [i] {:id i}) (range 1 6))+ result (#'read-resource/paginate-list items nil)]+ (is (= 1 (:page result)))+ (is (= 1 (:pages result)))+ (is (= 5 (:total result)))))+ (testing "empty list"+ (let [result (#'read-resource/paginate-list [] nil)]+ (is (= 1 (:page result)))+ (is (= 1 (:pages result)))+ (is (= 0 (:total result))))))++(deftest pagination-database-tables-test+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Database {db-id :id} {}]+ (doseq [i (range 1 31)]+ (t2/insert! :model/Table {:name (format "TABLE-%03d" i)+ :db_id db-id+ :active true}))+ (testing "page 1 returns first 25 tables, with page/pages metadata"+ (let [result (read-resource/read-resource+ {:uris [(str "metabase://database/" db-id "/tables")]})+ so (get-in result [:resources 0 :content :structured-output])]+ (is (= 1 (:page so)))+ (is (= 2 (:pages so)))+ (is (= 30 (:total so)))+ (is (= 25 (count (:items so))))))+ (testing "page 2 returns remaining 5 tables"+ (let [result (read-resource/read-resource+ {:uris [(str "metabase://database/" db-id "/tables?page=2")]})+ so (get-in result [:resources 0 :content :structured-output])]+ (is (= 2 (:page so)))+ (is (= 5 (count (:items so))))))+ (testing "out-of-range page surfaces as a resource error, not an uncaught exception"+ (let [result (read-resource/read-resource+ {:uris [(str "metabase://database/" db-id "/tables?page=999")]})]+ (is (=? {:resources [{:error string?}]} result)))))))++(deftest pagination-xml-output-test+ (testing "truncated list XML includes page/pages attrs and a truncation note with next-page URI hint"+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Database {db-id :id} {}]+ (doseq [i (range 1 31)]+ (t2/insert! :model/Table {:name (format "TBL-%03d" i)+ :db_id db-id+ :active true}))+ (let [{:keys [output]} (read-resource/read-resource+ {:uris [(str "metabase://database/" db-id "/tables")]})]+ (is (str/includes? output "page=\"1\""))+ (is (str/includes? output "pages=\"2\""))+ (is (str/includes? output "truncated=\"true\""))+ (is (str/includes? output "?page=2") "truncation note should hint at next page URI"))))))++;; ===== Collection tree ordering =====++(deftest collections-tree-ordering-test+ (testing "tree mode sorts by path name, not by raw location string (which would mis-order multi-digit IDs)"+ (mt/with-current-user (mt/user->id :crowberto)+ ;; Create roots whose IDs will cause lexicographic location-sort to diverge from+ ;; alphabetical path-sort: a root with a high numeric ID gets a child whose+ ;; location (/10/) would sort before the child of a lower-ID root (/2/).+ ;; After the fix, children are sorted by their human-readable path.+ (mt/with-temp+ [:model/Collection {z-root :id} {:name "Z-Root" :location "/"}+ :model/Collection {a-root :id} {:name "A-Root" :location "/"}+ :model/Collection _ {:name "Z-Child" :location (str "/" z-root "/")}+ :model/Collection _ {:name "A-Child" :location (str "/" a-root "/")}]+ (let [result (read-resource/read-resource {:uris ["metabase://collections?tree=true"]})+ so (get-in result [:resources 0 :content :structured-output])+ paths (mapv :path (:items so))]+ (testing "A-Root and its child appear before Z-Root and its child"+ (let [first-a (first (keep-indexed (fn [i p] (when (str/starts-with? p "A-Root") i)) paths))+ first-z (first (keep-indexed (fn [i p] (when (str/starts-with? p "Z-Root") i)) paths))]+ (is (some? first-a))+ (is (some? first-z))+ (is (< first-a first-z) "A-Root subtree must come before Z-Root subtree")))+ (testing "A-Root/A-Child appears immediately after A-Root"+ (let [a-root-idx (first (keep-indexed (fn [i p] (when (= "A-Root" p) i)) paths))+ a-child-idx (first (keep-indexed (fn [i p] (when (= "A-Root/A-Child" p) i)) paths))]+ (is (some? a-root-idx))+ (is (some? a-child-idx))+ (is (= (inc a-root-idx) a-child-idx) "child should immediately follow its parent"))))))))