Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

feat(mcp): add delete_category and let update_category move categories (#4063)

Alana6caa0a4c148
diff --git a/app/models/assistant.rb b/app/models/assistant.rb
index e8320c60ca..e124912b3f 100644
--- a/app/models/assistant.rb
+++ b/app/models/assistant.rb
@@ -41,7 +41,8 @@ module Assistant
Function::CreateTag,
Function::UpdateTag,
Function::CreateCategory,
- Function::UpdateCategory
+ Function::UpdateCategory,
+ Function::DeleteCategory
].freeze
class << self
@@ -83,6 +84,7 @@ module Assistant
Function::GetCategories,
Function::CreateCategory,
Function::UpdateCategory,
+ Function::DeleteCategory,
Function::GetMerchants,
Function::GetRules,
Function::GetRuleOptions,
diff --git a/app/models/assistant/function/delete_category.rb b/app/models/assistant/function/delete_category.rb
new file mode 100644
index 0000000000..e616076c1f
--- /dev/null
+++ b/app/models/assistant/function/delete_category.rb
@@ -0,0 +1,70 @@
+class Assistant::Function::DeleteCategory < Assistant::Function
+ class << self
+ def name
+ "delete_category"
+ end
+
+ def description
+ <<~INSTRUCTIONS
+ Deletes a category from the user's family. This cannot be undone.
+
+ Use get_categories first to find the category id. Transactions in the deleted category
+ are moved to replacement_id when given, otherwise they become uncategorized. Subcategories
+ of a deleted top-level category are kept and become top-level categories. Budget
+ allocations for the deleted category are removed.
+
+ Confirm with the user before calling this tool.
+ INSTRUCTIONS
+ end
+ end
+
+ def strict_mode?
+ false
+ end
+
+ def params_schema
+ build_schema(
+ required: [ "id" ],
+ properties: {
+ id: {
+ type: "string",
+ description: "ID of the category to delete (use get_categories to find it)"
+ },
+ replacement_id: {
+ type: "string",
+ description: "ID of a category to move the deleted category's transactions to (optional). Transactions become uncategorized if omitted."
+ }
+ }
+ )
+ end
+
+ def call(params = {})
+ category = find_category(params["id"])
+ return error("not_found", "Category with id '#{params["id"]}' not found.") unless category
+
+ replacement = nil
+ # Only an omitted or null replacement_id uncategorizes the transactions; any
+ # other value, blank included, must be the id of a category in the family.
+ unless params["replacement_id"].nil?
+ replacement = find_category(params["replacement_id"])
+ return error("replacement_not_found", "Replacement category with id '#{params["replacement_id"]}' not found.") unless replacement
+ return error("invalid_replacement", "A category cannot replace itself.") if replacement == category
+ end
+
+ name = category.name_with_parent
+ category.replace_and_destroy!(replacement)
+
+ message = "Category '#{name}' deleted."
+ message += " Its transactions were moved to '#{replacement.reload.name_with_parent}'." if replacement
+ { success: true, id: category.id, replacement_id: replacement&.id, message: message }
+ end
+
+ private
+ def find_category(id)
+ family.categories.find_by(id: id) if valid_uuid?(id)
+ end
+
+ def error(key, message)
+ { success: false, error: key, message: message }
+ end
+end
diff --git a/app/models/assistant/function/get_categories.rb b/app/models/assistant/function/get_categories.rb
index 189edfeb99..a82c8930e0 100644
--- a/app/models/assistant/function/get_categories.rb
+++ b/app/models/assistant/function/get_categories.rb
@@ -14,7 +14,7 @@ class Assistant::Function::GetCategories < Assistant::Function
Each entry includes id, name, color, icon, parent_id (null for top-level), and
name_with_parent (e.g. "Food & Drink > Restaurants"). Use this before creating
- subcategories or referencing a category by id in update_category.
+ subcategories or referencing a category by id in update_category or delete_category.
Note on pagination:
diff --git a/app/models/assistant/function/update_category.rb b/app/models/assistant/function/update_category.rb
index 73e50e3b41..5d0f0edcd9 100644
--- a/app/models/assistant/function/update_category.rb
+++ b/app/models/assistant/function/update_category.rb
@@ -6,11 +6,15 @@ class Assistant::Function::UpdateCategory < Assistant::Function
def description
<<~INSTRUCTIONS
- Updates an existing category's name, color, or icon.
+ Updates an existing category's name, color, icon, or parent.
Use get_categories first to find the category id. At least one of name, color,
- or icon must be supplied. Changing a parent's color does not cascade to existing
- subcategories (their colors are set at creation time).
+ icon, or parent_id must be supplied. Changing a parent's color does not cascade to
+ existing subcategories (their colors are set when they are saved).
+
+ Pass parent_id to move the category under another top-level category (it takes the
+ parent's color), or pass an empty string to make it a top-level category. A category
+ that has subcategories cannot itself become a subcategory.
INSTRUCTIONS
end
end
@@ -38,6 +42,10 @@ class Assistant::Function::UpdateCategory < Assistant::Function
icon: {
type: "string",
description: "New Lucide icon name (optional)"
+ },
+ parent_id: {
+ type: "string",
+ description: "ID of a top-level category to move this category under, or an empty string to make it top-level (optional)"
}
}
)
@@ -53,7 +61,19 @@ class Assistant::Function::UpdateCategory < Assistant::Function
attrs[:color] = params["color"].to_s.strip if params["color"].present?
attrs[:lucide_icon] = params["icon"].to_s.strip if params["icon"].present?
- return error("no_changes", "Provide at least one of name, color, or icon to update.") if attrs.empty?
+
+ # Only an empty string promotes to top-level; null counts as omitted, and
+ # any other value must be the id of a category in the family.
+ if params["parent_id"] == ""
+ attrs[:parent] = nil
+ elsif !params["parent_id"].nil?
+ parent = family.categories.find_by(id: params["parent_id"]) if valid_uuid?(params["parent_id"])
+ return error("parent_not_found", "Parent category with id '#{params["parent_id"]}' not found.") unless parent
+ return error("invalid_parent", "A category cannot be its own parent.") if parent == category
+ attrs[:parent] = parent
+ end
+
+ return error("no_changes", "Provide at least one of name, color, icon, or parent_id to update.") if attrs.empty?
if category.update(attrs)
{ success: true, category: serialize(category), message: "Category '#{category.name_with_parent}' updated." }
diff --git a/docs/hosting/ai.md b/docs/hosting/ai.md
index 9d78ac3551..c3ed35c656 100644
--- a/docs/hosting/ai.md
+++ b/docs/hosting/ai.md
@@ -1532,7 +1532,7 @@ Write:
- `update_transaction`, `update_budget`, `create_goal`
- `unmatch_transfer` - Unlink a wrongly matched transfer
- `update_transfer` - Count a transfer into an investment account as spending or as a plain transfer
-- `create_tag` / `update_tag`, `create_category` / `update_category`
+- `create_tag` / `update_tag`, `create_category` / `update_category` / `delete_category`
Documents:
- `import_bank_statement` - Import bank statement data
diff --git a/docs/hosting/mcp.md b/docs/hosting/mcp.md
index 9a0851cf5e..f7b871eaeb 100644
--- a/docs/hosting/mcp.md
+++ b/docs/hosting/mcp.md
@@ -150,7 +150,7 @@ At the time of writing, `tools/list` includes:
| `unmatch_transfer` | Unlink a confirmed or pending transfer (by either transaction's id) so a wrong match can be redone; rejects the pairing for auto-match by default. Supports `dry_run` |
| `update_transfer` | Switch a confirmed transfer into an investment or crypto account between an investment contribution (counted as spending) and a plain transfer, e.g. when a brokerage or crypto account only converts currency. Supports `dry_run` |
| `create_tag` / `update_tag` | Manage tags |
-| `create_category` / `update_category` | Manage categories |
+| `create_category` / `update_category` / `delete_category` | Manage categories: create, rename, recolor, move between parents, and delete (optionally moving transactions to a replacement) |
| `update_transaction` | Edit a transaction's metadata (name, notes, category, merchant, tags) |
| `update_budget` | Update budget allocations for a month |
| `get_rules` / `get_rule_options` | Transaction rules in readable form (ids resolved to names, latest run; paginated, with a text search), and the condition and action types a rule can use |
diff --git a/test/models/assistant/function/delete_category_test.rb b/test/models/assistant/function/delete_category_test.rb
new file mode 100644
index 0000000000..aecb52ba1e
--- /dev/null
+++ b/test/models/assistant/function/delete_category_test.rb
@@ -0,0 +1,82 @@
+require "test_helper"
+
+class Assistant::Function::DeleteCategoryTest < ActiveSupport::TestCase
+ setup do
+ @user = users(:family_admin)
+ @family = @user.family
+ @category = categories(:food_and_drink)
+ @fn = Assistant::Function::DeleteCategory.new(@user)
+ end
+
+ test "deletes category and uncategorizes its transactions" do
+ transaction = transactions(:one)
+ assert_equal @category, transaction.category
+
+ result = @fn.call("id" => @category.id)
+
+ assert result[:success]
+ assert_not Category.exists?(@category.id)
+ assert_nil transaction.reload.category_id
+ end
+
+ test "moves transactions to the replacement category" do
+ transaction = transactions(:one)
+ replacement = categories(:income)
+
+ result = @fn.call("id" => @category.id, "replacement_id" => replacement.id)
+
+ assert result[:success]
+ assert_equal replacement.id, result[:replacement_id]
+ assert_equal replacement, transaction.reload.category
+ end
+
+ test "promotes subcategories of a deleted parent to top-level" do
+ sub = categories(:subcategory)
+
+ @fn.call("id" => @category.id)
+
+ assert_nil sub.reload.parent_id
+ end
+
+ test "soft error when category not found" do
+ result = @fn.call("id" => "00000000-0000-0000-0000-000000000000")
+
+ assert_equal false, result[:success]
+ assert_equal "not_found", result[:error]
+ end
+
+ test "blank replacement_id is rejected instead of uncategorizing" do
+ [ "", " " ].each do |blank|
+ result = @fn.call("id" => @category.id, "replacement_id" => blank)
+
+ assert_equal "replacement_not_found", result[:error]
+ end
+ assert Category.exists?(@category.id)
+ assert_equal @category, transactions(:one).reload.category
+ end
+
+ test "null replacement_id uncategorizes like an omitted one" do
+ result = @fn.call("id" => @category.id, "replacement_id" => nil)
+
+ assert result[:success]
+ assert_not Category.exists?(@category.id)
+ assert_nil transactions(:one).reload.category_id
+ end
+
+ test "soft error when replacement is the category itself" do
+ result = @fn.call("id" => @category.id, "replacement_id" => @category.id)
+
+ assert_equal "invalid_replacement", result[:error]
+ assert Category.exists?(@category.id)
+ end
+
+ test "cannot delete or replace with a category from another family" do
+ other_family = Family.create!(name: "Other", currency: "USD", locale: "en", country: "US", timezone: "UTC")
+ other_cat = other_family.categories.create!(name: "Foreign", color: "#e99537", lucide_icon: "shapes")
+
+ assert_equal "not_found", @fn.call("id" => other_cat.id)[:error]
+ assert_equal "replacement_not_found", @fn.call("id" => @category.id, "replacement_id" => other_cat.id)[:error]
+ assert Category.exists?(other_cat.id)
+ assert Category.exists?(@category.id)
+ end
+end
diff --git a/test/models/assistant/function/update_category_test.rb b/test/models/assistant/function/update_category_test.rb
index 70e83a4857..800998da27 100644
--- a/test/models/assistant/function/update_category_test.rb
+++ b/test/models/assistant/function/update_category_test.rb
@@ -101,4 +101,61 @@ class Assistant::Function::UpdateCategoryTest < ActiveSupport::TestCase
assert_equal false, result[:success]
assert_equal "not_found", result[:error]
end
+
+ test "moves a category under a new parent and inherits its color" do
+ parent = categories(:income)
+
+ result = @fn.call("id" => categories(:one).id, "parent_id" => parent.id)
+
+ assert result[:success]
+ assert_equal parent.id, result[:category][:parent_id]
+ assert_equal parent.id, categories(:one).reload.parent_id
+ assert_equal parent.color, categories(:one).reload.color
+ end
+
+ test "empty parent_id promotes a subcategory to top-level" do
+ sub = categories(:subcategory)
+
+ result = @fn.call("id" => sub.id, "parent_id" => "")
+
+ assert result[:success]
+ assert_nil sub.reload.parent_id
+ end
+
+ test "soft error when moving a category with subcategories under a parent" do
+ result = @fn.call("id" => @category.id, "parent_id" => categories(:income).id)
+
+ assert_equal "validation_failed", result[:error]
+ assert_nil @category.reload.parent_id
+ end
+
+ test "soft error when parent is the category itself" do
+ result = @fn.call("id" => @category.id, "parent_id" => @category.id)
+
+ assert_equal "invalid_parent", result[:error]
+ end
+
+ test "null parent_id leaves the hierarchy unchanged" do
+ sub = categories(:subcategory)
+
+ result = @fn.call("id" => sub.id, "parent_id" => nil)
+
+ assert_equal "no_changes", result[:error]
+ assert_equal categories(:food_and_drink).id, sub.reload.parent_id
+ end
+
+ test "whitespace-only parent_id does not promote" do
+ sub = categories(:subcategory)
+
+ result = @fn.call("id" => sub.id, "parent_id" => " ")
+
+ assert_equal "parent_not_found", result[:error]
+ assert_equal categories(:food_and_drink).id, sub.reload.parent_id
+ end
+
+ test "soft error when parent not found" do
+ result = @fn.call("id" => @category.id, "parent_id" => "00000000-0000-0000-0000-000000000000")
+
+ assert_equal "parent_not_found", result[:error]
+ end
end