A platform for community discussion. Free, open, simple.
FEATURE: Add user administration tools to the MCP server (#44282)
Natalie Taya6660fe1f9a9
diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rbindex 24d55e714e1..3aa714a1096 100644--- a/app/controllers/admin/users_controller.rb+++ b/app/controllers/admin/users_controller.rb@@ -299,13 +299,7 @@ class Admin::UsersController < Admin::StaffControllerenddef approve- guardian.ensure_can_approve!(@user)-- reviewable =- ReviewableUser.find_by(target: @user) ||- Jobs::CreateUserReviewable.new.execute(user_id: @user.id).reviewable-- reviewable.perform(current_user, :approve_user, allow_reviewed: true)+ UserApprover.approve(guardian, @user)render body: nilend@@ -321,23 +315,16 @@ class Admin::UsersController < Admin::StaffControllerenddef activate- guardian.ensure_can_activate!(@user)- # ensure there is an active email token- if [email protected]_tokens.active.exists?- @user.email_tokens.create!(email: @user.email, scope: EmailToken.scopes[:signup])- end- @user.activate- StaffActionLogger.new(current_user).log_user_activate(@user, I18n.t("user.activated_by_staff"))+ UserActivator.activate(guardian, @user)render json: success_jsonenddef deactivate- guardian.ensure_can_deactivate!(@user)- @user.deactivate(current_user)- StaffActionLogger.new(current_user).log_user_deactivate(+ UserDeactivator.deactivate(+ guardian,@user,- I18n.t("user.deactivated_by_staff"),- params.slice(:context),+ context: params.slice(:context),+ allow_deletion: true,)refresh_browser @userrender json: success_jsondiff --git a/app/controllers/users_controller.rb b/app/controllers/users_controller.rbindex 8d12b00952a..d6d439f5300 100644--- a/app/controllers/users_controller.rb+++ b/app/controllers/users_controller.rb@@ -734,7 +734,9 @@ class UsersController < ApplicationControllerif SiteSetting.enable_discourse_connect && !is_api?return fail_with("login.new_registrations_disabled_discourse_connect")end- return fail_with("login.new_registrations_disabled") unless SiteSetting.allow_new_registrations+ if error = UserCreator.registration_error(invite_code: params[:invite_code])+ return fail_with(error)+ endif params[:password] && params[:password].length > User.max_password_lengthreturn fail_with("login.password_too_long")@@ -751,11 +753,6 @@ class UsersController < ApplicationControllerreturn fail_with("login.email_too_long") if params[:email].length > 254 + 1 + 253- if SiteSetting.require_invite_code &&- SiteSetting.invite_code.strip.downcase != params[:invite_code].strip.downcase- return fail_with("login.wrong_invite_code")- end-if clashing_with_existing_route?(params[:username]) ||User.reserved_username?(params[:username])return fail_with("login.reserved_username")@@ -786,22 +783,8 @@ class UsersController < ApplicationControllerReviewableUser.set_approved_fields!(user, current_user)end- # Handle custom fields- user_fields = UserField.all- if user_fields.present?- fields = user.custom_fields-- user_fields.each do |f|- field_val = clean_custom_field_values(f)- field_val = nil if field_val == "false"- if field_val.blank?- return fail_with("login.missing_user_field") if f.required?- else- fields["#{User::USER_FIELD_PREFIX}#{f.id}"] = field_val[0...UserField.max_length]- end- end-- user.custom_fields = fields+ if error = UserCreator.assign_signup_fields(user) { |field| clean_custom_field_values(field) }+ return fail_with(error)end# Handle associated accounts@@ -2190,19 +2173,7 @@ class UsersController < ApplicationControllerenddef clean_custom_field_values(field)- field_values = params.dig(:user_fields, field.id.to_s)-- return field_values if field_values.nil? || field_values.empty?-- if field.field_type == "dropdown"- field.user_field_options.find_by_value(field_values)&.value- elsif field.field_type == "multiselect"- field_values = Array.wrap(field_values)- bad_values = field_values - field.user_field_options.map(&:value)- field_values - bad_values- else- field_values- end+ UserCreator.clean_custom_field_values(field, params.dig(:user_fields, field.id.to_s))enddef password_reset_find_user(token, committing_change:)diff --git a/app/services/user_activator.rb b/app/services/user_activator.rbindex b5e2c0f2b38..3e8bb797a97 100644--- a/app/services/user_activator.rb+++ b/app/services/user_activator.rb@@ -1,6 +1,15 @@# frozen_string_literal: trueclass UserActivator+ def self.activate(guardian, user)+ guardian.ensure_can_activate!(user)+ if !user.email_tokens.active.exists?+ user.email_tokens.create!(email: user.email, scope: EmailToken.scopes[:signup])+ end+ user.activate+ StaffActionLogger.new(guardian.user).log_user_activate(user, I18n.t("user.activated_by_staff"))+ end+attr_reader :user, :request, :session, :cookies, :messagedef initialize(user, request, session, cookies)diff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 95a16dcf86d..2e6b23e4826 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -81,8 +81,10 @@ en:top_period_only_for_top_view: "Top period is only supported by the top view"upload_not_found: "Upload not found"upload_too_large: "The upload is too large"- user_update_required: "Provide at least one profile field to update"+ user_create_failed: "The user could not be created"+ user_deactivation_pending_review: "Review this user's pending approval before deactivating the account."user_not_found: "User not found"+ user_update_required: "Provide at least one profile field to update"oauth:authorize_title: "Authorize MCP client"client_request: "%{client_name} is requesting access to %{site_name}."@@ -3617,6 +3619,7 @@ en:wrong_invite_code: "The invite code you entered was incorrect."reserved_username: "That username is not allowed."missing_user_field: "You have not completed all the required user fields"+ missing_user_field_details: "Complete the required user field '%{name}' (ID: %{id})."missing_username: "Please enter a username"missing_full_name: "Please enter your full name"auth_complete: "Authentication is complete."diff --git a/lib/discourse_mcp.rb b/lib/discourse_mcp.rbindex 713192c3f0e..ed8ab086e7d 100644--- a/lib/discourse_mcp.rb+++ b/lib/discourse_mcp.rb@@ -19,6 +19,8 @@ module DiscourseMcpTHEMES_READ = "mcp:themes:read"THEMES_WRITE = "mcp:themes:write"GROUPS_READ = "mcp:groups:read"+ USERS_READ = "mcp:users:read"+ USERS_WRITE = "mcp:users:write"endPROTOCOL_VERSION = "2026-07-28"diff --git a/lib/discourse_mcp/core_primitives.rb b/lib/discourse_mcp/core_primitives.rbindex 4245109960a..ece9b3a0f93 100644--- a/lib/discourse_mcp/core_primitives.rb+++ b/lib/discourse_mcp/core_primitives.rb@@ -70,6 +70,7 @@ module DiscourseMcpregister_theme_tools(registry)register_group_tools(registry)register_category_tools(registry)+ register_user_administration_tools(registry)register_resources(registry)register_prompts(registry)end@@ -1939,6 +1940,153 @@ module DiscourseMcp)end+ def register_user_administration_tools(registry)+ register_tool(+ registry,+ "discourse_list_users",+ title: "List users",+ description: "Lists and filters users visible through Discourse's staff user directory.",+ implementation: Tools::ListUsers,+ input_schema:+ object_schema(+ {+ query: {+ type: "string",+ enum: Tools::ListUsers::QUERIES,+ default: "active",+ },+ filter: {+ type: "string",+ minLength: 1,+ maxLength: 500,+ },+ order: {+ type: "string",+ enum: Tools::ListUsers::ORDERS,+ },+ ascending: {+ type: "boolean",+ default: false,+ },+ include_emails: {+ type: "boolean",+ default: false,+ },+ page: {+ type: "integer",+ minimum: 0,+ default: 0,+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: 100,+ default: 100,+ },+ },+ ),+ annotations: READ_ONLY,+ risk: :administration,+ )+ register_tool(+ registry,+ "discourse_create_user",+ title: "Create user",+ description:+ "Creates a user as an administrator. Registrations must be open. Supply the site's invite code if required and required user fields keyed by field ID. Missing-field errors identify the field name and ID.",+ implementation: Tools::CreateUser,+ input_schema:+ object_schema(+ {+ username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ email: {+ type: "string",+ format: "email",+ maxLength: 508,+ },+ name: {+ type: "string",+ minLength: 1,+ maxLength: 255,+ },+ password: {+ type: "string",+ minLength: 1,+ maxLength: 200,+ },+ invite_code: {+ type: "string",+ maxLength: 1000,+ },+ user_fields: {+ type: "object",+ additionalProperties: false,+ patternProperties: {+ "^[1-9][0-9]*$" => {+ oneOf: [+ { type: "string", maxLength: 2048 },+ { type: "array", maxItems: 2048, items: { type: "string", maxLength: 2048 } },+ ],+ },+ },+ },+ active: {+ type: "boolean",+ default: true,+ },+ approved: {+ type: "boolean",+ default: true,+ },+ upload_id: {+ type: "integer",+ minimum: 1,+ },+ },+ required: %w[username email name password],+ ),+ annotations: EXTERNAL_SIDE_EFFECT,+ risk: :administration,+ )+ register_tool(+ registry,+ "discourse_manage_user_activation",+ title: "Manage user activation",+ description:+ "Activates, approves, activates and approves, or deactivates an eligible user.",+ implementation: Tools::ManageUserActivation,+ input_schema:+ object_schema(+ {+ username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ action: {+ type: "string",+ enum: Tools::ManageUserActivation::ACTIONS,+ },+ confirm: {+ const: true,+ },+ },+ required: %w[username action confirm],+ ),+ annotations: {+ readOnlyHint: false,+ destructiveHint: true,+ idempotentHint: true,+ openWorldHint: true,+ },+ risk: :administration,+ )+ end+def register_resources(registry)register_resource_template(registry,diff --git a/lib/discourse_mcp/primitive.rb b/lib/discourse_mcp/primitive.rbindex 16eb5f6760f..ade5b939192 100644--- a/lib/discourse_mcp/primitive.rb+++ b/lib/discourse_mcp/primitive.rb@@ -80,8 +80,6 @@ module DiscourseMcpannotations.except("title").values.any? { |value| value != true && value != false }raise ArgumentError, "invalid MCP primitive annotations"end- rescue JSONSchemer::InvalidSchema- raise ArgumentError, "invalid MCP primitive schema"endendenddiff --git a/lib/discourse_mcp/server.rb b/lib/discourse_mcp/server.rbindex 69da122ff6d..a1eb974160f 100644--- a/lib/discourse_mcp/server.rb+++ b/lib/discourse_mcp/server.rb@@ -48,10 +48,6 @@ module DiscourseMcpResponse.new(http_status: 403, body: failure(payload&.dig("id"), error), headers: {})rescue RateLimiter::LimitExceededraise- rescue JSONSchemer::InvalidSchema => error- protocol_error = Error.new("Invalid schema", code: -32_000, http_status: 500)- Discourse.warn_exception(error, message: "MCP schema validation failed")- Response.new(http_status: 500, body: failure(payload&.dig("id"), protocol_error), headers: {})rescue StandardError => errorprotocol_error = Error.new("Internal error", code: -32_603, http_status: 500)Discourse.warn_exception(error, message: "MCP request failed")@@ -268,10 +264,8 @@ module DiscourseMcptool = authorized_primitive(:tool, params["name"], "Unknown tool")arguments = params["arguments"].is_a?(Hash) ? params["arguments"] : {}- errors = JSONSchemer.schema(tool.input_schema).validate(arguments).to_a- if errors.present?- raise Error.new("Invalid tool arguments", code: -32_602, data: { errors: errors.first(20) })- end+ errors = argument_validation_errors(tool.input_schema, arguments)+ raise Error.new("Invalid tool arguments", code: -32_602, data: { errors: }) if errors.present?result = tool.implementation.call(arguments: arguments, request_context: request_context)complete_result(**result.symbolize_keys)@@ -346,15 +340,9 @@ module DiscourseMcpdef get_prompt(params)prompt = authorized_primitive(:prompt, params["name"], "Prompt not found")arguments = params["arguments"].is_a?(Hash) ? params["arguments"] : {}- errors = JSONSchemer.schema(prompt.input_schema).validate(arguments).to_a+ errors = argument_validation_errors(prompt.input_schema, arguments)if errors.present?- raise Error.new(- "Invalid prompt arguments",- code: -32_602,- data: {- errors: errors.first(20),- },- )+ raise Error.new("Invalid prompt arguments", code: -32_602, data: { errors: })endcomplete_result(**prompt@@ -364,6 +352,14 @@ module DiscourseMcp)end+ def argument_validation_errors(schema, arguments)+ JSONSchemer+ .schema(schema)+ .validate(arguments)+ .first(20)+ .map { |error| error.slice("type", "data_pointer", "schema_pointer") }+ end+def complete_result(**values)values.compact.merge(resultType: "complete",diff --git a/lib/discourse_mcp/tools/users.rb b/lib/discourse_mcp/tools/users.rbindex a1be71e0277..d1b413e2c04 100644--- a/lib/discourse_mcp/tools/users.rb+++ b/lib/discourse_mcp/tools/users.rb@@ -33,6 +33,164 @@ module DiscourseMcpendend+ class ListUsers+ REQUIRED_SCOPES = [Scopes::USERS_READ].freeze+ QUERIES = %w[active new staff suspended silenced pending staged].freeze+ ORDERS = %w[created last_emailed seen username trust_level days_visited posts].freeze+ OUTPUT_SCHEMA =+ OutputSchema.object(users: OutputSchema::OBJECT_ARRAY, meta: OutputSchema::OBJECT)++ def self.call(arguments:, request_context:)+ guardian = request_context.guardian+ raise Discourse::InvalidAccess if !guardian.is_staff?++ page = arguments.fetch("page", 0)+ limit = arguments.fetch("limit", 100)+ include_emails = arguments.fetch("include_emails", false) && guardian.can_check_emails?(nil)+ query =+ AdminUserIndexQuery.new(+ {+ query: arguments.fetch("query", "active"),+ filter: arguments["filter"],+ order: arguments["order"],+ asc: arguments.fetch("ascending", false),+ show_emails: include_emails ? "true" : nil,+ },+ guardian:,+ )+ users_query = query.find_users_query+ users_query = users_query.preload(:primary_email) if include_emails+ users = users_query.offset(page * limit).limit(limit + 1).to_a+ has_more = users.length > limit+ users = users.first(limit)++ if include_emails+ StaffActionLogger.new(guardian.user).log_show_emails(users, context: "MCP user listing")+ end++ rows = users.map { |user| user_json(user, guardian, include_emails:) }+ ToolHelpers.text_and_structured(+ users: rows,+ meta: {+ page:,+ limit:,+ returned: rows.length,+ has_more:,+ next_page: has_more ? page + 1 : nil,+ },+ )+ end++ def self.user_json(user, guardian, include_emails:)+ {+ id: user.id,+ username: user.username,+ name: user.name,+ email: include_emails && guardian.can_check_emails?(user) ? user.email : nil,+ avatar_template: user.avatar_template,+ trust_level: user.trust_level,+ created_at: user.created_at.iso8601,+ last_seen_at: user.last_seen_at&.iso8601,+ active: user.active?,+ approved: user.approved?,+ admin: user.admin?,+ moderator: user.moderator?,+ suspended: user.suspended?,+ silenced: user.silenced?,+ staged: user.staged?,+ }+ end+ private_class_method :user_json+ end++ class CreateUser+ REQUIRED_SCOPES = [Scopes::USERS_WRITE].freeze+ OUTPUT_SCHEMA =+ OutputSchema.object(+ created: OutputSchema::BOOLEAN,+ user_id: OutputSchema::INTEGER,+ username: OutputSchema::STRING,+ name: OutputSchema::STRING_OR_NULL,+ email: OutputSchema::STRING,+ active: OutputSchema::BOOLEAN,+ approved: OutputSchema::BOOLEAN,+ avatar_updated: OutputSchema::BOOLEAN,+ )++ def self.call(arguments:, request_context:)+ user = UserCreator.create(request_context.guardian, arguments)+ if !user.persisted? || user.errors.present?+ message =+ user.errors.full_messages.to_sentence.presence ||+ I18n.t("mcp.errors.user_create_failed")+ raise ToolError, message+ end++ ToolHelpers.text_and_structured(+ created: true,+ user_id: user.id,+ username: user.username,+ name: user.name,+ email: user.email,+ active: user.active?,+ approved: user.approved?,+ avatar_updated: arguments["upload_id"].present?,+ )+ rescue UserCreator::UploadNotFound+ raise ToolError, I18n.t("mcp.errors.upload_not_found")+ end+ end++ class ManageUserActivation+ REQUIRED_SCOPES = [Scopes::USERS_WRITE].freeze+ ACTIONS = %w[activate approve activate_and_approve deactivate].freeze+ OUTPUT_SCHEMA =+ OutputSchema.object(+ success: OutputSchema::BOOLEAN,+ username: OutputSchema::STRING,+ requested_action: OutputSchema::STRING,+ completed_actions: OutputSchema::STRING_ARRAY,+ active: OutputSchema::BOOLEAN,+ approved: OutputSchema::BOOLEAN,+ )++ def self.call(arguments:, request_context:)+ user = User.find_by_username(arguments.fetch("username"))+ raise ToolError, I18n.t("mcp.errors.user_not_found") if user.blank?++ action = arguments.fetch("action")+ completed_actions = action == "activate_and_approve" ? %w[activate approve] : [action]+ User.transaction do+ completed_actions.each do |completed_action|+ perform_action(completed_action, request_context.guardian, user)+ end+ end+ user.reload+ ToolHelpers.text_and_structured(+ success: true,+ username: user.username,+ requested_action: action,+ completed_actions:,+ active: user.active?,+ approved: user.approved?,+ )+ rescue UserDeactivator::PendingReview+ raise ToolError, I18n.t("mcp.errors.user_deactivation_pending_review")+ end++ def self.perform_action(action, guardian, user)+ case action+ when "activate"+ UserActivator.activate(guardian, user)+ when "approve"+ UserApprover.approve(guardian, user)+ when "deactivate"+ UserDeactivator.deactivate(guardian, user, context: { context: "MCP user activation" })+ end+ end+ private_class_method :perform_action+ end+class ListDirectoryItemsREQUIRED_SCOPES = [Scopes::CONTENT_READ].freezePAGE_SIZE = ::DirectoryItemsQuery::PAGE_SIZE@@ -380,7 +538,7 @@ module DiscourseMcpUser.transaction doupdated = UserUpdater.new(request_context.user, user).update(attributes)raise ToolError, user.errors.full_messages.join(", ") if !updated- user.pick_avatar!(upload.id, type: :custom) if upload+ UserAvatarUpdater.update(request_context.guardian, user, upload) if uploadenduser.reload@@ -405,15 +563,10 @@ module DiscourseMcpdef self.avatar_upload(upload_id, user, guardian)return if upload_id.blank?- if SiteSetting.discourse_connect_overrides_avatar || SiteSetting.auth_overrides_avatar ||- !user.in_any_groups?(SiteSetting.uploaded_avatars_allowed_groups_map)- raise Discourse::InvalidAccess- end-+ guardian.ensure_can_pick_avatar_source!(user, "custom")upload = Upload.find_by(id: upload_id, user_id: user.id)raise ToolError, I18n.t("mcp.errors.upload_not_found") if upload.blank?- guardian.ensure_can_pick_avatar!(user.user_avatar || user.build_user_avatar, upload)uploadendprivate_class_method :avatar_uploaddiff --git a/lib/user_approver.rb b/lib/user_approver.rbnew file mode 100644index 00000000000..54b95f679f4--- /dev/null+++ b/lib/user_approver.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++class UserApprover+ def self.approve(guardian, user)+ guardian.ensure_can_approve!(user)+ reviewable = ReviewableUser.find_by(target: user)+ if !reviewable+ job = Jobs::CreateUserReviewable.new+ job.execute(user_id: user.id)+ reviewable =+ job.reviewable ||+ ReviewableUser.needs_review!(+ target: user,+ created_by: Discourse.system_user,+ reviewable_by_moderator: true,+ payload: ReviewableUser.payload_for(user),+ )+ end++ reviewable.perform(guardian.user, :approve_user, allow_reviewed: true)+ end+enddiff --git a/lib/user_avatar_updater.rb b/lib/user_avatar_updater.rbnew file mode 100644index 00000000000..40a80a48f3f--- /dev/null+++ b/lib/user_avatar_updater.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++class UserAvatarUpdater+ def self.update(guardian, user, upload, type: "custom")+ guardian.ensure_can_pick_avatar_source!(user, type)+ avatar = user.user_avatar || user.build_user_avatar+ guardian.ensure_can_pick_avatar!(avatar, upload)+ user.pick_avatar!(upload&.id, type: type.to_sym)+ SiteSetting.use_site_small_logo_as_system_avatar = false if user.is_system_user?+ end+enddiff --git a/lib/user_creator.rb b/lib/user_creator.rbnew file mode 100644index 00000000000..3c01fe7112e--- /dev/null+++ b/lib/user_creator.rb@@ -0,0 +1,155 @@+# frozen_string_literal: true++class UserCreator+ class UploadNotFound < StandardError+ end++ def self.create(guardian, attributes)+ new(guardian, attributes).create+ end++ def self.registration_error(invite_code: nil)+ return "login.new_registrations_disabled" unless SiteSetting.allow_new_registrations+ if SiteSetting.require_invite_code &&+ SiteSetting.invite_code.strip.downcase != invite_code.to_s.strip.downcase+ "login.wrong_invite_code"+ end+ end++ def self.assign_signup_fields(user)+ fields = user.custom_fields+ UserField.all.each do |field|+ value = yield(field)+ value = nil if value == "false"+ if value.blank?+ if field.required?+ user.errors.add(+ :base,+ I18n.t("login.missing_user_field_details", name: field.name, id: field.id),+ )+ return "login.missing_user_field"+ end+ else+ fields["#{User::USER_FIELD_PREFIX}#{field.id}"] = value[0...UserField.max_length]+ end+ end+ user.custom_fields = fields+ nil+ end++ def self.clean_custom_field_values(field, field_values)+ return field_values if field_values.nil? || field_values.empty?++ if field.field_type == "dropdown"+ field.user_field_options.find_by_value(field_values)&.value+ elsif field.field_type == "multiselect"+ field_values = Array.wrap(field_values)+ bad_values = field_values - field.user_field_options.map(&:value)+ field_values - bad_values+ else+ field_values+ end+ end++ def initialize(guardian, attributes)+ @guardian = guardian+ @attributes = attributes.to_h.with_indifferent_access+ end++ def create+ raise Discourse::InvalidAccess if !guardian.is_admin?++ user = User.new+ if error = self.class.registration_error(invite_code: attributes[:invite_code])+ user.errors.add(:base, I18n.t(error))+ return user+ end++ error =+ self+ .class+ .assign_signup_fields(user) do |field|+ self.class.clean_custom_field_values(field, attributes.dig(:user_fields, field.id.to_s))+ end+ return user if error+ custom_fields = user.custom_fields++ if attributes[:password].blank?+ user.errors.add(:password, :blank)+ return user+ end++ upload = find_upload+ user = nil+ User.transaction do+ user =+ User::Action::CreateFromVerifiedEmail.call(+ email: Email.downcase(attributes[:email]),+ username: attributes[:username],+ name: attributes[:name],+ password: attributes[:password],+ )+ raise ActiveRecord::Rollback if !user.persisted? || user.errors.present?++ user.custom_fields.merge!(custom_fields)+ user.save!++ if attributes.fetch(:approved, true)+ approve(user)+ else+ user.update!(approved: false, approved_by_id: nil, approved_at: nil)+ end+ if attributes.fetch(:active, true)+ activate(user)+ else+ send_activation_email(user)+ end+ update_avatar(user, upload) if upload+ log_creation(user)+ end+ user+ end++ private++ attr_reader :guardian, :attributes++ def find_upload+ return if attributes[:upload_id].blank?++ Upload.find_by(id: attributes[:upload_id]) || raise(UploadNotFound)+ end++ def approve(user)+ return if user.approved?++ ReviewableUser.set_approved_fields!(user, guardian.user)+ user.save!+ end++ def activate(user)+ user.activate+ user.enqueue_welcome_message("welcome_user") if user.guardian.can_access_forum?+ end++ def send_activation_email(user)+ email_token = user.email_tokens.create!(email: user.email, scope: EmailToken.scopes[:signup])+ EmailToken.enqueue_signup_email(email_token)+ end++ def update_avatar(user, upload)+ user = User.find(user.id)+ Group.refresh_automatic_groups_for_user!(user)+ UserAvatarUpdater.update(guardian, user, upload)+ end++ def log_creation(user)+ StaffActionLogger.new(guardian.user).log_custom(+ "create_user",+ target_user_id: user.id,+ subject: user.username,+ active: user.active?,+ approved: user.approved?,+ )+ end+enddiff --git a/lib/user_deactivator.rb b/lib/user_deactivator.rbnew file mode 100644index 00000000000..b96421db9f8--- /dev/null+++ b/lib/user_deactivator.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++class UserDeactivator+ class PendingReview < StandardError+ end++ def self.deactivate(guardian, user, context: {}, allow_deletion: false)+ guardian.ensure_can_deactivate!(user)+ User.transaction do+ user.lock!+ guardian.ensure_can_deactivate!(user)+ raise PendingReview if !allow_deletion && ReviewableUser.pending.exists?(target: user)+ user.deactivate(guardian.user)+ raise PendingReview if !allow_deletion && !User.exists?(user.id)+ StaffActionLogger.new(guardian.user).log_user_deactivate(+ user,+ I18n.t("user.deactivated_by_staff"),+ context,+ )+ end+ end+enddiff --git a/spec/lib/discourse_mcp/primitive_spec.rb b/spec/lib/discourse_mcp/primitive_spec.rbnew file mode 100644index 00000000000..fd74e9350e2--- /dev/null+++ b/spec/lib/discourse_mcp/primitive_spec.rb@@ -0,0 +1,28 @@+# frozen_string_literal: true++describe DiscourseMcp::Primitive do+ describe ".new" do+ let(:attributes) do+ {+ identifier: "test_tool",+ kind: :tool,+ title: "Test tool",+ description: "A test tool",+ implementation: ->(**) {},+ }+ end++ it "preserves primitive validation errors" do+ expect { described_class.new(**attributes, kind: :invalid) }.to raise_error(+ ArgumentError,+ "invalid MCP primitive kind",+ )+ end++ it "preserves errors raised while parsing schemas" do+ expect do+ described_class.new(**attributes, input_schema: { type: "object", pattern: "[" })+ end.to raise_error(RegexpError)+ end+ end+enddiff --git a/spec/lib/discourse_mcp/staff_tools_spec.rb b/spec/lib/discourse_mcp/staff_tools_spec.rbindex 5a6857d79f5..911ceb96d18 100644--- a/spec/lib/discourse_mcp/staff_tools_spec.rb+++ b/spec/lib/discourse_mcp/staff_tools_spec.rb@@ -889,6 +889,9 @@ describe DiscourseMcp::Tools do"discourse_create_category" => [DiscourseMcp::Scopes::CATEGORIES_WRITE],"discourse_update_category" => [DiscourseMcp::Scopes::CATEGORIES_WRITE],"discourse_delete_category" => [DiscourseMcp::Scopes::CATEGORIES_WRITE],+ "discourse_list_users" => [DiscourseMcp::Scopes::USERS_READ],+ "discourse_create_user" => [DiscourseMcp::Scopes::USERS_WRITE],+ "discourse_manage_user_activation" => [DiscourseMcp::Scopes::USERS_WRITE],}actual =diff --git a/spec/lib/user_approver_spec.rb b/spec/lib/user_approver_spec.rbnew file mode 100644index 00000000000..1ec2efc9ead--- /dev/null+++ b/spec/lib/user_approver_spec.rb@@ -0,0 +1,24 @@+# frozen_string_literal: true++describe UserApprover do+ fab!(:moderator)++ describe ".approve" do+ it "approves a user through the reviewable workflow" do+ SiteSetting.must_approve_users = true+ unapproved_user = Fabricate(:user, approved: false)++ described_class.approve(moderator.guardian, unapproved_user)++ expect(unapproved_user.reload).to be_approved+ expect(ReviewableUser.find_by(target: unapproved_user)).to be_approved+ expect(+ UserHistory.where(+ action: UserHistory.actions[:approve_user],+ acting_user_id: moderator.id,+ target_user_id: unapproved_user.id,+ ),+ ).to exist+ end+ end+enddiff --git a/spec/lib/user_avatar_updater_spec.rb b/spec/lib/user_avatar_updater_spec.rbnew file mode 100644index 00000000000..c4f96d5d457--- /dev/null+++ b/spec/lib/user_avatar_updater_spec.rb@@ -0,0 +1,42 @@+# frozen_string_literal: true++describe UserAvatarUpdater do+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }++ describe ".update" do+ it "updates the selected and custom avatar together" do+ upload = Fabricate(:upload, user:)+ described_class.update(user.guardian, user, upload)+ expect(user.reload.uploaded_avatar_id).to eq(upload.id)+ expect(user.user_avatar.reload.custom_upload_id).to eq(upload.id)+ end++ it "clears the associated account selection when choosing a custom avatar" do+ account = Fabricate(:user_associated_account, user:)+ user.user_avatar.update!(selected_user_associated_account_id: account.id)+ upload = Fabricate(:upload, user:)++ described_class.update(user.guardian, user, upload)++ expect(user.reload.uploaded_avatar_id).to eq(upload.id)+ expect(user.user_avatar.reload.selected_user_associated_account_id).to be_nil+ end++ it "rejects updates to another user's avatar" do+ other_user = Fabricate(:user)+ upload = Fabricate(:upload, user:)+ expect do described_class.update(user.guardian, other_user, upload) end.to raise_error(+ Discourse::InvalidAccess,+ )+ expect(other_user.reload.uploaded_avatar_id).to be_nil+ end++ it "rejects an upload the actor cannot pick" do+ upload = Fabricate(:upload)+ expect do described_class.update(user.guardian, user, upload) end.to raise_error(+ Discourse::InvalidAccess,+ )+ expect(user.reload.uploaded_avatar_id).to be_nil+ end+ end+enddiff --git a/spec/lib/user_creator_spec.rb b/spec/lib/user_creator_spec.rbnew file mode 100644index 00000000000..074c930dec8--- /dev/null+++ b/spec/lib/user_creator_spec.rb@@ -0,0 +1,184 @@+# frozen_string_literal: true++describe UserCreator do+ fab!(:admin)+ fab!(:moderator)++ describe ".create" do+ it "creates an active and approved user and records the staff action" do+ created_user = nil++ expect do+ created_user =+ described_class.create(+ admin.guardian,+ username: "new_cat",+ email: "[email protected]",+ name: "New 猫",+ password: "correct horse battery staple",+ active: true,+ approved: true,+ )+ end.to change(User, :count).by(1).and change {+ UserHistory.where(+ action: UserHistory.actions[:custom_staff],+ custom_type: "create_user",+ acting_user_id: admin.id,+ ).count+ }.by(1)++ expect(created_user).to be_persisted+ expect(created_user).to be_active.and be_approved+ expect(created_user).to be_email_confirmed+ end++ it "preserves requested inactive and unapproved state" do+ created_user =+ described_class.create(+ admin.guardian,+ username: "pending_cat",+ email: "[email protected]",+ name: "Pending Cat",+ password: "correct horse battery staple",+ active: false,+ approved: false,+ )++ expect(created_user).to be_persisted+ expect(created_user).not_to be_active+ expect(created_user).not_to be_approved+ end++ it "assigns an uploaded avatar through the existing avatar permission" do+ upload = Fabricate(:upload, user: admin)++ created_user =+ described_class.create(+ admin.guardian,+ username: "avatar_cat",+ email: "[email protected]",+ name: "Avatar Cat",+ password: "correct horse battery staple",+ upload_id: upload.id,+ )++ expect(created_user.reload.uploaded_avatar_id).to eq(upload.id)+ expect(created_user.user_avatar.custom_upload_id).to eq(upload.id)+ end++ it "does not create the user when authentication controls avatars" do+ SiteSetting.auth_overrides_avatar = true+ upload = Fabricate(:upload, user: admin)++ expect do+ described_class.create(+ admin.guardian,+ username: "managed_avatar_cat",+ email: "[email protected]",+ name: "Managed Avatar Cat",+ password: "correct horse battery staple",+ upload_id: upload.id,+ )+ end.to raise_error(Discourse::InvalidAccess).and not_change(User, :count)+ end++ it "does not create the user when the user cannot upload an avatar" do+ SiteSetting.uploaded_avatars_allowed_groups = Group::AUTO_GROUPS[:admins].to_s+ upload = Fabricate(:upload, user: admin)++ expect do+ described_class.create(+ admin.guardian,+ username: "restricted_cat",+ email: "[email protected]",+ name: "Restricted Avatar Cat",+ password: "correct horse battery staple",+ upload_id: upload.id,+ )+ end.to raise_error(Discourse::InvalidAccess).and not_change(User, :count)+ end++ it "rolls back staged-user fields when avatar authorization fails" do+ SiteSetting.auth_overrides_avatar = true+ field = Fabricate(:user_field)+ staged = Fabricate(:staged)+ staged.custom_fields["#{User::USER_FIELD_PREFIX}#{field.id}"] = "original"+ staged.save_custom_fields+ upload = Fabricate(:upload, user: admin)++ expect do+ described_class.create(+ admin.guardian,+ username: "staged_fields",+ email: staged.email,+ name: "Staged fields",+ password: "correct horse battery staple",+ user_fields: {+ field.id.to_s => "changed",+ },+ upload_id: upload.id,+ )+ end.to raise_error(Discourse::InvalidAccess)++ expect(staged.reload).to be_staged+ expect(staged.user_fields[field.id.to_s]).to eq("original")+ end++ it "requires an administrator even when the caller is staff" do+ expect do+ described_class.create(+ moderator.guardian,+ username: "not_created",+ email: "[email protected]",+ name: "Not Created",+ password: "correct horse battery staple",+ )+ end.to raise_error(Discourse::InvalidAccess)++ expect(User.find_by_username("not_created")).to be_nil+ end++ it "returns validation errors without recording a staff action" do+ existing_user = Fabricate(:user)+ created_user = nil++ expect do+ created_user =+ described_class.create(+ admin.guardian,+ username: existing_user.username,+ email: "[email protected]",+ name: "Duplicate",+ password: "correct horse battery staple",+ )+ end.not_to change {+ UserHistory.where(+ action: UserHistory.actions[:custom_staff],+ custom_type: "create_user",+ acting_user_id: admin.id,+ ).count+ }++ expect(created_user).not_to be_persisted+ expect(created_user.errors).to be_present+ end++ it "does not unstage an existing user when the requested attributes are invalid" do+ existing_user = Fabricate(:user)+ staged_user = Fabricate(:staged, email: "[email protected]")++ created_user =+ described_class.create(+ admin.guardian,+ username: existing_user.username,+ email: staged_user.email,+ name: "Staged Cat",+ password: "correct horse battery staple",+ )++ expect(created_user.errors).to be_present+ expect(staged_user.reload).to be_staged+ expect(staged_user.username).not_to eq(existing_user.username)+ end+ end+enddiff --git a/spec/lib/user_deactivator_spec.rb b/spec/lib/user_deactivator_spec.rbnew file mode 100644index 00000000000..f9b39cd5a23--- /dev/null+++ b/spec/lib/user_deactivator_spec.rb@@ -0,0 +1,29 @@+# frozen_string_literal: true++describe UserDeactivator do+ fab!(:admin)+ fab!(:moderator)+ fab!(:user)++ describe ".deactivate" do+ it "deactivates a regular user and records the staff action" do+ expect do described_class.deactivate(moderator.guardian, user) end.to change {+ UserHistory.where(+ action: UserHistory.actions[:deactivate_user],+ acting_user_id: moderator.id,+ target_user_id: user.id,+ ).count+ }.by(1)++ expect(user.reload).not_to be_active+ end++ it "does not let a moderator deactivate a staff user" do+ expect do described_class.deactivate(moderator.guardian, admin) end.to raise_error(+ Discourse::InvalidAccess,+ )++ expect(admin.reload).to be_active+ end+ end+enddiff --git a/spec/requests/admin/users_controller_spec.rb b/spec/requests/admin/users_controller_spec.rbindex 17169841157..6163da70c09 100644--- a/spec/requests/admin/users_controller_spec.rb+++ b/spec/requests/admin/users_controller_spec.rb@@ -382,6 +382,25 @@ RSpec.describe Admin::UsersController dobefore { SiteSetting.must_approve_users = true }shared_examples "user approval possible" do+ it "approves without a reviewable when signup approval is disabled" do+ SiteSetting.must_approve_users = false+ SiteSetting.invite_only = false+ evil_trout.update!(active: true, approved: false)+ expect(ReviewableUser.find_by(target: evil_trout)).to be_nil++ put "/admin/users/#{evil_trout.id}/approve.json"++ expect(response.status).to eq(200)+ expect(evil_trout.reload).to be_approved+ expect(ReviewableUser.find_by(target: evil_trout)).to be_approved+ expect(+ UserHistory.where(+ action: UserHistory.actions[:approve_user],+ target_user_id: evil_trout.id,+ ).count,+ ).to eq(1)+ end+it "creates a reviewable if one does not exist" doevil_trout.update!(active: true)expect(ReviewableUser.find_by(target: evil_trout)).to be_blankdiff --git a/spec/requests/mcp_controller_spec.rb b/spec/requests/mcp_controller_spec.rbindex d3028c97acf..f49ceb64de3 100644--- a/spec/requests/mcp_controller_spec.rb+++ b/spec/requests/mcp_controller_spec.rb@@ -78,6 +78,25 @@ describe "MCP transport" doMcpPrimitive.create!(kind: "tool", identifier: "discourse_current_user_get", enabled: true)end+ it "returns a structured internal error when a tool unexpectedly fails" do+ failure_message = "private implementation failure"+ primitive = DiscourseMcp.registry.find(:tool, "discourse_current_user_get")+ primitive.implementation.stubs(:call).raises(StandardError, failure_message)++ post "/mcp", params: payload.to_json, headers: headers++ expect(response.status).to eq(500)+ expect(response.parsed_body).to eq(+ "jsonrpc" => "2.0",+ "id" => payload[:id],+ "error" => {+ "code" => -32_603,+ "message" => "Internal error",+ },+ )+ expect(response.body).not_to include(failure_message)+ end+context "when login is required" dobefore { SiteSetting.login_required = true }@@ -217,6 +236,43 @@ describe "MCP transport" doexpect(admin.user_profile.reload.bio_raw).not_to eq("Changed without profile access")end+ it "omits submitted values from prompt validation errors" do+ McpPrimitive.create!(kind: "prompt", identifier: "discourse.draft_reply", enabled: true)+ prompt_headers = classic_headers+ prompt_authorization =+ DiscourseMcp::OAuth::AuthorizationGrant.create!(+ user: admin,+ client:,+ redirect_uri: client.redirect_uris.first,+ requested_scopes: [DiscourseMcp::INITIAL_SCOPE, DiscourseMcp::Scopes::CONTENT_READ],+ )+ prompt_token = McpOauthAccessToken.issue!(authorization: prompt_authorization)+ instructions = "Confidential draft instructions"++ post "/mcp",+ params: {+ jsonrpc: "2.0",+ id: 1,+ method: "prompts/get",+ params: {+ name: "discourse.draft_reply",+ arguments: {+ instructions:,+ },+ },+ }.to_json,+ headers: prompt_headers.merge("HTTP_AUTHORIZATION" => "Bearer #{prompt_token}")++ expect(response.status).to eq(400)+ expect(response.parsed_body.dig("error", "code")).to eq(-32_602)+ expect(response.parsed_body.dig("error", "data", "errors")).to contain_exactly(+ "type" => "required",+ "data_pointer" => "",+ "schema_pointer" => "",+ )+ expect(response.body).not_to include(instructions)+ end+it "negotiates a compatible protocol through the standard initialize request" dopost "/mcp",params: initialize_payload.to_json,diff --git a/spec/requests/mcp_user_administration_spec.rb b/spec/requests/mcp_user_administration_spec.rbnew file mode 100644index 00000000000..2b242308105--- /dev/null+++ b/spec/requests/mcp_user_administration_spec.rb@@ -0,0 +1,659 @@+# frozen_string_literal: true++describe "MCP user administration tools" do+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:moderator)+ fab!(:admin)+ fab!(:scope_group, :group)++ before { SiteSetting.mcp_server_enabled = true }++ it "rejects deactivation that would delete a pending account" do+ SiteSetting.must_approve_users = true+ pending_user = Fabricate(:user, active: true, approved: false)+ Jobs::CreateUserReviewable.new.execute(user_id: pending_user.id)+ authorize("mcp:users:write")++ call_tool(+ "discourse_manage_user_activation",+ { username: pending_user.username, action: "deactivate", confirm: true },+ )++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(pending_user.reload).to be_active+ expect(ReviewableUser.find_by(target: pending_user)).to be_pending+ end++ it "honors registration restrictions before creating an account" do+ authorize("mcp:users:write")+ arguments = {+ username: "restricted_signup",+ email: "[email protected]",+ name: "Restricted",+ password: "correct horse battery staple",+ }+ SiteSetting.allow_new_registrations = false+ call_tool("discourse_create_user", arguments)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(User.find_by_username(arguments[:username])).to be_nil++ SiteSetting.allow_new_registrations = true+ SiteSetting.invite_code = "invite-only"+ call_tool("discourse_create_user", arguments)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(User.find_by_username(arguments[:username])).to be_nil++ SiteSetting.invite_code = ""+ Fabricate(:user_field, requirement: :on_signup)+ call_tool("discourse_create_user", arguments)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(User.find_by_username(arguments[:username])).to be_nil+ end++ it "creates accounts with required user fields, including fields hidden from signup" do+ signup_field = Fabricate(:user_field)+ hidden_field = Fabricate(:user_field, requirement: :for_all_users, show_on_signup: false)+ authorize("mcp:users:write")++ call_tool(+ "discourse_create_user",+ {+ username: "required_fields",+ email: "[email protected]",+ name: "Required 猫",+ password: "correct horse battery staple",+ user_fields: {+ signup_field.id.to_s => "Member 猫",+ hidden_field.id.to_s => "12345",+ },+ },+ )++ expect(response.status).to eq(200)+ expect(structured_content["created"]).to eq(true)+ expect(User.find_by_username("required_fields").user_fields).to include(+ signup_field.id.to_s => "Member 猫",+ hidden_field.id.to_s => "12345",+ )+ end++ it "identifies missing required user fields without unstaging the account" do+ field = Fabricate(:user_field, name: "Membership 猫")+ staged = Fabricate(:staged)+ authorize("mcp:users:write")++ call_tool(+ "discourse_create_user",+ {+ username: "missing_fields",+ email: staged.email,+ name: "Missing fields",+ password: "correct horse battery staple",+ },+ )++ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(response.parsed_body.dig("result", "content", 0, "text")).to include(+ field.name,+ field.id.to_s,+ )+ expect(staged.reload).to be_staged+ expect(User.find_by_username("missing_fields")).to be_nil+ end++ it "cleans field options and preserves unrelated fields when converting a staged user" do+ dropdown = Fabricate(:user_field_dropdown, requirement: :optional)+ multiselect = Fabricate(:user_field, field_type: :multiselect)+ option = Fabricate(:user_field_option, user_field: multiselect, value: "猫")+ staged = Fabricate(:staged)+ staged.custom_fields["unrelated_field"] = "preserved"+ staged.save_custom_fields+ authorize("mcp:users:write")++ call_tool(+ "discourse_create_user",+ {+ username: "converted_fields",+ email: staged.email,+ name: "Converted fields",+ password: "correct horse battery staple",+ user_fields: {+ dropdown.id.to_s => "invalid option",+ multiselect.id.to_s => [option.value, "invalid option"],+ },+ },+ )++ expect(response.status).to eq(200)+ expect(structured_content).to include("created" => true, "user_id" => staged.id)+ expect(staged.reload).not_to be_staged+ expect(staged.user_fields[multiselect.id.to_s]).to eq(option.value)+ expect(staged.user_fields[dropdown.id.to_s]).to be_blank+ expect(staged.custom_fields["unrelated_field"]).to eq("preserved")+ end++ it "rejects invalid required dropdown values without creating an account" do+ field = Fabricate(:user_field_dropdown)+ authorize("mcp:users:write")++ expect do+ call_tool(+ "discourse_create_user",+ {+ username: "invalid_fields",+ email: "[email protected]",+ name: "Invalid fields",+ password: "correct horse battery staple",+ user_fields: {+ field.id.to_s => "invalid option",+ },+ },+ )+ end.not_to change(User, :count)++ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(response.parsed_body.dig("result", "content", 0, "text")).to include(+ field.name,+ field.id.to_s,+ )+ end++ it "enforces watched words in submitted public user fields" do+ field = Fabricate(:user_field, show_on_profile: true)+ word = Fabricate(:watched_word, word: "blockedphrase")+ authorize("mcp:users:write")++ expect do+ call_tool(+ "discourse_create_user",+ {+ username: "blocked_fields",+ email: "[email protected]",+ name: "Blocked fields",+ password: "correct horse battery staple",+ user_fields: {+ field.id.to_s => word.word,+ },+ },+ )+ end.not_to change(User, :count)++ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ end++ it "accepts the site's invite code without bypassing closed registrations" do+ SiteSetting.invite_code = "Invite-Cats"+ authorize("mcp:users:write")+ arguments = {+ username: "invited_fields",+ email: "[email protected]",+ name: "Invited fields",+ password: "correct horse battery staple",+ invite_code: " invite-cats ",+ }++ call_tool("discourse_create_user", arguments.merge(invite_code: "wrong"))+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(User.find_by_username(arguments[:username])).to be_nil++ SiteSetting.allow_new_registrations = false+ call_tool("discourse_create_user", arguments)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(User.find_by_username(arguments[:username])).to be_nil++ SiteSetting.allow_new_registrations = true+ call_tool("discourse_create_user", arguments)+ expect(response.status).to eq(200)+ expect(structured_content["created"]).to eq(true)+ end++ it "preserves explicit unapproved state despite domain auto approval" do+ SiteSetting.must_approve_users = true+ SiteSetting.auto_approve_email_domains = "example.com"+ authorize("mcp:users:write")+ call_tool(+ "discourse_create_user",+ {+ username: "unapproved_cat",+ email: "[email protected]",+ name: "Cat",+ password: "correct horse battery staple",+ active: false,+ approved: false,+ },+ )+ expect(response.status).to eq(200)+ created_user = User.find_by_username("unapproved_cat")+ expect(created_user).not_to be_approved+ expect(created_user.approved_by_id).to be_nil+ expect(created_user.approved_at).to be_nil+ end++ def authorize(*extra_scopes, auth_user: admin)+ 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: "User administration 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 = {})+ McpPrimitive.find_or_create_by!(kind: "tool", identifier: name) do |primitive|+ primitive.enabled = true+ end+ 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 structured_content+ response.parsed_body.dig("result", "structuredContent")+ end++ it "requires dedicated read and write scopes" do+ authorize++ {+ "discourse_list_users" => [{}, "mcp:users:read"],+ "discourse_create_user" => [+ {+ username: "not_created",+ email: "[email protected]",+ name: "Not Created",+ password: "correct horse battery staple",+ },+ "mcp:users:write",+ ],+ "discourse_manage_user_activation" => [+ { username: user.username, action: "deactivate", confirm: true },+ "mcp:users:write",+ ],+ }.each do |name, (arguments, scope)|+ call_tool(name, arguments)++ aggregate_failures(name) do+ expect(response.status).to eq(403)+ expect(response.headers["WWW-Authenticate"]).to include(+ 'error="insufficient_scope"',+ %(scope="#{scope}"),+ )+ end+ end++ expect(User.find_by_username("not_created")).to be_nil+ expect(user.reload).to be_active+ end++ it "does not let a regular user administer users when the token has both scopes" do+ authorize("mcp:users:read", "mcp:users:write", auth_user: user)++ call_tool("discourse_list_users")+ expect(response.status).to eq(403)++ call_tool(+ "discourse_create_user",+ {+ username: "not_created",+ email: "[email protected]",+ name: "Not Created",+ password: "correct horse battery staple",+ },+ )+ expect(response.status).to eq(403)++ call_tool(+ "discourse_manage_user_activation",+ { username: admin.username, action: "deactivate", confirm: true },+ )+ expect(response.status).to eq(403)+ expect(admin.reload).to be_active+ end++ it "denies each activation operation when a scoped user lacks authority" do+ SiteSetting.must_approve_users = true+ inactive_user = Fabricate(:inactive_user, approved: false)+ pending_user = Fabricate(:user, approved: false)+ authorize("mcp:users:write", auth_user: user)++ {+ "activate" => inactive_user,+ "activate_and_approve" => inactive_user,+ "approve" => pending_user,+ "deactivate" => admin,+ }.each do |action, target|+ call_tool(+ "discourse_manage_user_activation",+ { username: target.username, action: action, confirm: true },+ )+ expect(response.status).to eq(403)+ end++ expect(inactive_user.reload).not_to be_active+ expect(pending_user.reload).not_to be_approved+ expect(admin.reload).to be_active+ end++ it "lists filtered users with bounded pagination and optional email access" do+ matching_user = Fabricate(:user, username: "searchable_cat", email: "[email protected]")+ Fabricate(:user, username: "unrelated_dog")+ authorize("mcp:users:read")++ expect do+ call_tool(+ "discourse_list_users",+ { filter: "searchable_cat", include_emails: true, limit: 1 },+ )+ end.to change {+ UserHistory.where(action: UserHistory.actions[:check_email], acting_user_id: admin.id).count+ }.by(1)++ expect(response.status).to eq(200)+ expect(structured_content["users"]).to contain_exactly(+ include(+ "id" => matching_user.id,+ "username" => matching_user.username,+ "email" => matching_user.email,+ ),+ )+ expect(structured_content["meta"]).to include("page" => 0, "limit" => 1, "has_more" => false)+ end++ it "lets staff list users without exposing or logging emails they cannot inspect" do+ SiteSetting.moderators_view_emails = false+ target_user = Fabricate(:user, username: "private_email_cat", email: "[email protected]")+ authorize("mcp:users:read", auth_user: moderator)++ expect do+ call_tool("discourse_list_users", { filter: target_user.username, include_emails: true })+ end.not_to change {+ UserHistory.where(+ action: UserHistory.actions[:check_email],+ acting_user_id: moderator.id,+ ).count+ }++ expect(response.status).to eq(200)+ expect(structured_content["users"].first).to include(+ "username" => target_user.username,+ "email" => nil,+ )+ end++ it "creates a user as an administrator without returning the password" do+ authorize("mcp:users:write")++ call_tool(+ "discourse_create_user",+ {+ username: "created_cat",+ email: "[email protected]",+ name: "Created 猫",+ password: "correct horse battery staple",+ },+ )++ expect(response.status).to eq(200)+ created_user = User.find_by_username("created_cat")+ expect(created_user).to be_active.and be_approved+ expect(structured_content).to include(+ "created" => true,+ "user_id" => created_user.id,+ "username" => created_user.username,+ "active" => true,+ "approved" => true,+ )+ expect(response.body).not_to include("correct horse battery staple")+ end++ it "does not report a failed staged-user conversion as a successful creation" do+ existing_user = Fabricate(:user)+ staged_user = Fabricate(:staged, email: "[email protected]")+ authorize("mcp:users:write")++ call_tool(+ "discourse_create_user",+ {+ username: existing_user.username,+ email: staged_user.email,+ name: "Staged Request",+ password: "correct horse battery staple",+ },+ )++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ expect(response.body).not_to include("correct horse battery staple")+ expect(staged_user.reload).to be_staged+ end++ it "rejects whitespace-only passwords without creating or unstaging users" do+ staged_user = Fabricate(:staged, email: "[email protected]")+ authorize("mcp:users:write")++ ["[email protected]", staged_user.email].each do |email|+ expect do+ call_tool(+ "discourse_create_user",+ { username: "blank_password", email: email, name: "Blank Password", password: " " * 20 },+ )+ end.not_to change(User, :count)++ expect(response.status).to eq(200)+ expect(response.parsed_body.dig("result", "isError")).to eq(true)+ end++ expect(staged_user.reload).to be_staged+ expect(User.find_by_username("blank_password")).to be_nil+ end++ it "preserves surrounding whitespace in a nonblank password" do+ authorize("mcp:users:write")+ password = " correct horse battery staple "++ call_tool(+ "discourse_create_user",+ {+ username: "spaced_password",+ email: "[email protected]",+ name: "Spaced",+ password: password,+ },+ )++ expect(response.status).to eq(200)+ expect(structured_content["created"]).to eq(true)+ created_user = User.find_by_username("spaced_password")+ expect(created_user.confirm_password?(password)).to eq(true)+ expect(created_user.confirm_password?(password.strip)).to eq(false)+ end++ it "approves an explicitly unapproved account when signup approval is disabled" do+ SiteSetting.must_approve_users = false+ SiteSetting.invite_only = false+ authorize("mcp:users:write")+ call_tool(+ "discourse_create_user",+ {+ username: "manual_approval",+ email: "[email protected]",+ name: "Manual Approval",+ password: "correct horse battery staple",+ approved: false,+ },+ )+ created_user = User.find_by_username("manual_approval")+ expect(created_user).to be_active+ expect(created_user).not_to be_approved+ expect(ReviewableUser.find_by(target: created_user)).to be_nil++ call_tool(+ "discourse_manage_user_activation",+ { username: created_user.username, action: "approve", confirm: true },+ )++ expect(response.status).to eq(200)+ expect(structured_content["approved"]).to eq(true)+ expect(created_user.reload).to be_approved+ expect(ReviewableUser.find_by(target: created_user)).to be_approved+ expect(+ UserHistory.where(+ action: UserHistory.actions[:approve_user],+ target_user_id: created_user.id,+ ).count,+ ).to eq(1)+ end++ it "requires both scope and staff authority for approval without a reviewable" do+ SiteSetting.must_approve_users = false+ SiteSetting.invite_only = false+ pending_user = Fabricate(:user, active: true, approved: false)++ [[admin, []], [user, ["mcp:users:write"]]].each do |actor, scopes|+ authorize(*scopes, auth_user: actor)++ call_tool(+ "discourse_manage_user_activation",+ { username: pending_user.username, action: "approve", confirm: true },+ )++ expect(response.status).to eq(403)+ expect(pending_user.reload).not_to be_approved+ expect(ReviewableUser.find_by(target: pending_user)).to be_nil+ expect(+ UserHistory.where(+ action: UserHistory.actions[:approve_user],+ target_user_id: pending_user.id,+ ),+ ).not_to exist+ end+ end++ it "omits submitted values from user creation schema errors" do+ authorize("mcp:users:write")+ arguments = {+ username: "invalid_signup",+ email: "[email protected]",+ name: "Invalid Signup",+ password: "correct horse battery staple",+ }++ [arguments.except(:name), arguments.merge(password: "secret" * 40)].each do |invalid_arguments|+ call_tool("discourse_create_user", invalid_arguments)++ expect(response.status).to eq(400)+ expect(response.parsed_body.dig("error", "code")).to eq(-32_602)+ errors = response.parsed_body.dig("error", "data", "errors")+ expect(errors).to be_present+ errors.each do |error|+ expect(error.keys).to contain_exactly("type", "data_pointer", "schema_pointer")+ end+ expect(response.body).not_to include(invalid_arguments[:password])+ end++ expect(User.find_by_username(arguments[:username])).to be_nil+ end++ it "converts an existing staged user with a mixed-case email" do+ staged_user = Fabricate(:staged, email: "[email protected]")+ authorize("mcp:users:write")++ expect do+ call_tool(+ "discourse_create_user",+ {+ username: "converted_cat",+ email: "[email protected]",+ name: "Converted Cat",+ password: "correct horse battery staple",+ },+ )+ end.not_to change(User, :count)++ expect(response.status).to eq(200)+ expect(structured_content).to include("created" => true, "user_id" => staged_user.id)+ expect(staged_user.reload).not_to be_staged+ expect(staged_user).to be_active.and be_approved+ expect(staged_user.email).to eq("[email protected]")+ end++ it "does not let a moderator create users when the token has write scope" do+ authorize("mcp:users:write", auth_user: moderator)++ call_tool(+ "discourse_create_user",+ {+ username: "not_created",+ email: "[email protected]",+ name: "Not Created",+ password: "correct horse battery staple",+ },+ )++ expect(response.status).to eq(403)+ expect(User.find_by_username("not_created")).to be_nil+ end++ it "lets staff activate and approve an eligible user" do+ SiteSetting.must_approve_users = true+ inactive_user = Fabricate(:inactive_user, approved: false)+ authorize("mcp:users:write", auth_user: moderator)++ call_tool(+ "discourse_manage_user_activation",+ { username: inactive_user.username, action: "activate_and_approve", confirm: true },+ )++ expect(response.status).to eq(200)+ expect(inactive_user.reload).to be_active.and be_approved+ expect(structured_content).to include(+ "username" => inactive_user.username,+ "requested_action" => "activate_and_approve",+ "completed_actions" => %w[activate approve],+ "active" => true,+ "approved" => true,+ )+ end++ it "requires confirmation and preserves the target when access is denied" do+ authorize("mcp:users:write", auth_user: moderator)++ call_tool("discourse_manage_user_activation", { username: user.username, action: "deactivate" })+ expect(response.status).to eq(400)+ expect(user.reload).to be_active++ call_tool(+ "discourse_manage_user_activation",+ { username: admin.username, action: "deactivate", confirm: true },+ )+ expect(response.status).to eq(403)+ expect(admin.reload).to be_active+ end+enddiff --git a/spec/services/user_activator_spec.rb b/spec/services/user_activator_spec.rbindex 56c5890579f..ba17cd9e19d 100644--- a/spec/services/user_activator_spec.rb+++ b/spec/services/user_activator_spec.rb@@ -1,9 +1,29 @@# frozen_string_literal: true-RSpec.describe UserActivator do+describe UserActivator dofab!(:user)let!(:email_token) { Fabricate(:email_token, user: user) }+ describe ".activate" do+ fab!(:moderator)++ it "activates a user and records the staff action" do+ inactive_user = Fabricate(:inactive_user)+ inactive_user.email_tokens.update_all(confirmed: false, expired: true)++ expect do described_class.activate(moderator.guardian, inactive_user) end.to change {+ UserHistory.where(+ action: UserHistory.actions[:activate_user],+ acting_user_id: moderator.id,+ target_user_id: inactive_user.id,+ ).count+ }.by(1)++ expect(inactive_user.reload).to be_active+ expect(inactive_user).to be_email_confirmed+ end+ end+describe "email_activator" dolet(:activator) { EmailActivator.new(user, nil, nil, nil) }