The personal finance app for everyone (by everyone)
Ruby
feat(mcp): add pagination to get_tags and get_categories tools (#2492)
Blaž Dular37301e15ae0c
diff --git a/app/models/assistant/function/get_categories.rb b/app/models/assistant/function/get_categories.rbindex f7bf643d86..57e39b0899 100644--- a/app/models/assistant/function/get_categories.rb+++ b/app/models/assistant/function/get_categories.rb@@ -1,22 +1,49 @@class Assistant::Function::GetCategories < Assistant::Functionclass << self+ def default_page_size+ 50+ end+def name"get_categories"enddef description<<~INSTRUCTIONS- Returns all categories for the user's family, ordered alphabetically by hierarchy.+ Returns categories for the user's family, ordered alphabetically by hierarchy, with pagination.Each entry includes id, name, color, icon, parent_id (null for top-level), andname_with_parent (e.g. "Food & Drink > Restaurants"). Use this before creatingsubcategories or referencing a category by id in update_category.++ Note on pagination:++ This function can be paginated. You can expect the following properties in the response:++ - `total_pages`: The total number of pages of results+ - `page`: The current page of results+ - `page_size`: The number of results per page (this will always be #{default_page_size})+ - `total_results`: The total number of resultsINSTRUCTIONSendend+ def params_schema+ build_schema(+ required: [],+ properties: {+ page: {+ type: "integer",+ description: "Page number (defaults to 1)"+ }+ }+ )+ end+def call(params = {})- categories = family.categories.alphabetically_by_hierarchy+ categories_scope = family.categories.alphabetically_by_hierarchy+ pagy = Pagy.new(count: categories_scope.count, page: params["page"] || 1, limit: default_page_size)+ categories = categories_scope.offset(pagy.offset).limit(pagy.limit){categories: categories.map { |c|@@ -30,7 +57,15 @@ class Assistant::Function::GetCategories < Assistant::Functionis_subcategory: c.subcategory?}},- total: categories.size+ total_results: pagy.count,+ page: pagy.page,+ page_size: default_page_size,+ total_pages: pagy.pages}end++ private+ def default_page_size+ self.class.default_page_size+ endenddiff --git a/app/models/assistant/function/get_holdings.rb b/app/models/assistant/function/get_holdings.rbindex d0025fb54d..c65769eb71 100644--- a/app/models/assistant/function/get_holdings.rb+++ b/app/models/assistant/function/get_holdings.rb@@ -1,6 +1,4 @@class Assistant::Function::GetHoldings < Assistant::Function- include Pagy::Backend-SUPPORTED_ACCOUNT_TYPES = %w[Investment Crypto].freezeclass << self@@ -87,11 +85,9 @@ class Assistant::Function::GetHoldings < Assistant::Functiondef call(params = {})holdings_query = build_holdings_query(params)- pagy, paginated_holdings = pagy(- holdings_query.includes(:security, :account).order(amount: :desc),- page: params["page"] || 1,- limit: default_page_size- )+ ordered_holdings = holdings_query.order(amount: :desc)+ pagy = Pagy.new(count: ordered_holdings.count, page: params["page"] || 1, limit: default_page_size)+ paginated_holdings = ordered_holdings.includes(:security, :account).offset(pagy.offset).limit(pagy.limit)total_value = holdings_query.sum(:amount)diff --git a/app/models/assistant/function/get_tags.rb b/app/models/assistant/function/get_tags.rbindex b4dfdcd98d..7fd1d74b8f 100644--- a/app/models/assistant/function/get_tags.rb+++ b/app/models/assistant/function/get_tags.rb@@ -1,25 +1,60 @@class Assistant::Function::GetTags < Assistant::Functionclass << self+ def default_page_size+ 50+ end+def name"get_tags"enddef description<<~INSTRUCTIONS- Returns all tags defined for the user's family, sorted alphabetically.+ Returns tags defined for the user's family, sorted alphabetically, with pagination.Use this when the user wants to see available tags or before referencinga tag in another operation like create_tag or update_tag.++ Note on pagination:++ This function can be paginated. You can expect the following properties in the response:++ - `total_pages`: The total number of pages of results+ - `page`: The current page of results+ - `page_size`: The number of results per page (this will always be #{default_page_size})+ - `total_results`: The total number of resultsINSTRUCTIONSendend+ def params_schema+ build_schema(+ required: [],+ properties: {+ page: {+ type: "integer",+ description: "Page number (defaults to 1)"+ }+ }+ )+ end+def call(params = {})- tags = family.tags.alphabetically+ tags_scope = family.tags.alphabetically+ pagy = Pagy.new(count: tags_scope.count, page: params["page"] || 1, limit: default_page_size)+ tags = tags_scope.offset(pagy.offset).limit(pagy.limit){tags: tags.map { |t| { id: t.id, name: t.name, color: t.color } },- total: tags.size+ total_results: pagy.count,+ page: pagy.page,+ page_size: default_page_size,+ total_pages: pagy.pages}end++ private+ def default_page_size+ self.class.default_page_size+ endenddiff --git a/app/models/assistant/function/get_transactions.rb b/app/models/assistant/function/get_transactions.rbindex 93cba63c8f..ec6a9ce4c4 100644--- a/app/models/assistant/function/get_transactions.rb+++ b/app/models/assistant/function/get_transactions.rb@@ -1,6 +1,4 @@class Assistant::Function::GetTransactions < Assistant::Function- include Pagy::Backend-class << selfdef default_page_size50@@ -143,16 +141,13 @@ class Assistant::Function::GetTransactions < Assistant::Functionpagy_query = params["order"] == "asc" ? transactions_query.chronological : transactions_query.reverse_chronological# By default, we give a small page size to force the AI to use filters effectively and save on tokens- pagy, paginated_transactions = pagy(- pagy_query.includes(- { entry: :account },- :category, :merchant, :tags,- transfer_as_outflow: { inflow_transaction: { entry: :account } },- transfer_as_inflow: { outflow_transaction: { entry: :account } }- ),- page: params["page"] || 1,- limit: default_page_size- )+ pagy = Pagy.new(count: pagy_query.count, page: params["page"] || 1, limit: default_page_size)+ paginated_transactions = pagy_query.includes(+ { entry: :account },+ :category, :merchant, :tags,+ transfer_as_outflow: { inflow_transaction: { entry: :account } },+ transfer_as_inflow: { outflow_transaction: { entry: :account } }+ ).offset(pagy.offset).limit(pagy.limit)totals = search.totalsdiff --git a/app/models/category.rb b/app/models/category.rbindex d57a8905e5..89163f24aa 100644--- a/app/models/category.rb+++ b/app/models/category.rb@@ -26,7 +26,7 @@ class Category < ApplicationRecordleft_joins(:parent).order(Arel.sql("COALESCE(parents_categories.name, categories.name)")).order(Arel.sql("parents_categories.name IS NOT NULL"))- .order(:name)+ .order(:name, :id)}scope :roots, -> { where(parent_id: nil) }# Legacy scopes - classification removed; these now return all categoriesdiff --git a/app/models/tag.rb b/app/models/tag.rbindex 108e1c89c0..388dbc9809 100644--- a/app/models/tag.rb+++ b/app/models/tag.rb@@ -7,7 +7,7 @@ class Tag < ApplicationRecordvalidates :name, presence: true, uniqueness: { scope: :family }validates :color, format: { with: /\A#[0-9A-Fa-f]{6}\z/ }, allow_nil: true- scope :alphabetically, -> { order(:name) }+ scope :alphabetically, -> { order(:name, :id) }COLORS = %w[#e99537 #4da568 #6471eb #db5a54 #df4e92 #c44fe9 #eb5429 #61c9ea #805dee #6ad28a]diff --git a/db/migrate/20260727120000_add_family_name_index_to_tags_and_categories.rb b/db/migrate/20260727120000_add_family_name_index_to_tags_and_categories.rbnew file mode 100644index 0000000000..2ed490ac2c--- /dev/null+++ b/db/migrate/20260727120000_add_family_name_index_to_tags_and_categories.rb@@ -0,0 +1,6 @@+class AddFamilyNameIndexToTagsAndCategories < ActiveRecord::Migration[7.2]+ def change+ add_index :tags, [ :family_id, :name ], unique: true+ add_index :categories, [ :family_id, :name ], unique: true+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 23a6efe062..ce34218055 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[7.2].define(version: 2026_08_09_000000) do+ActiveRecord::Schema[7.2].define(version: 2026_08_12_000000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pgcrypto"enable_extension "plpgsql"@@ -395,8 +395,9 @@ ActiveRecord::Schema[7.2].define(version: 2026_08_09_000000) dot.string "classification_unused", default: "expense", null: falset.string "lucide_icon", default: "shapes", null: falset.datetime "last_used_at"- t.index ["family_id"], name: "index_categories_on_family_id"t.index ["family_id", "last_used_at"], name: "index_categories_on_family_id_and_last_used_at"+ t.index ["family_id", "name"], name: "index_categories_on_family_id_and_name", unique: true+ t.index ["family_id"], name: "index_categories_on_family_id"endcreate_table "chats", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|@@ -2062,6 +2063,7 @@ ActiveRecord::Schema[7.2].define(version: 2026_08_09_000000) dot.datetime "created_at", null: falset.datetime "updated_at", null: falset.index ["family_id"], name: "index_tags_on_family_id"+ t.index ["family_id", "name"], name: "index_tags_on_family_id_and_name", unique: trueendcreate_table "tool_calls", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|diff --git a/test/models/assistant/function/get_categories_test.rb b/test/models/assistant/function/get_categories_test.rbindex 7d48462a9e..8497ba3cb0 100644--- a/test/models/assistant/function/get_categories_test.rb+++ b/test/models/assistant/function/get_categories_test.rb@@ -11,17 +11,21 @@ class Assistant::Function::GetCategoriesTest < ActiveSupport::TestCasedefinition = @fn.to_definitionassert_equal "get_categories", definition[:name]assert_not_empty definition[:description]+ assert_equal "object", definition[:params_schema][:type]end- test "returns all family categories" do- result = @fn.call+ test "returns paginated categories" do+ result = @fn.call({ "page" => 1 })assert_kind_of Array, result[:categories]- assert_equal @family.categories.count, result[:total]+ assert_equal 1, result[:page]+ assert result[:total_results] >= result[:categories].size+ assert result[:total_pages] >= 1+ assert_equal Assistant::Function::GetCategories.default_page_size, result[:page_size]endtest "each category includes required fields" do- result = @fn.call+ result = @fn.call({ "page" => 1 })result[:categories].each do |c|assert c[:id].present?assert c[:name].present?@@ -34,7 +38,7 @@ class Assistant::Function::GetCategoriesTest < ActiveSupport::TestCaseendtest "subcategory is_subcategory is true and has parent_id" do- result = @fn.call+ result = @fn.call({ "page" => 1 })sub = result[:categories].find { |c| c[:name] == categories(:subcategory).name }assert sub.present?@@ -43,7 +47,7 @@ class Assistant::Function::GetCategoriesTest < ActiveSupport::TestCaseendtest "top-level category has nil parent_id and is_subcategory false" do- result = @fn.call+ result = @fn.call({ "page" => 1 })top = result[:categories].find { |c| c[:name] == categories(:food_and_drink).name }assert top.present?@@ -55,8 +59,28 @@ class Assistant::Function::GetCategoriesTest < ActiveSupport::TestCaseother_family = Family.create!(name: "Other", currency: "USD", locale: "en", country: "US", timezone: "UTC")other_family.categories.create!(name: "Foreign Category", color: "#e99537", lucide_icon: "shapes")- result = @fn.call+ result = @fn.call({ "page" => 1 })category_names = result[:categories].map { |c| c[:name] }assert_not_includes category_names, "Foreign Category"end++ test "defaults to page 1 when page param is omitted" do+ result_with_page = @fn.call({ "page" => 1 })+ result_without_page = @fn.call++ assert_equal result_with_page[:page], result_without_page[:page]+ assert_equal result_with_page[:total_results], result_without_page[:total_results]+ end++ test "paginates correctly when there are multiple pages" do+ 50.times { |i| @family.categories.create!(name: "PaginationCategory#{format('%02d', i)}", color: "#e99537", lucide_icon: "shapes") }++ page1 = @fn.call({ "page" => 1 })+ page2 = @fn.call({ "page" => 2 })++ assert page1[:total_pages] > 1+ assert_equal 1, page1[:page]+ assert_equal 2, page2[:page]+ assert_not_equal page1[:categories].map { |c| c[:name] }, page2[:categories].map { |c| c[:name] }+ endenddiff --git a/test/models/assistant/function/get_tags_test.rb b/test/models/assistant/function/get_tags_test.rbindex b5c9ba9c7f..c734fe90f9 100644--- a/test/models/assistant/function/get_tags_test.rb+++ b/test/models/assistant/function/get_tags_test.rb@@ -14,18 +14,21 @@ class Assistant::Function::GetTagsTest < ActiveSupport::TestCaseassert_equal "object", definition[:params_schema][:type]end- test "returns all family tags sorted alphabetically" do- result = @fn.call+ test "returns paginated tags sorted alphabetically" do+ result = @fn.call({ "page" => 1 })assert_kind_of Array, result[:tags]- assert_equal @family.tags.count, result[:total]+ assert_equal 1, result[:page]+ assert result[:total_results] >= result[:tags].size+ assert result[:total_pages] >= 1+ assert_equal Assistant::Function::GetTags.default_page_size, result[:page_size]names = result[:tags].map { |t| t[:name] }assert_equal names.sort, namesendtest "each tag includes id, name, and color" do- result = @fn.call+ result = @fn.call({ "page" => 1 })result[:tags].each do |t|assert t[:id].present?assert t[:name].present?@@ -37,8 +40,28 @@ class Assistant::Function::GetTagsTest < ActiveSupport::TestCaseother_family = Family.create!(name: "Other", currency: "USD", locale: "en", country: "US", timezone: "UTC")other_family.tags.create!(name: "Foreign Tag")- result = @fn.call+ result = @fn.call({ "page" => 1 })tag_names = result[:tags].map { |t| t[:name] }assert_not_includes tag_names, "Foreign Tag"end++ test "defaults to page 1 when page param is omitted" do+ result_with_page = @fn.call({ "page" => 1 })+ result_without_page = @fn.call++ assert_equal result_with_page[:page], result_without_page[:page]+ assert_equal result_with_page[:total_results], result_without_page[:total_results]+ end++ test "paginates correctly when there are multiple pages" do+ 50.times { |i| @family.tags.create!(name: "PaginationTag#{format('%02d', i)}") }++ page1 = @fn.call({ "page" => 1 })+ page2 = @fn.call({ "page" => 2 })++ assert page1[:total_pages] > 1+ assert_equal 1, page1[:page]+ assert_equal 2, page2[:page]+ assert_not_equal page1[:tags].map { |t| t[:name] }, page2[:tags].map { |t| t[:name] }+ endend