A platform for community discussion. Free, open, simple.
FEATURE: Add category management tools to the MCP server (#44232)
Natalie Tay41e84f0e42e1
diff --git a/app/controllers/categories_controller.rb b/app/controllers/categories_controller.rbindex 0bfc94cd6d2..499c1ad94e2 100644--- a/app/controllers/categories_controller.rb+++ b/app/controllers/categories_controller.rb@@ -17,8 +17,6 @@ class CategoriesController < ApplicationController]before_action :fetch_category, only: %i[show update destroy visible_groups convert_nested_replies]- before_action :initialize_staff_action_logger, only: %i[create update destroy]-skip_before_action :check_xhr,only: %i[index@@ -159,37 +157,20 @@ class CategoriesController < ApplicationControllerrender_serialized(@category, CategorySerializer)end- MAX_DESCRIPTION_PARAM_LENGTH = 1000+ MAX_DESCRIPTION_PARAM_LENGTH = CategoryCreator::MAX_DESCRIPTION_LENGTH+def createguardian.ensure_can_create!(Category)position = category_params.delete(:position)category_type = params[:category_type]-- if category_params[:description].present? &&- category_params[:description].size > MAX_DESCRIPTION_PARAM_LENGTH- render json: {- errors: [- I18n.t(- "category.errors.description_too_long",- count: MAX_DESCRIPTION_PARAM_LENGTH,- ),- ],- },- status: :unprocessable_entity- return- end-- @category =- begin- Category.new(required_create_params.merge(user: current_user))- rescue ArgumentError => e- return render json: { errors: [e.message] }, status: :unprocessable_entity- end+ category_attributes = required_create_paramsconfigure_error = nilCategory.transaction do- if @category.save+ @category = CategoryCreator.create(guardian, category_attributes)++ if @category.persisted?@category.move_to(position.to_i) if positionif category_type.present?@@ -244,10 +225,6 @@ class CategoriesController < ApplicationControllerendif @category.persisted?- Scheduler::Defer.later "Log staff action create category" do- @staff_action_logger.log_category_creation(@category)- end-render_serialized(@category, CategorySerializer)elserender_json_error(@category)@@ -258,7 +235,7 @@ class CategoriesController < ApplicationControllerguardian.ensure_can_edit!(@category)json_result(@category, serializer: CategorySerializer) do |cat|- old_category_params = category_params.dup+ category_params_for_log = category_params.dupcat.move_to(category_params[:position].to_i) if category_params[:position]category_params.delete(:position)@@ -299,17 +276,16 @@ class CategoriesController < ApplicationControllerold_permissions = cat.permissions_paramsold_permissions = { Group[:everyone].name => 1 } if old_permissions.empty?- if result = cat.update(category_params)+ if result =+ CategoryUpdater.update(+ guardian,+ cat,+ category_params,+ log_attributes: category_params_for_log,+ old_permissions:,+ old_custom_fields:,+ )Category.preload_user_fields!(guardian, [cat])-- Scheduler::Defer.later "Log staff action change category settings" do- @staff_action_logger.log_category_settings_change(- @category,- old_category_params,- old_permissions: old_permissions,- old_custom_fields: old_custom_fields,- )- endendresult@@ -368,13 +344,7 @@ class CategoriesController < ApplicationControllerenddef destroy- guardian.ensure_can_delete!(@category)- @category.destroy- Discourse.cache.delete(Categories::TypeRegistry::COUNTS_CACHE_KEY)-- Scheduler::Defer.later "Log staff action delete category" do- @staff_action_logger.log_category_deletion(@category)- end+ CategoryDestroyer.destroy(guardian, @category)render json: success_jsonend@@ -930,8 +900,4 @@ class CategoriesController < ApplicationController@topic_listend-- def initialize_staff_action_logger- @staff_action_logger = StaffActionLogger.new(current_user)- endenddiff --git a/app/models/category.rb b/app/models/category.rbindex b1e048f4c4e..6e15bf7dca4 100644--- a/app/models/category.rb+++ b/app/models/category.rb@@ -830,6 +830,11 @@ class Category < ActiveRecord::Basedef parent_category_validatorif parent_category_id+ if parent_category.blank?+ errors.add(:base, I18n.t("category.errors.not_found"))+ return+ end+errors.add(:base, I18n.t("category.errors.uncategorized_parent")) if uncategorized?errors.add(:base, I18n.t("category.errors.self_parent")) if parent_category_id == id@@ -1220,18 +1225,16 @@ class Category < ActiveRecord::Basedef permissions_compatibility_validator# when saving subcategories- if @permissions && parent_category_id.present?- return if parent_category.category_groups.empty?+ if (@permissions || parent_category_id_changed?) && parent_category_id.present?+ return if parent_category.blank? || parent_category.category_groups.empty?parent_permissions = parent_category.category_groups.pluck(:group_id, :permission_type)child_permissions =- (- if @permissions.empty?- [[Group[:everyone].id, CategoryGroup.permission_types[:full]]]- else- @permissions- end- )+ @permissions ||+ category_groups.map { |permission| [permission.group_id, permission.permission_type] }+ if child_permissions.empty?+ child_permissions = [[Group[:everyone].id, CategoryGroup.permission_types[:full]]]+ endcheck_permissions_compatibility(parent_permissions, child_permissions)# when saving parent categorydiff --git a/app/services/staff_action_logger.rb b/app/services/staff_action_logger.rbindex bddfe0a1aba..844ceb4c837 100644--- a/app/services/staff_action_logger.rb+++ b/app/services/staff_action_logger.rb@@ -748,7 +748,7 @@ class StaffActionLoggerchanged_attributes = category.previous_changes.slice(*category_params.keys)- if !old_permissions.empty? && (old_permissions != category_params[:permissions].to_h)+ if old_permissions.present? && (old_permissions != category_params[:permissions].to_h)changed_attributes.merge!(permissions: [old_permissions.to_json, category_params[:permissions].to_json],)diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 32e79ede986..5204b0727d9 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -20,6 +20,12 @@ en:date_with_timezone: "%{date} (%{timezone})"mcp:errors:+ category_create_failed: "Category could not be created"+ category_delete_confirmation_required: "Category deletion must be confirmed"+ category_delete_name_mismatch: "Category name does not match"+ category_not_found: "Category not found"+ category_update_failed: "Category could not be updated"+ category_update_required: "At least one category field must be provided"draft_sequence_conflict: "Draft sequence conflict"draft_too_long: "Draft is too long"group_not_found: "Group not found"diff --git a/lib/category_creator.rb b/lib/category_creator.rbnew file mode 100644index 00000000000..740680561a6--- /dev/null+++ b/lib/category_creator.rb@@ -0,0 +1,48 @@+# frozen_string_literal: true++class CategoryCreator+ MAX_DESCRIPTION_LENGTH = 1_000++ def self.create(guardian, attributes)+ new(guardian, attributes).create+ end++ def initialize(guardian, attributes)+ @guardian = guardian+ @attributes = attributes.to_h.with_indifferent_access+ end++ def create+ guardian.ensure_can_create!(Category)++ category = Category.new+ begin+ category.assign_attributes(attributes.merge(user: guardian.user))+ rescue ArgumentError => error+ category.errors.add(:base, error.message)+ return category+ end++ if category.parent_category_id.present? && category.parent_category.present?+ guardian.ensure_can_edit!(category.parent_category)+ end++ if attributes[:description].present? && attributes[:description].length > MAX_DESCRIPTION_LENGTH+ category.errors.add(+ :base,+ I18n.t("category.errors.description_too_long", count: MAX_DESCRIPTION_LENGTH),+ )+ return category+ end++ Category.transaction do+ StaffActionLogger.new(guardian.user).log_category_creation(category) if category.save+ end++ category+ end++ private++ attr_reader :guardian, :attributes+enddiff --git a/lib/category_destroyer.rb b/lib/category_destroyer.rbnew file mode 100644index 00000000000..e8845a95f82--- /dev/null+++ b/lib/category_destroyer.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++class CategoryDestroyer+ def self.destroy(guardian, category)+ Category.transaction do+ category.lock!+ guardian.ensure_can_delete!(category)+ StaffActionLogger.new(guardian.user).log_category_deletion(category)+ category.destroy!+ end++ Discourse.cache.delete(Categories::TypeRegistry::COUNTS_CACHE_KEY)+ category+ end+enddiff --git a/lib/category_updater.rb b/lib/category_updater.rbnew file mode 100644index 00000000000..7da0bc58482--- /dev/null+++ b/lib/category_updater.rb@@ -0,0 +1,88 @@+# frozen_string_literal: true++class CategoryUpdater+ MAX_DESCRIPTION_LENGTH = CategoryCreator::MAX_DESCRIPTION_LENGTH++ def self.update(+ guardian,+ category,+ attributes = nil,+ log_attributes: nil,+ old_permissions: nil,+ old_custom_fields: nil,+ **attribute_keywords+ )+ attributes = attributes ? attributes.to_h.merge(attribute_keywords) : attribute_keywords++ new(+ guardian,+ category,+ attributes,+ log_attributes:,+ old_permissions:,+ old_custom_fields:,+ ).update+ end++ def initialize(+ guardian,+ category,+ attributes,+ log_attributes: nil,+ old_permissions: nil,+ old_custom_fields: nil+ )+ @guardian = guardian+ @category = category+ @attributes = attributes.to_h.with_indifferent_access+ @log_attributes = (log_attributes || attributes).to_h.with_indifferent_access+ @old_permissions = old_permissions+ @old_custom_fields = old_custom_fields+ end++ def update+ guardian.ensure_can_edit!(category)++ if attributes[:parent_category_id].present?+ parent_category = Category.find_by(id: attributes[:parent_category_id])+ guardian.ensure_can_edit!(parent_category) if parent_category.present?+ end++ if attributes[:description].present? && attributes[:description].length > MAX_DESCRIPTION_LENGTH+ category.errors.add(+ :base,+ I18n.t("category.errors.description_too_long", count: MAX_DESCRIPTION_LENGTH),+ )+ return false+ end++ Category.transaction do+ begin+ updated = category.update(attributes)+ rescue ArgumentError => error+ category.errors.add(:base, error.message)+ return false+ end++ if updated+ StaffActionLogger.new(guardian.user).log_category_settings_change(+ category,+ log_attributes,+ old_permissions:,+ old_custom_fields:,+ )+ end++ updated+ end+ end++ private++ attr_reader :guardian,+ :category,+ :attributes,+ :log_attributes,+ :old_permissions,+ :old_custom_fields+enddiff --git a/lib/discourse_mcp.rb b/lib/discourse_mcp.rbindex 0b5b398eee4..713192c3f0e 100644--- a/lib/discourse_mcp.rb+++ b/lib/discourse_mcp.rb@@ -4,6 +4,8 @@ module DiscourseMcpmodule ScopesPROFILE_READ = "mcp:profile:read"PROFILE_WRITE = "mcp:profile:write"+ CATEGORIES_READ = "mcp:categories:read"+ CATEGORIES_WRITE = "mcp:categories:write"CONTENT_READ = "mcp:content:read"CONTENT_WRITE = "mcp:content:write"DRAFTS_READ = "mcp:drafts:read"diff --git a/lib/discourse_mcp/core_primitives.rb b/lib/discourse_mcp/core_primitives.rbindex 4d2d7d94b06..4245109960a 100644--- a/lib/discourse_mcp/core_primitives.rb+++ b/lib/discourse_mcp/core_primitives.rb@@ -69,10 +69,156 @@ module DiscourseMcpregister_site_setting_tools(registry)register_theme_tools(registry)register_group_tools(registry)+ register_category_tools(registry)register_resources(registry)register_prompts(registry)end+ def register_category_tools(registry)+ register_tool(+ registry,+ "discourse_get_category",+ title: "Get category",+ description: "Reads category details needed for category management.",+ implementation: Tools::GetCategory,+ input_schema:+ object_schema(+ { category_id: { type: "integer", minimum: 1 } },+ required: %w[category_id],+ ),+ annotations: READ_ONLY,+ risk: :administration,+ )+ register_tool(+ registry,+ "discourse_create_category",+ title: "Create category",+ description: "Creates a category and returns its ID, slug, and name.",+ implementation: Tools::CreateCategory,+ input_schema:+ object_schema(+ {+ name: {+ type: "string",+ minLength: 1,+ maxLength: Tools::CreateCategory::MAX_NAME_LENGTH,+ },+ color: {+ type: "string",+ pattern: "^(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$",+ },+ text_color: {+ type: "string",+ pattern: "^(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$",+ },+ emoji: {+ type: "string",+ minLength: 1,+ maxLength: Tools::CreateCategory::MAX_STYLE_VALUE_LENGTH,+ },+ icon: {+ type: "string",+ minLength: 1,+ maxLength: Tools::CreateCategory::MAX_STYLE_VALUE_LENGTH,+ },+ parent_category_id: {+ type: "integer",+ minimum: 1,+ },+ description: {+ type: "string",+ maxLength: Tools::CreateCategory::MAX_DESCRIPTION_LENGTH,+ },+ },+ required: %w[name],+ ),+ annotations: WRITE,+ risk: :administration,+ )+ register_tool(+ registry,+ "discourse_update_category",+ title: "Update category",+ description: "Updates basic details for a category.",+ implementation: Tools::UpdateCategory,+ input_schema:+ object_schema(+ {+ category_id: {+ type: "integer",+ minimum: 1,+ },+ name: {+ type: "string",+ minLength: 1,+ maxLength: Tools::UpdateCategory::MAX_NAME_LENGTH,+ },+ slug: {+ type: "string",+ minLength: 1,+ maxLength: 255,+ },+ color: {+ type: "string",+ pattern: "^(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$",+ },+ text_color: {+ type: "string",+ pattern: "^(?:[0-9a-fA-F]{3}|[0-9a-fA-F]{6})$",+ },+ emoji: {+ type: "string",+ minLength: 1,+ maxLength: Tools::UpdateCategory::MAX_STYLE_VALUE_LENGTH,+ },+ icon: {+ type: "string",+ minLength: 1,+ maxLength: Tools::UpdateCategory::MAX_STYLE_VALUE_LENGTH,+ },+ parent_category_id: {+ type: %w[integer null],+ minimum: 1,+ },+ description: {+ type: "string",+ maxLength: Tools::UpdateCategory::MAX_DESCRIPTION_LENGTH,+ },+ },+ required: %w[category_id],+ ),+ annotations: WRITE,+ risk: :administration,+ )+ register_tool(+ registry,+ "discourse_delete_category",+ title: "Delete category",+ description: "Deletes an empty category after confirming its current name.",+ implementation: Tools::DeleteCategory,+ input_schema:+ object_schema(+ {+ category_id: {+ type: "integer",+ minimum: 1,+ },+ expected_name: {+ type: "string",+ minLength: 1,+ maxLength: Tools::UpdateCategory::MAX_NAME_LENGTH,+ },+ confirm: {+ type: "boolean",+ },+ },+ required: %w[category_id expected_name confirm],+ ),+ annotations: DESTRUCTIVE,+ risk: :destructive,+ )+ end+def register_read_tools(registry)register_tool(registry,diff --git a/lib/discourse_mcp/core_tools.rb b/lib/discourse_mcp/core_tools.rbindex c6c713f433f..8e4d1624bb5 100644--- a/lib/discourse_mcp/core_tools.rb+++ b/lib/discourse_mcp/core_tools.rb@@ -1,5 +1,8 @@# frozen_string_literal: true+require "category_creator"+require "category_destroyer"+require "category_updater"require "discourse_mcp/tool_helpers"require "discourse_mcp/output_schema"require "discourse_mcp/tools/search"@@ -15,3 +18,4 @@ require "discourse_mcp/tools/moderation"require "discourse_mcp/tools/site_settings"require "discourse_mcp/tools/themes"require "discourse_mcp/tools/groups"+require "discourse_mcp/tools/categories"diff --git a/lib/discourse_mcp/tools/categories.rb b/lib/discourse_mcp/tools/categories.rbnew file mode 100644index 00000000000..421e0c86e5b--- /dev/null+++ b/lib/discourse_mcp/tools/categories.rb@@ -0,0 +1,166 @@+# frozen_string_literal: true++module DiscourseMcp+ module Tools+ module CategorySupport+ BASIC_ATTRIBUTE_NAMES = %w[+ name+ slug+ description+ parent_category_id+ color+ text_color+ emoji+ icon+ ].freeze+ CATEGORY_SCHEMA =+ OutputSchema.object(+ id: OutputSchema::INTEGER,+ name: OutputSchema::STRING,+ slug: OutputSchema::STRING,+ description: OutputSchema::STRING_OR_NULL,+ parent_category_id: OutputSchema::INTEGER_OR_NULL,+ color: OutputSchema::STRING,+ text_color: OutputSchema::STRING,+ style_type: OutputSchema::STRING,+ emoji: OutputSchema::STRING_OR_NULL,+ icon: OutputSchema::STRING_OR_NULL,+ position: OutputSchema::INTEGER,+ topic_count: OutputSchema::INTEGER,+ can_delete: OutputSchema::BOOLEAN,+ updated_at: OutputSchema::STRING,+ )++ module_function++ def find_category!(category_id, guardian)+ guardian.ensure_can_create!(Category)+ category = Category.find_by(id: category_id)+ raise ToolError, I18n.t("mcp.errors.category_not_found") if category.blank?++ category+ end++ def category_json(category, guardian)+ {+ id: category.id,+ name: category.name,+ slug: category.slug,+ description: category.topic&.first_post&.raw || category.description_text,+ parent_category_id: category.parent_category_id,+ color: category.color,+ text_color: category.text_color,+ style_type: category.style_type,+ emoji: category.emoji,+ icon: category.icon,+ position: category.position,+ topic_count: category.topic_count,+ can_delete: guardian.can_delete?(category),+ updated_at: category.updated_at.iso8601,+ }+ end++ def basic_attributes(arguments)+ attributes = arguments.slice(*BASIC_ATTRIBUTE_NAMES)++ if arguments["emoji"].present?+ attributes["style_type"] = "emoji"+ elsif arguments["icon"].present?+ attributes["style_type"] = "icon"+ end++ attributes+ end+ end++ class CreateCategory+ REQUIRED_SCOPES = [Scopes::CATEGORIES_WRITE].freeze+ MAX_NAME_LENGTH = 50+ MAX_DESCRIPTION_LENGTH = CategoryCreator::MAX_DESCRIPTION_LENGTH+ MAX_STYLE_VALUE_LENGTH = 100+ OUTPUT_SCHEMA =+ OutputSchema.object(+ id: OutputSchema::INTEGER,+ slug: OutputSchema::STRING,+ name: OutputSchema::STRING,+ )++ def self.call(arguments:, request_context:)+ guardian = request_context.guardian+ category = CategoryCreator.create(guardian, category_attributes(arguments))+ if !category.persisted?+ message =+ category.errors.full_messages.to_sentence.presence ||+ I18n.t("mcp.errors.category_create_failed")+ raise ToolError, message+ end++ ToolHelpers.text_and_structured(id: category.id, slug: category.slug, name: category.name)+ end++ def self.category_attributes(arguments)+ CategorySupport.basic_attributes(arguments).except("slug")+ end+ private_class_method :category_attributes+ end++ class GetCategory+ REQUIRED_SCOPES = [Scopes::CATEGORIES_READ].freeze+ OUTPUT_SCHEMA = OutputSchema.object(category: CategorySupport::CATEGORY_SCHEMA)++ def self.call(arguments:, request_context:)+ guardian = request_context.guardian+ category = CategorySupport.find_category!(arguments.fetch("category_id"), guardian)+ guardian.ensure_can_edit!(category)+ ToolHelpers.text_and_structured(category: CategorySupport.category_json(category, guardian))+ end+ end++ class UpdateCategory+ REQUIRED_SCOPES = [Scopes::CATEGORIES_WRITE].freeze+ MAX_NAME_LENGTH = CreateCategory::MAX_NAME_LENGTH+ MAX_DESCRIPTION_LENGTH = CategoryUpdater::MAX_DESCRIPTION_LENGTH+ MAX_STYLE_VALUE_LENGTH = CreateCategory::MAX_STYLE_VALUE_LENGTH+ OUTPUT_SCHEMA = OutputSchema.object(category: CategorySupport::CATEGORY_SCHEMA)++ def self.call(arguments:, request_context:)+ guardian = request_context.guardian+ category = CategorySupport.find_category!(arguments.fetch("category_id"), guardian)+ attributes = CategorySupport.basic_attributes(arguments)+ raise ToolError, I18n.t("mcp.errors.category_update_required") if attributes.empty?++ if !CategoryUpdater.update(guardian, category, attributes)+ message =+ category.errors.full_messages.to_sentence.presence ||+ I18n.t("mcp.errors.category_update_failed")+ raise ToolError, message+ end++ ToolHelpers.text_and_structured(category: CategorySupport.category_json(category, guardian))+ end+ end++ class DeleteCategory+ REQUIRED_SCOPES = [Scopes::CATEGORIES_WRITE].freeze+ OUTPUT_SCHEMA =+ OutputSchema.object(deleted: OutputSchema::BOOLEAN, category_id: OutputSchema::INTEGER)++ def self.call(arguments:, request_context:)+ guardian = request_context.guardian+ category = CategorySupport.find_category!(arguments.fetch("category_id"), guardian)+ guardian.ensure_can_delete!(category)++ if arguments["confirm"] != true+ raise ToolError, I18n.t("mcp.errors.category_delete_confirmation_required")+ end+ if arguments.fetch("expected_name") != category.name+ raise ToolError, I18n.t("mcp.errors.category_delete_name_mismatch")+ end++ category_id = category.id+ CategoryDestroyer.destroy(guardian, category)+ ToolHelpers.text_and_structured(deleted: true, category_id:)+ end+ end+ end+enddiff --git a/plugins/chat/spec/system/create_channel_spec.rb b/plugins/chat/spec/system/create_channel_spec.rbindex 275c3b2347e..c0e27d1a2e8 100644--- a/plugins/chat/spec/system/create_channel_spec.rb+++ b/plugins/chat/spec/system/create_channel_spec.rb@@ -64,6 +64,12 @@ RSpec.describe "Create channel" docontext "when category is a child" dofab!(:group_2, :group)fab!(:child_category) do+ private_category_1.update!(+ permissions: {+ group_1.name => :full,+ group_2.name => :full,+ },+ )Fabricate(:private_category, parent_category_id: private_category_1.id, group: group_2)enddiff --git a/plugins/discourse-ai/lib/agents/tools/create_category.rb b/plugins/discourse-ai/lib/agents/tools/create_category.rbindex 427a47b5aa5..b41eaf67f24 100644--- a/plugins/discourse-ai/lib/agents/tools/create_category.rb+++ b/plugins/discourse-ai/lib/agents/tools/create_category.rb@@ -78,12 +78,12 @@ module DiscourseAiendif parameters[:description].present? &&- parameters[:description].size > CategoriesController::MAX_DESCRIPTION_PARAM_LENGTH+ parameters[:description].size > CategoryCreator::MAX_DESCRIPTION_LENGTHreturn(error_response(I18n.t("category.errors.description_too_long",- count: CategoriesController::MAX_DESCRIPTION_PARAM_LENGTH,+ count: CategoryCreator::MAX_DESCRIPTION_LENGTH,),))@@ -96,7 +96,7 @@ module DiscourseAi# Model validations (duplicate name, name length, color format) run# against the unsaved candidate so an invalid request is rejected# before it is queued for approval.- candidate = Category.new(category_attributes)+ candidate = Category.new(category_attributes.merge(user: guardian.user))return error_response(candidate.errors.full_messages.to_sentence) if !candidate.valid?nil@@ -117,7 +117,6 @@ module DiscourseAiname: parameters[:name],description: parameters[:description].presence,parent_category_id: parent_category&.id,- user: guardian.user,}%i[color text_color].each do |param|value = parameters[param]@@ -127,14 +126,9 @@ module DiscourseAienddef perform_create- if !guardian.can_create_category?- return error_response(I18n.t("discourse_ai.ai_bot.create_category.errors.not_allowed"))- end-- category = Category.new(category_attributes)+ category = CategoryCreator.create(guardian, category_attributes)- if category.save- StaffActionLogger.new(guardian.user).log_category_creation(category)+ if category.persisted?{status: "success",category_id: category.id,@@ -144,6 +138,8 @@ module DiscourseAielseerror_response(category.errors.full_messages.to_sentence)end+ rescue Discourse::InvalidAccess+ error_response(I18n.t("discourse_ai.ai_bot.create_category.errors.not_allowed"))endendenddiff --git a/spec/lib/category_creator_spec.rb b/spec/lib/category_creator_spec.rbnew file mode 100644index 00000000000..e8ffb83fa53--- /dev/null+++ b/spec/lib/category_creator_spec.rb@@ -0,0 +1,135 @@+# frozen_string_literal: true++describe CategoryCreator do+ fab!(:admin)+ fab!(:moderator)+ fab!(:user)++ describe ".create" do+ it "creates a category as the authenticated user" do+ category = nil++ expect do+ category =+ described_class.create(+ admin.guardian,+ name: "猫 support",+ description: "Help with **cats**",+ color: "0088CC",+ text_color: "FFFFFF",+ )+ end.to change {+ UserHistory.where(+ action: UserHistory.actions[:create_category],+ acting_user_id: admin.id,+ ).count+ }.by(1)++ expect(category).to be_persisted+ expect(category).to have_attributes(+ name: "猫 support",+ user_id: admin.id,+ color: "0088CC",+ text_color: "FFFFFF",+ )+ expect(category.topic.first_post.raw).to eq("Help with **cats**")+ end++ it "creates a subcategory" do+ parent_category = Fabricate(:category)++ category =+ described_class.create(+ admin.guardian,+ name: "Subcategory",+ parent_category_id: parent_category.id,+ )++ expect(category).to be_persisted+ expect(category.parent_category_id).to eq(parent_category.id)+ end++ it "does not create a subcategory under a deleted category" do+ parent_category = Fabricate(:category)+ parent_category.destroy!++ category =+ described_class.create(+ admin.guardian,+ name: "Orphaned",+ parent_category_id: parent_category.id,+ )++ expect(category).not_to be_persisted+ expect(category.errors.full_messages).to contain_exactly(I18n.t("category.errors.not_found"))+ end++ it "uses the existing category management permission" do+ expect do described_class.create(user.guardian, name: "Not allowed") end.to raise_error(+ Discourse::InvalidAccess,+ )++ expect do+ described_class.create(moderator.guardian, name: "Moderator category")+ end.to raise_error(Discourse::InvalidAccess)++ SiteSetting.moderators_manage_categories = true++ category = described_class.create(moderator.guardian, name: "Moderator category")++ expect(category).to be_persisted+ expect(category.user_id).to eq(moderator.id)+ end++ it "does not let a moderator create a subcategory under a category they cannot see" do+ SiteSetting.moderators_manage_categories = true+ group = Fabricate(:group)+ parent_category = Fabricate(:private_category, group:)++ expect do+ described_class.create(+ moderator.guardian,+ name: "Not visible",+ parent_category_id: parent_category.id,+ )+ end.to raise_error(Discourse::InvalidAccess)++ expect(Category.find_by(name: "Not visible")).to be_nil+ end++ it "rejects descriptions above the category API limit" do+ category =+ described_class.create(+ admin.guardian,+ name: "Long description",+ description: "a" * (described_class::MAX_DESCRIPTION_LENGTH + 1),+ )++ expect(category).not_to be_persisted+ expect(category.errors.full_messages).to contain_exactly(+ I18n.t(+ "category.errors.description_too_long",+ count: described_class::MAX_DESCRIPTION_LENGTH,+ ),+ )+ end++ it "returns model assignment errors without creating a category" do+ category = nil++ expect do+ category =+ described_class.create(admin.guardian, name: "Invalid style", style_type: "not-a-style")+ end.not_to change {+ UserHistory.where(+ action: UserHistory.actions[:create_category],+ acting_user_id: admin.id,+ ).count+ }++ expect(category).not_to be_persisted+ expect(category.errors).to be_present+ expect(Category.find_by(name: "Invalid style")).to be_nil+ end+ end+enddiff --git a/spec/lib/category_destroyer_spec.rb b/spec/lib/category_destroyer_spec.rbnew file mode 100644index 00000000000..dd6ce449da2--- /dev/null+++ b/spec/lib/category_destroyer_spec.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++describe CategoryDestroyer do+ fab!(:admin)+ fab!(:moderator)+ fab!(:user)++ describe ".destroy" do+ it "deletes a category and records the staff action" do+ category = Fabricate(:category, user: admin)+ topic_timer = Fabricate(:topic_timer, category:)++ expect { described_class.destroy(admin.guardian, category) }.to change(Category, :count).by(+ -1,+ ).and change {+ UserHistory.where(+ action: UserHistory.actions[:delete_category],+ acting_user_id: admin.id,+ category_id: category.id,+ ).count+ }.by(1)++ expect(TopicTimer.exists?(topic_timer.id)).to eq(false)+ end++ it "uses the existing category deletion permission" do+ category = Fabricate(:category, user: admin)++ expect do described_class.destroy(user.guardian, category) end.to raise_error(+ Discourse::InvalidAccess,+ )++ expect do described_class.destroy(moderator.guardian, category) end.to raise_error(+ Discourse::InvalidAccess,+ )++ SiteSetting.moderators_manage_categories = true++ described_class.destroy(moderator.guardian, category)++ expect(Category.exists?(category.id)).to eq(false)+ end++ it "does not delete a category that contains topics" do+ category = Fabricate(:category, user: admin)+ Fabricate(:topic, category:)+ category.update!(topic_count: 1)++ expect do described_class.destroy(admin.guardian, category) end.to raise_error(+ Discourse::InvalidAccess,+ )++ expect(Category.exists?(category.id)).to eq(true)+ end++ it "does not delete a category that contains subcategories" do+ category = Fabricate(:category, user: admin)+ Fabricate(:category, parent_category: category)++ expect do described_class.destroy(admin.guardian, category) end.to raise_error(+ Discourse::InvalidAccess,+ )++ expect(Category.exists?(category.id)).to eq(true)+ end+ end+enddiff --git a/spec/lib/category_updater_spec.rb b/spec/lib/category_updater_spec.rbnew file mode 100644index 00000000000..113a6a5dd07--- /dev/null+++ b/spec/lib/category_updater_spec.rb@@ -0,0 +1,137 @@+# frozen_string_literal: true++describe CategoryUpdater do+ fab!(:admin)+ fab!(:moderator)+ fab!(:user)++ describe ".update" do+ it "updates category details and keeps the definition topic in sync" do+ category = Fabricate(:category_with_definition, user: admin)+ result = nil++ expect do+ result =+ described_class.update(+ admin.guardian,+ category,+ name: "猫 support",+ description: "Updated **description**",+ color: "0088CC",+ text_color: "FFFFFF",+ )+ end.to change {+ UserHistory.where(+ action: UserHistory.actions[:change_category_settings],+ acting_user_id: admin.id,+ category_id: category.id,+ subject: "name",+ ).count+ }.by(1)++ expect(result).to eq(true)+ expect(category.reload).to have_attributes(+ name: "猫 support",+ color: "0088CC",+ text_color: "FFFFFF",+ )+ expect(category.topic.first_post.reload.raw).to eq("Updated **description**")+ end++ it "moves a category under an existing parent" do+ category = Fabricate(:category, user: admin)+ parent_category = Fabricate(:category)++ result =+ described_class.update(admin.guardian, category, parent_category_id: parent_category.id)++ expect(result).to eq(true)+ expect(category.reload.parent_category_id).to eq(parent_category.id)+ end++ it "does not move a category under a deleted parent" do+ category = Fabricate(:category, user: admin)+ parent_category = Fabricate(:category)+ parent_category.destroy!++ result =+ described_class.update(admin.guardian, category, parent_category_id: parent_category.id)++ expect(result).to eq(false)+ expect(category.errors.full_messages).to contain_exactly(I18n.t("category.errors.not_found"))+ expect(category.reload.parent_category_id).to be_nil+ end++ it "uses the existing category management permission" do+ category = Fabricate(:category, user: admin)++ expect do+ described_class.update(user.guardian, category, name: "Not allowed")+ end.to raise_error(Discourse::InvalidAccess)++ expect do+ described_class.update(moderator.guardian, category, name: "Moderator category")+ end.to raise_error(Discourse::InvalidAccess)++ SiteSetting.moderators_manage_categories = true++ expect(+ described_class.update(moderator.guardian, category, name: "Moderator category"),+ ).to eq(true)+ expect(category.reload.name).to eq("Moderator category")+ end++ it "does not let a moderator update a category they cannot see" do+ SiteSetting.moderators_manage_categories = true+ group = Fabricate(:group)+ category = Fabricate(:private_category, group:)++ expect do+ described_class.update(moderator.guardian, category, name: "Not visible")+ end.to raise_error(Discourse::InvalidAccess)++ expect(category.reload.name).not_to eq("Not visible")+ end++ it "does not let a moderator move a category under a category they cannot see" do+ SiteSetting.moderators_manage_categories = true+ category = Fabricate(:category)+ group = Fabricate(:group)+ parent_category = Fabricate(:private_category, group:)++ expect do+ described_class.update(moderator.guardian, category, parent_category_id: parent_category.id)+ end.to raise_error(Discourse::InvalidAccess)++ expect(category.reload.parent_category_id).to be_nil+ end++ it "rejects descriptions above the category API limit" do+ category = Fabricate(:category, user: admin)+ result = nil++ expect do+ result =+ described_class.update(+ admin.guardian,+ category,+ description: "a" * (described_class::MAX_DESCRIPTION_LENGTH + 1),+ )+ end.not_to change {+ UserHistory.where(+ action: UserHistory.actions[:change_category_settings],+ acting_user_id: admin.id,+ category_id: category.id,+ ).count+ }++ expect(result).to eq(false)+ expect(category.errors.full_messages).to contain_exactly(+ I18n.t(+ "category.errors.description_too_long",+ count: described_class::MAX_DESCRIPTION_LENGTH,+ ),+ )+ end+ end+enddiff --git a/spec/lib/discourse_mcp/staff_tools_spec.rb b/spec/lib/discourse_mcp/staff_tools_spec.rbindex 348614c0a0d..5a6857d79f5 100644--- a/spec/lib/discourse_mcp/staff_tools_spec.rb+++ b/spec/lib/discourse_mcp/staff_tools_spec.rb@@ -885,6 +885,10 @@ describe DiscourseMcp::Tools do"discourse_get_theme" => [DiscourseMcp::Scopes::THEMES_READ],"discourse_create_theme" => [DiscourseMcp::Scopes::THEMES_WRITE],"discourse_update_theme" => [DiscourseMcp::Scopes::THEMES_WRITE],+ "discourse_get_category" => [DiscourseMcp::Scopes::CATEGORIES_READ],+ "discourse_create_category" => [DiscourseMcp::Scopes::CATEGORIES_WRITE],+ "discourse_update_category" => [DiscourseMcp::Scopes::CATEGORIES_WRITE],+ "discourse_delete_category" => [DiscourseMcp::Scopes::CATEGORIES_WRITE],}actual =@@ -899,6 +903,10 @@ describe DiscourseMcp::Tools doexpect(DiscourseMcp.registry.find(:tool, "discourse_update_site_setting").annotations,).to include("destructiveHint" => true, "idempotentHint" => true, "openWorldHint" => true)+ expect(DiscourseMcp.registry.find(:tool, "discourse_delete_category").annotations).to include(+ "destructiveHint" => true,+ "openWorldHint" => false,+ )schemas = DiscourseMcp.registry.all.map(&:input_schema)expect(schemas.to_json).not_to include('\\\\A', '\\\\z')diff --git a/spec/models/category_spec.rb b/spec/models/category_spec.rbindex 2ddb2481c33..40c40df2a70 100644--- a/spec/models/category_spec.rb+++ b/spec/models/category_spec.rb@@ -1250,6 +1250,52 @@ RSpec.describe Category doFabricate(:category_with_definition, name: "child1", parent_category_id: parent_category.id)end+ it "preserves compatible persisted permissions when moving a private category" do+ private_parent = Fabricate(:private_category, group:)+ child = Fabricate(:private_category, group:)+ permissions = child.category_groups.pluck(:group_id, :permission_type)++ expect(child.update(parent_category_id: private_parent.id)).to eq(true)+ expect(child.reload.category_groups.pluck(:group_id, :permission_type)).to eq(permissions)+ expect(Guardian.new.can_see?(child)).to eq(false)+ end++ it "validates permissions built with a new private subcategory" do+ private_parent = Fabricate(:private_category, group:)+ child = Fabricate(:private_category, parent_category: private_parent, group:)++ expect(child).to be_persisted+ expect(child.category_groups.pluck(:group_id)).to contain_exactly(group.id)+ expect(Guardian.new.can_see?(child)).to eq(false)+ end++ it "rejects moving a private category with a different audience" do+ private_parent = Fabricate(:private_category, group:)+ child = Fabricate(:private_category, group: group2)++ expect(child.update(parent_category_id: private_parent.id)).to eq(false)+ expect(child.errors.full_messages).to include(+ I18n.t("category.errors.permission_conflict", group_names: group2.name),+ )+ expect(child.reload.parent_category_id).to be_nil+ end++ it "allows compatible permissions supplied when creating a private subcategory" do+ private_parent = Fabricate(:private_category, group:)+ child =+ Category.new(+ name: "Private child",+ user: admin,+ parent_category_id: private_parent.id,+ permissions: {+ group.name => :full,+ },+ )++ expect(child.save).to eq(true)+ expect(Guardian.new.can_see?(child.reload)).to eq(false)+ end+context "when changing subcategory permissions" doit "is invalid when permissions are less restrictive" dosubcategory.set_permissions(group => :readonly)diff --git a/spec/models/site_spec.rb b/spec/models/site_spec.rbindex d43e9b28adf..e51d938a4d1 100644--- a/spec/models/site_spec.rb+++ b/spec/models/site_spec.rb@@ -118,8 +118,11 @@ RSpec.describe Site docategory.set_permissions(staff: :full)category.save!- sub_category = Fabricate(:category, parent_category_id: category.id)- expect(Site.new(guardian).categories).not_to include(sub_category)+ sub_category =+ Fabricate(:category, parent_category_id: category.id, permissions: { staff: :full })+ expect(Site.new(guardian).categories.map { |entry| entry[:id] }).not_to include(+ sub_category.id,+ )endit "clears the cache when custom fields change" dodiff --git a/spec/requests/categories_controller_spec.rb b/spec/requests/categories_controller_spec.rbindex 386e61a03b3..806523f376b 100644--- a/spec/requests/categories_controller_spec.rb+++ b/spec/requests/categories_controller_spec.rb@@ -829,10 +829,7 @@ RSpec.describe CategoriesController doit "preloads user fields for restricted categories" docategory.set_permissions(admins: :full)category.save!- Fabricate(:category, parent_category: category).tap do |subcategory|- subcategory.set_permissions(admins: :full)- subcategory.save!- end+ Fabricate(:category, parent_category: category, permissions: { admins: :full })sign_in(admin)get "/c/#{category.slug}/find_by_slug.json"diff --git a/spec/requests/mcp_categories_spec.rb b/spec/requests/mcp_categories_spec.rbnew file mode 100644index 00000000000..88def39d212--- /dev/null+++ b/spec/requests/mcp_categories_spec.rb@@ -0,0 +1,428 @@+# frozen_string_literal: true++describe "MCP category tools" do+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:admin)+ fab!(:scope_group, :group)++ before do+ SiteSetting.mcp_server_enabled = true+ scope_group.add(user)+ %w[+ discourse_create_category+ discourse_get_category+ discourse_update_category+ discourse_delete_category+ ].each { |identifier| McpPrimitive.create!(kind: "tool", identifier:, enabled: true) }+ end++ def authorize(*extra_scopes, auth_user: user)+ scope_group.add(auth_user)+ scopes = [DiscourseMcp::INITIAL_SCOPE, *extra_scopes]+ scopes.each { |scope| McpGroupScope.find_or_create_by!(group: scope_group, scope:) }+ client =+ McpOauthClient.create!(+ client_id: SecureRandom.hex,+ name: "Category tool test client",+ registration_type: "pre_registered",+ trust_state: "approved",+ redirect_uris: ["http://127.0.0.1/callback"],+ )+ authorization =+ DiscourseMcp::OAuth::AuthorizationGrant.create!(+ user: auth_user,+ client:,+ redirect_uri: client.redirect_uris.first,+ requested_scopes: scopes,+ )+ @token = McpOauthAccessToken.issue!(authorization:)+ end++ def call_tool(name, arguments)+ post "/mcp",+ params: {+ jsonrpc: "2.0",+ id: 1,+ method: "tools/call",+ params: {+ name:,+ arguments:,+ },+ }.to_json,+ headers: {+ "HTTP_AUTHORIZATION" => "Bearer #{@token}",+ "CONTENT_TYPE" => "application/json",+ "HTTP_ACCEPT" => "application/json, text/event-stream",+ "HTTP_MCP_PROTOCOL_VERSION" => DiscourseMcp::LEGACY_PROTOCOL_VERSION,+ }+ end++ def call_create_category(arguments)+ call_tool("discourse_create_category", arguments)+ end++ it "requires the category write scope" do+ authorize++ call_create_category(name: "Missing scope")++ expect(response.status).to eq(403)+ expect(response.headers["WWW-Authenticate"]).to include(+ 'error="insufficient_scope"',+ 'scope="mcp:categories:write"',+ )+ expect(Category.find_by(name: "Missing scope")).to be_nil+ end++ it "does not let a regular user create a category when the token has scope" do+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE)++ call_create_category(name: "Not allowed", parent_category_id: 999_999_999)++ expect(response.status).to eq(403)+ expect(Category.find_by(name: "Not allowed")).to be_nil+ end++ it "creates a subcategory and logs the action for an authorized admin" do+ parent_category = Fabricate(:category)+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: admin)++ expect do+ call_create_category(+ name: "猫 support",+ description: "Help with cats",+ parent_category_id: parent_category.id,+ color: "0088CC",+ text_color: "FFFFFF",+ emoji: "cat",+ icon: "paw",+ )+ end.to change {+ UserHistory.where(+ action: UserHistory.actions[:create_category],+ acting_user_id: admin.id,+ ).count+ }.by(1)++ expect(response.status).to eq(200)+ result = response.parsed_body.dig("result", "structuredContent")+ category = Category.find(result.fetch("id"))+ expect(result).to include("name" => "猫 support", "slug" => category.slug)+ expect(category).to have_attributes(+ parent_category_id: parent_category.id,+ user_id: admin.id,+ style_type: "emoji",+ emoji: "cat",+ icon: "paw",+ )+ end++ it "rejects a public subcategory beneath a private parent" do+ group = Fabricate(:group)+ parent = Fabricate(:private_category, group:)+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: admin)++ expect do+ call_create_category(name: "Public child", parent_category_id: parent.id)+ end.not_to change(Category, :count)++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(Guardian.new.can_see?(parent)).to eq(false)+ end++ it "rejects moving a public category beneath a private parent" do+ group = Fabricate(:group)+ parent = Fabricate(:private_category, group:)+ category = Fabricate(:category)+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: admin)++ call_tool("discourse_update_category", category_id: category.id, parent_category_id: parent.id)++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(category.reload.parent_category_id).to be_nil+ expect(Guardian.new.can_see?(category)).to eq(true)+ expect(Guardian.new.can_see?(parent)).to eq(false)+ end++ it "does not create a category with an invalid emoji" do+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: admin)++ call_create_category(name: "Invalid emoji", emoji: "not-a-real-emoji")++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(Category.find_by(name: "Invalid emoji")).to be_nil+ end++ it "does not create a subcategory under a deleted category" do+ parent_category = Fabricate(:category)+ parent_category.destroy!+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: admin)++ call_create_category(name: "Orphaned", parent_category_id: parent_category.id)++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(response.parsed_body.dig("result", "content")).to eq(+ [{ "type" => "text", "text" => I18n.t("category.errors.not_found") }],+ )+ expect(Category.find_by(name: "Orphaned")).to be_nil+ end++ it "requires the category read scope for management details" do+ category = Fabricate(:category)+ authorize++ call_tool("discourse_get_category", category_id: category.id)++ expect(response.status).to eq(403)+ expect(response.headers["WWW-Authenticate"]).to include(+ 'error="insufficient_scope"',+ 'scope="mcp:categories:read"',+ )+ end++ it "returns a tool error when a category has been deleted" do+ category = Fabricate(:category)+ category.destroy!+ authorize(DiscourseMcp::Scopes::CATEGORIES_READ, auth_user: admin)++ call_tool("discourse_get_category", category_id: category.id)++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(response.parsed_body.dig("result", "content")).to eq(+ [{ "type" => "text", "text" => I18n.t("mcp.errors.category_not_found") }],+ )+ end++ it "requires the category write scope to update a category" do+ category = Fabricate(:category, name: "Original")+ authorize(DiscourseMcp::Scopes::CATEGORIES_READ, auth_user: admin)++ call_tool("discourse_update_category", category_id: category.id, name: "Changed")++ expect(response.status).to eq(403)+ expect(response.headers["WWW-Authenticate"]).to include(+ 'error="insufficient_scope"',+ 'scope="mcp:categories:write"',+ )+ expect(category.reload.name).to eq("Original")+ end++ it "requires the category write scope to delete a category" do+ category = Fabricate(:category)+ authorize(DiscourseMcp::Scopes::CATEGORIES_READ, auth_user: admin)++ call_tool(+ "discourse_delete_category",+ category_id: category.id,+ expected_name: category.name,+ confirm: true,+ )++ expect(response.status).to eq(403)+ expect(response.headers["WWW-Authenticate"]).to include(+ 'error="insufficient_scope"',+ 'scope="mcp:categories:write"',+ )+ expect(Category.exists?(category.id)).to eq(true)+ end++ it "does not let a regular user manage categories when the token has scope" do+ category = Fabricate(:category, name: "Original")+ authorize(DiscourseMcp::Scopes::CATEGORIES_READ, DiscourseMcp::Scopes::CATEGORIES_WRITE)++ call_create_category(name: "Not allowed")+ expect(response.status).to eq(403)++ call_tool("discourse_get_category", category_id: category.id)+ expect(response.status).to eq(403)++ call_tool("discourse_update_category", category_id: category.id, name: "Changed")+ expect(response.status).to eq(403)++ call_tool(+ "discourse_delete_category",+ category_id: category.id,+ expected_name: category.name,+ confirm: true,+ )+ expect(response.status).to eq(403)++ expect(Category.find_by(name: "Not allowed")).to be_nil+ expect(category.reload.name).to eq("Original")+ end++ it "lets an authorized admin read and update basic category details" do+ parent_category = Fabricate(:category)+ category = Fabricate(:category_with_definition, name: "Original", user: admin)+ authorize(+ DiscourseMcp::Scopes::CATEGORIES_READ,+ DiscourseMcp::Scopes::CATEGORIES_WRITE,+ auth_user: admin,+ )++ call_tool("discourse_get_category", category_id: category.id)++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "structuredContent", "category")).to include(+ "id" => category.id,+ "name" => "Original",+ "can_delete" => true,+ )++ call_tool(+ "discourse_update_category",+ category_id: category.id,+ name: "猫 support",+ description: "Updated **description**",+ parent_category_id: parent_category.id,+ emoji: "cat",+ )++ expect(response.status).to eq(200)+ result = response.parsed_body.dig("result", "structuredContent", "category")+ expect(result).to include(+ "id" => category.id,+ "name" => "猫 support",+ "parent_category_id" => parent_category.id,+ "description" => "Updated **description**",+ "style_type" => "emoji",+ "emoji" => "cat",+ )+ expect(category.reload.topic.first_post.raw).to eq("Updated **description**")+ history =+ UserHistory.find_by(+ action: UserHistory.actions[:change_category_settings],+ acting_user_id: admin.id,+ category_id: category.id,+ subject: "name",+ )+ expect(history).to have_attributes(previous_value: "Original", new_value: "猫 support")+ end++ it "does not persist or log an invalid category update" do+ category = Fabricate(:category, name: "Original")+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: admin)++ expect do+ call_tool("discourse_update_category", category_id: category.id, emoji: "not-an-emoji")+ end.not_to change {+ UserHistory.where(+ action: UserHistory.actions[:change_category_settings],+ category_id: category.id,+ ).count+ }++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(category.reload.style_type).to eq("square")+ end++ it "uses moderator category permissions in addition to OAuth scope" do+ SiteSetting.moderators_manage_categories = true+ moderator = Fabricate(:moderator)+ visible_category = Fabricate(:category, name: "Visible")+ group = Fabricate(:group)+ hidden_category = Fabricate(:private_category, group:)+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: moderator)++ call_tool(+ "discourse_update_category",+ category_id: visible_category.id,+ name: "Updated by moderator",+ )+ expect(response.status).to eq(200)++ call_tool("discourse_update_category", category_id: hidden_category.id, name: "Not visible")+ expect(response.status).to eq(403)++ call_tool(+ "discourse_update_category",+ category_id: visible_category.id,+ parent_category_id: hidden_category.id,+ )+ expect(response.status).to eq(403)++ call_tool(+ "discourse_delete_category",+ category_id: hidden_category.id,+ expected_name: "Guessed name",+ confirm: true,+ )+ expect(response.status).to eq(403)++ expect(visible_category.reload.name).to eq("Updated by moderator")+ expect(visible_category.parent_category_id).to be_nil+ expect(hidden_category.reload.name).not_to eq("Not visible")+ end++ it "requires explicit confirmation and the current name before deleting" do+ category = Fabricate(:category)+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: admin)++ call_tool(+ "discourse_delete_category",+ category_id: category.id,+ expected_name: category.name,+ confirm: false,+ )+ expect(response.parsed_body.dig("result", "isError")).to eq(true)++ call_tool(+ "discourse_delete_category",+ category_id: category.id,+ expected_name: "Wrong name",+ confirm: true,+ )+ expect(response.parsed_body.dig("result", "isError")).to eq(true)++ expect(Category.exists?(category.id)).to eq(true)+ end++ it "deletes an empty category and logs the action for an authorized admin" do+ category = Fabricate(:category)+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: admin)++ expect do+ call_tool(+ "discourse_delete_category",+ category_id: category.id,+ expected_name: category.name,+ confirm: true,+ )+ end.to change {+ UserHistory.where(+ action: UserHistory.actions[:delete_category],+ acting_user_id: admin.id,+ category_id: category.id,+ ).count+ }.by(1)++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "structuredContent")).to eq(+ "deleted" => true,+ "category_id" => category.id,+ )+ expect(Category.exists?(category.id)).to eq(false)+ end++ it "does not delete a category that contains topics" do+ category = Fabricate(:category)+ category.update!(topic_count: 1)+ authorize(DiscourseMcp::Scopes::CATEGORIES_WRITE, auth_user: admin)++ call_tool(+ "discourse_delete_category",+ category_id: category.id,+ expected_name: category.name,+ confirm: true,+ )++ expect(response.status).to eq(403)+ expect(Category.exists?(category.id)).to eq(true)+ end+end