A platform for community discussion. Free, open, simple.
FEATURE: Add regular user tools to the MCP server (#43515)
Natalie Tayf42adc580a89
diff --git a/app/controllers/topics_controller.rb b/app/controllers/topics_controller.rbindex 112b6edb5c0..94a0fbc468d 100644--- a/app/controllers/topics_controller.rb+++ b/app/controllers/topics_controller.rb@@ -430,58 +430,21 @@ class TopicsController < ApplicationControllerendif params.key?(:category_id) && (params[:category_id].to_i != topic.category_id.to_i)+ category_validation =+ TopicCategoryChangeValidator.call(+ topic:,+ category_id: params[:category_id],+ guardian:,+ tag_names: resolve_tag_names(topic),+ tags_changed: params.has_key?(:tags),+ )+ if !category_validation.success?+ return render_json_error(category_validation.error, status: category_validation.status)+ end+if topic.shared_drafttopic.shared_draft.update(category_id: params[:category_id])params.delete(:category_id)- else- category = Category.find_by(id: params[:category_id])-- if category || (params[:category_id].to_i == 0)- begin- guardian.ensure_can_move_topic_to_category!(category)- rescue Discourse::InvalidAccess- return(- render_json_error I18n.t("category.errors.move_topic_to_category_disallowed"),- status: :forbidden- )- end- else- return render_json_error(I18n.t("category.errors.not_found"))- end-- if category- topic_tag_names = resolve_tag_names(topic)-- if topic_tag_names.present?- allowed_tags =- DiscourseTagging.filter_allowed_tags(guardian, category: category).map(&:name)-- invalid_tags = topic_tag_names - allowed_tags-- # Do not raise an error on a topic's hidden tags when not modifying tags- if !params.has_key?(:tags)- invalid_tags.each do |tag_name|- if DiscourseTagging.hidden_tag_names.include?(tag_name)- invalid_tags.delete(tag_name)- end- end- end-- invalid_tags = Tag.where_name(invalid_tags).pluck(:name)-- if !invalid_tags.empty?- if (invalid_tags & DiscourseTagging.hidden_tag_names).present?- return render_json_error(I18n.t("category.errors.disallowed_tags_generic"))- else- return(- render_json_error(- I18n.t("category.errors.disallowed_topic_tags", tags: invalid_tags.join(", ")),- )- )- end- end- end- endendend@@ -532,7 +495,13 @@ class TopicsController < ApplicationController# this is used to return the title to the client as it may have been changed by "TextCleaner"if !success- render_json_error(topic)+ error =+ TopicCategoryChangeValidator.safe_revision_errors(+ topic:,+ guardian:,+ category_changed: changes.has_key?(:category_id),+ )+ render_json_error(error)elsif tags_submittedrender_topic_with_tags(topic)elsediff --git a/app/services/topic_category_change_validator.rb b/app/services/topic_category_change_validator.rbnew file mode 100644index 00000000000..dd197725cc4--- /dev/null+++ b/app/services/topic_category_change_validator.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++class TopicCategoryChangeValidator+ Result =+ Data.define(:category, :error, :status) do+ def success?+ error.nil?+ end+ end++ def self.call(topic:, category_id:, guardian:, tag_names:, tags_changed:)+ category = category_id.to_i.zero? ? nil : Category.find_by(id: category_id)++ if topic.shared_draft+ return failure(I18n.t("category.errors.not_found")) if category.blank?++ guardian.ensure_can_publish_topic!(topic, category)+ return success(category)+ end++ return failure(I18n.t("category.errors.not_found")) if category_id.to_i != 0 && category.blank?++ begin+ guardian.ensure_can_move_topic_to_category!(category)+ rescue Discourse::InvalidAccess+ return failure(I18n.t("category.errors.move_topic_to_category_disallowed"), :forbidden)+ end++ return success(category) if category.blank? || tag_names.blank?++ allowed_tag_names = DiscourseTagging.filter_allowed_tags(guardian, category:).map(&:name)+ invalid_tag_names = tag_names - allowed_tag_names+ hidden_tag_names = DiscourseTagging.hidden_tag_names(guardian)+ invalid_tag_names -= hidden_tag_names if !tags_changed+ invalid_tag_names = Tag.where_name(invalid_tag_names).pluck(:name)+ return success(category) if invalid_tag_names.empty?++ error =+ if (invalid_tag_names & hidden_tag_names).present?+ I18n.t("category.errors.disallowed_tags_generic")+ else+ I18n.t("category.errors.disallowed_topic_tags", tags: invalid_tag_names.join(", "))+ end+ failure(error)+ end++ def self.safe_revision_errors(topic:, guardian:, category_changed:)+ if category_changed+ visible_tag_ids = DiscourseTagging.visible_tag_ids(topic.tags, guardian)+ if topic.tags.any? { |tag| visible_tag_ids.exclude?(tag.id) }+ return [I18n.t("category.errors.disallowed_tags_generic")]+ end+ end++ topic.errors.full_messages+ end++ def self.success(category)+ Result.new(category:, error: nil, status: nil)+ end+ private_class_method :success++ def self.failure(error, status = :unprocessable_entity)+ Result.new(category: nil, error:, status:)+ end+ private_class_method :failure+enddiff --git a/config/locales/server.en.yml b/config/locales/server.en.ymlindex 9657b638399..73a5be8b8f0 100644--- a/config/locales/server.en.yml+++ b/config/locales/server.en.yml@@ -1,5 +1,36 @@en:mcp:+ errors:+ draft_sequence_conflict: "Draft sequence conflict"+ draft_too_long: "Draft is too long"+ group_not_found: "Group not found"+ invalid_date: "Invalid date"+ invalid_directory_period: "Invalid directory period"+ invalid_reply_mode: "Invalid reply mode"+ post_not_found: "Post not found"+ user_directory_disabled: "The user directory is disabled"+ filter_only_for_filtered_view: "Filter is only supported by the filtered view"+ filter_required: "A nonblank filter is required for the filtered view"+ invalid_post_selection: "The post selection options are invalid"+ invalid_search_query: "The search query is invalid"+ group_mailbox_sent: "Group private-message mailboxes do not support sent messages"+ invalid_upload_data: "The upload data is not valid base64"+ invalid_upload_source: "Provide either base64 data with a filename or one remote URL"+ invalid_upload_type: "The upload type is not supported"+ invalid_upload_url: "The upload URL must use HTTP or HTTPS"+ private_message_email_message: "A custom message is only valid with an email recipient"+ private_message_group_notification: "Group notifications are only valid with a group recipient"+ private_message_invite_failed: "The participant could not be added to the personal message"+ private_message_not_found: "Personal message not found"+ private_message_recipient_required: "At least one private-message recipient is required"+ private_message_single_recipient: "Provide exactly one user, group, or email recipient"+ topic_not_found: "Topic not found"+ topic_update_required: "Provide at least one topic field to update"+ 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_not_found: "User not found"oauth:authorize_title: "Authorize MCP client"client_request: "%{client_name} is requesting access to %{site_name}."diff --git a/lib/discourse_mcp/core_primitives.rb b/lib/discourse_mcp/core_primitives.rbindex 0af07b1dc31..5cc0a6b4ef4 100644--- a/lib/discourse_mcp/core_primitives.rb+++ b/lib/discourse_mcp/core_primitives.rb@@ -14,6 +14,12 @@ module DiscourseMcpidempotentHint: false,openWorldHint: false,}.freeze+ EXTERNAL_SIDE_EFFECT = {+ readOnlyHint: false,+ destructiveHint: false,+ idempotentHint: false,+ openWorldHint: true,+ }.freezeDESTRUCTIVE = {readOnlyHint: false,destructiveHint: true,@@ -59,10 +65,79 @@ module DiscourseMcpminLength: 1,maxLength: 500,},- limit: {+ max_results: {+ type: "integer",+ minimum: 1,+ maximum: 50,+ default: 10,+ },+ },+ required: %w[query],+ ),+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_filter_topics",+ title: "Filter topics",+ description:+ "Discover topics through a filtered, top, or hot view. Filtered uses Discourse " \+ "TopicsFilter syntax; top uses Discourse's top score and defaults to weekly; hot " \+ "is daily top. Returns a uniform topic projection and truthful pagination metadata.",+ implementation: Tools::FilterTopics,+ input_schema:+ object_schema(+ {+ filter: {+ type: "string",+ maxLength: 1_000,+ },+ view: {+ type: "string",+ enum: %w[filtered top hot],+ default: "filtered",+ },+ top_period: {+ type: "string",+ enum: Tools::FilterTopics::TOP_PERIODS,+ },+ page: {+ type: "integer",+ minimum: 0,+ default: 0,+ },+ per_page: {type: "integer",minimum: 1,maximum: 50,+ default: 20,+ },+ },+ ),+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_search_posts",+ title: "Search posts",+ description:+ "Search post-level evidence with Discourse query syntax. Preserves matched posts, " \+ "highlighted excerpts, authors, topics, categories, and bounded continuation. This " \+ "is keyword search, not semantic search.",+ implementation: Tools::SearchPosts,+ input_schema:+ object_schema(+ {+ query: {+ type: "string",+ minLength: 1,+ maxLength: 500,+ },+ page: {+ type: "integer",+ minimum: 1,+ maximum: 10,+ default: 1,},},required: %w[query],@@ -71,8 +146,201 @@ module DiscourseMcpannotations: READ_ONLY,)registry.register_tool(- "discourse_topic_get",- title: "Get topic",+ "discourse_read_topic_posts",+ title: "Read selected topic posts",+ description:+ "Read exact, earliest, latest, around-post, or username-filtered topic evidence. " \+ "Selection is bounded to 50 posts and reports the visible stream size without " \+ "claiming the entire topic was loaded.",+ implementation: Tools::ReadTopicPosts,+ input_schema:+ object_schema(+ {+ topic_id: {+ type: "integer",+ minimum: 1,+ },+ selection_mode: {+ type: "string",+ enum: %w[latest earliest post_ids around_post usernames],+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: 50,+ },+ post_ids: {+ type: "array",+ items: {+ type: "integer",+ minimum: 1,+ },+ minItems: 1,+ maxItems: 50,+ },+ post_number: {+ type: "integer",+ minimum: 1,+ },+ usernames: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ minItems: 1,+ maxItems: 50,+ },+ replies_only: {+ type: "boolean",+ },+ },+ required: %w[topic_id selection_mode],+ ),+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_get_post_replies",+ title: "Get post replies",+ description:+ "Read reply relationships for a post as recursive descendant IDs, bounded rich " \+ "direct replies, or the upstream-bounded ancestor history. Preserves upstream " \+ "ordering and references.",+ implementation: Tools::GetPostReplies,+ input_schema:+ object_schema(+ {+ post_id: {+ type: "integer",+ minimum: 1,+ },+ mode: {+ type: "string",+ enum: %w[reply_ids direct_replies reply_history],+ default: "reply_ids",+ },+ after_post_number: {+ type: "integer",+ minimum: 0,+ },+ },+ required: %w[post_id],+ ),+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_list_latest_posts",+ title: "List latest posts",+ description:+ "List the site's latest visible posts using Discourse's fixed 50-post page and " \+ "post-ID cursor. Results are a feed, not an exhaustive history.",+ implementation: Tools::ListLatestPosts,+ input_schema:+ object_schema(+ { before_post_id: { type: "integer", minimum: 1 }, replies_only: { type: "boolean" } },+ ),+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_get_topic_view_stats",+ title: "Get topic view stats",+ description:+ "Get up to 300 ascending daily topic view counts. Views combine anonymous and " \+ "logged-in views; they are not unique viewers or an engagement judgment.",+ implementation: Tools::GetTopicViewStats,+ input_schema:+ object_schema(+ {+ topic_id: {+ type: "integer",+ minimum: 1,+ },+ from: {+ type: "string",+ pattern: "\\A[0-9]{4}-[0-9]{2}-[0-9]{2}\\z",+ },+ to: {+ type: "string",+ pattern: "\\A[0-9]{4}-[0-9]{2}-[0-9]{2}\\z",+ },+ },+ required: %w[topic_id],+ ),+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_list_directory_items",+ title: "List directory items",+ description:+ "List user-directory metrics with authoritative totals and continuation. Supports " \+ "Discourse periods, ordering, visible groups, page 0-10, and up to 50 rows.",+ implementation: Tools::ListDirectoryItems,+ input_schema:+ object_schema(+ {+ period: {+ type: "string",+ enum: %w[daily weekly monthly quarterly yearly all],+ },+ order: {+ type: "string",+ pattern: "\\A[a-z0-9_]+\\z",+ },+ ascending: {+ type: "boolean",+ },+ group: {+ type: "string",+ minLength: 1,+ },+ page: {+ type: "integer",+ minimum: 0,+ maximum: Tools::ListDirectoryItems::PAGE_LIMIT,+ default: 0,+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: Tools::ListDirectoryItems::PAGE_SIZE,+ default: Tools::ListDirectoryItems::PAGE_SIZE,+ },+ name: {+ type: "string",+ },+ username: {+ type: "string",+ },+ exclude_groups: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ maxItems: 50,+ },+ exclude_usernames: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ },+ maxItems: 100,+ },+ },+ required: %w[period],+ ),+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_read_topic",+ title: "Read topic",description: "Reads a topic and a bounded set of posts visible to the authenticated user.",implementation: Tools::GetTopic,input_schema:@@ -85,7 +353,12 @@ module DiscourseMcppost_limit: {type: "integer",minimum: 1,- maximum: 100,+ maximum: 50,+ default: 5,+ },+ start_post_number: {+ type: "integer",+ minimum: 1,},},required: %w[topic_id],@@ -94,8 +367,8 @@ module DiscourseMcpannotations: READ_ONLY,)registry.register_tool(- "discourse_post_get",- title: "Get post",+ "discourse_read_post",+ title: "Read post",description: "Reads one visible post.",implementation: Tools::GetPost,input_schema:@@ -130,7 +403,7 @@ module DiscourseMcpannotations: READ_ONLY,)registry.register_tool(- "discourse_user_get",+ "discourse_get_user",title: "Get user",description: "Reads a user profile visible to the authenticated user.",implementation: Tools::GetUser,@@ -143,112 +416,586 @@ module DiscourseMcpannotations: READ_ONLY,)registry.register_tool(- "discourse_bookmark_list",- title: "List bookmarks",- description: "Lists the authenticated user's bookmarks.",- implementation: Tools::ListBookmarks,- input_schema: object_schema({ limit: { type: "integer", minimum: 1, maximum: 100 } }),+ "discourse_list_user_posts",+ title: "List user posts",+ description: "Lists a user's visible topics and replies with zero-based pagination.",+ implementation: Tools::ListUserPosts,+ input_schema:+ object_schema(+ {+ username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ page: {+ type: "integer",+ minimum: 0,+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: 50,+ },+ },+ required: %w[username],+ ),required_scopes: %w[mcp:content:read],annotations: READ_ONLY,)registry.register_tool(- "discourse_notification_list",- title: "List notifications",- description: "Lists the authenticated user's notifications.",- implementation: Tools::ListNotifications,- input_schema: object_schema({ limit: { type: "integer", minimum: 1, maximum: 100 } }),+ "discourse_get_user_summary",+ title: "Get user summary",+ description: "Returns profile-visible aggregate activity for a user.",+ implementation: Tools::GetUserSummary,+ input_schema:+ object_schema(+ { username: { type: "string", minLength: 1, maxLength: 60 } },+ required: %w[username],+ ),required_scopes: %w[mcp:content:read],annotations: READ_ONLY,)- end-- def register_write_tools(registry)registry.register_tool(- "discourse_topic_create",- title: "Create topic",- description: "Creates a topic as the authenticated user.",- implementation: Tools::CreateTopic,+ "discourse_list_user_actions",+ title: "List user actions",+ description: "Lists a user's visible activity using named action types.",+ implementation: Tools::ListUserActions,input_schema:object_schema({- title: {+ username: {type: "string",minLength: 1,+ maxLength: 60,},- raw: {+ acting_username: {type: "string",minLength: 1,+ maxLength: 60,},- category_id: {- type: "integer",- },- tags: {+ action_types: {type: "array",items: {type: "string",+ enum: Tools::ListUserActions::ACTION_TYPES.keys,},- maxItems: 10,+ minItems: 1,+ uniqueItems: true,},- },- required: %w[title raw],- ),- required_scopes: %w[mcp:content:write],- annotations: WRITE,- risk: :write,- )- registry.register_tool(- "discourse_topic_reply",- title: "Reply to topic",- description: "Replies to a topic as the authenticated user.",- implementation: Tools::ReplyTopic,- input_schema:- object_schema(- {- topic_id: {+ offset: {type: "integer",- minimum: 1,- },- raw: {- type: "string",- minLength: 1,+ minimum: 0,},- reply_to_post_number: {+ limit: {type: "integer",minimum: 1,+ maximum: 100,},},- required: %w[topic_id raw],+ required: %w[username],),- required_scopes: %w[mcp:content:write],- annotations: WRITE,- risk: :write,+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,)registry.register_tool(- "discourse_post_edit",- title: "Edit post",- description: "Edits a post when the authenticated user has permission.",- implementation: Tools::EditPost,+ "discourse_get_draft",+ title: "Get draft",+ description: "Retrieves one of the authenticated user's drafts by key.",+ implementation: Tools::GetDraft,input_schema:object_schema({- post_id: {- type: "integer",- minimum: 1,- },- raw: {+ draft_key: {type: "string",minLength: 1,+ maxLength: 40,},- edit_reason: {- type: "string",- maxLength: 200,+ sequence: {+ type: "integer",+ minimum: 0,},},- required: %w[post_id raw],+ required: %w[draft_key],),- required_scopes: %w[mcp:content:write],- annotations: WRITE,- risk: :write,+ required_scopes: %w[mcp:drafts:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_bookmark_list",+ title: "List bookmarks",+ description: "Lists the authenticated user's bookmarks.",+ implementation: Tools::ListBookmarks,+ input_schema: object_schema({ limit: { type: "integer", minimum: 1, maximum: 100 } }),+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_notification_list",+ title: "List notifications",+ description: "Lists the authenticated user's notifications.",+ implementation: Tools::ListNotifications,+ input_schema: object_schema({ limit: { type: "integer", minimum: 1, maximum: 100 } }),+ required_scopes: %w[mcp:content:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_list_private_messages",+ title: "List private messages",+ description: "Lists a personal or group private-message mailbox visible to the user.",+ implementation: Tools::ListPrivateMessages,+ input_schema:+ object_schema(+ {+ username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ mailbox: {+ type: "string",+ enum: Tools::ListPrivateMessages::MAILBOXES,+ default: "inbox",+ },+ group_name: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ page: {+ type: "integer",+ minimum: 0,+ default: 0,+ },+ per_page: {+ type: "integer",+ minimum: 1,+ maximum: 100,+ default: 30,+ },+ },+ ),+ required_scopes: %w[mcp:private-messages:read],+ annotations: READ_ONLY,+ )+ registry.register_tool(+ "discourse_read_private_message",+ title: "Read private message",+ description: "Reads a private message visible to the authenticated user.",+ implementation: Tools::ReadPrivateMessage,+ input_schema:+ object_schema(+ {+ topic_id: {+ type: "integer",+ minimum: 1,+ },+ post_limit: {+ type: "integer",+ minimum: 1,+ maximum: 50,+ default: 5,+ },+ start_post_number: {+ type: "integer",+ minimum: 1,+ },+ },+ required: %w[topic_id],+ ),+ required_scopes: %w[mcp:private-messages:read],+ annotations: READ_ONLY,+ )+ end++ def register_write_tools(registry)+ registry.register_tool(+ "discourse_create_topic",+ title: "Create topic",+ description: "Creates a topic as the authenticated user.",+ implementation: Tools::CreateTopic,+ input_schema:+ object_schema(+ {+ title: {+ type: "string",+ minLength: 1,+ maxLength: 300,+ },+ raw: {+ type: "string",+ minLength: 1,+ maxLength: 30_000,+ },+ category_id: {+ type: "integer",+ },+ tags: {+ type: "array",+ items: {+ type: "string",+ },+ maxItems: 10,+ },+ author_username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ },+ required: %w[title raw],+ ),+ required_scopes: %w[mcp:content:write],+ annotations: WRITE,+ risk: :write,+ )+ registry.register_tool(+ "discourse_create_post",+ title: "Create post",+ description: "Creates a reply in a topic as the authenticated user.",+ implementation: Tools::ReplyTopic,+ input_schema:+ object_schema(+ {+ topic_id: {+ type: "integer",+ minimum: 1,+ },+ raw: {+ type: "string",+ minLength: 1,+ maxLength: 30_000,+ },+ reply_to_post_number: {+ type: "integer",+ minimum: 1,+ },+ author_username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ },+ required: %w[topic_id raw],+ ),+ required_scopes: %w[mcp:content:write],+ annotations: WRITE,+ risk: :write,+ )+ registry.register_tool(+ "discourse_update_post",+ title: "Update post",+ description: "Edits a post when the authenticated user has permission.",+ implementation: Tools::EditPost,+ input_schema:+ object_schema(+ {+ post_id: {+ type: "integer",+ minimum: 1,+ },+ raw: {+ type: "string",+ minLength: 1,+ maxLength: 30_000,+ },+ edit_reason: {+ type: "string",+ maxLength: 500,+ },+ },+ required: %w[post_id raw],+ ),+ required_scopes: %w[mcp:content:write],+ annotations: WRITE,+ risk: :write,+ )+ registry.register_tool(+ "discourse_update_topic",+ title: "Update topic",+ description: "Updates fields on a topic when the user may edit it.",+ implementation: Tools::UpdateTopic,+ input_schema:+ object_schema(+ {+ topic_id: {+ type: "integer",+ minimum: 1,+ },+ title: {+ type: "string",+ minLength: 1,+ maxLength: 300,+ },+ category_id: {+ type: "integer",+ minimum: 0,+ },+ tags: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ maxItems: 10,+ },+ featured_link: {+ type: "string",+ maxLength: 2_048,+ },+ original_title: {+ type: "string",+ maxLength: 300,+ },+ original_tags: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ maxItems: 10,+ },+ },+ required: %w[topic_id],+ ),+ required_scopes: %w[mcp:content:write],+ annotations: WRITE,+ risk: :write,+ )+ registry.register_tool(+ "discourse_update_user",+ title: "Update user",+ description: "Updates the authenticated user's own profile.",+ implementation: Tools::UpdateUser,+ input_schema:+ object_schema(+ {+ username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ name: {+ type: "string",+ maxLength: 255,+ },+ bio_raw: {+ type: "string",+ maxLength: 3_000,+ },+ location: {+ type: "string",+ maxLength: 1_000,+ },+ website: {+ type: "string",+ maxLength: 2_048,+ },+ title: {+ type: "string",+ maxLength: 255,+ },+ date_of_birth: {+ type: "string",+ format: "date",+ },+ locale: {+ type: "string",+ maxLength: 20,+ },+ profile_background_upload_url: {+ type: "string",+ maxLength: 2_048,+ },+ card_background_upload_url: {+ type: "string",+ maxLength: 2_048,+ },+ upload_id: {+ type: "integer",+ minimum: 1,+ },+ },+ required: %w[username],+ ),+ required_scopes: %w[mcp:profile:write],+ annotations: WRITE,+ risk: :write,+ )+ registry.register_tool(+ "discourse_upload_file",+ title: "Upload file",+ description: "Uploads base64 data or a remote HTTP(S) file for the authenticated user.",+ implementation: Tools::UploadFile,+ input_schema:+ object_schema(+ {+ upload_type: {+ type: "string",+ enum: Tools::UploadFile::UPLOAD_TYPES,+ },+ image_data: {+ type: "string",+ minLength: 1,+ },+ url: {+ type: "string",+ minLength: 1,+ maxLength: 2_048,+ },+ filename: {+ type: "string",+ minLength: 1,+ maxLength: 255,+ },+ user_id: {+ type: "integer",+ minimum: 1,+ },+ },+ required: %w[upload_type],+ ),+ required_scopes: %w[mcp:content:write],+ annotations: EXTERNAL_SIDE_EFFECT,+ risk: :external_side_effect,+ )+ registry.register_tool(+ "discourse_create_private_message",+ title: "Create private message",+ description: "Creates a private message as the authenticated user.",+ implementation: Tools::CreatePrivateMessage,+ input_schema:+ object_schema(+ {+ title: {+ type: "string",+ minLength: 1,+ maxLength: 300,+ },+ raw: {+ type: "string",+ minLength: 1,+ maxLength: 30_000,+ },+ usernames: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ maxItems: 100,+ },+ group_names: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ maxItems: 100,+ },+ email_addresses: {+ type: "array",+ items: {+ type: "string",+ format: "email",+ },+ maxItems: 100,+ },+ author_username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ },+ required: %w[title raw],+ ),+ required_scopes: %w[mcp:private-messages:write],+ annotations: EXTERNAL_SIDE_EFFECT,+ risk: :external_side_effect,+ )+ registry.register_tool(+ "discourse_reply_private_message",+ title: "Reply to private message",+ description: "Replies to a private message visible to the authenticated user.",+ implementation: Tools::ReplyPrivateMessage,+ input_schema:+ object_schema(+ {+ topic_id: {+ type: "integer",+ minimum: 1,+ },+ raw: {+ type: "string",+ minLength: 1,+ maxLength: 30_000,+ },+ reply_to_post_number: {+ type: "integer",+ minimum: 1,+ },+ author_username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ },+ required: %w[topic_id raw],+ ),+ required_scopes: %w[mcp:private-messages:write],+ annotations: WRITE,+ risk: :write,+ )+ registry.register_tool(+ "discourse_invite_to_private_message",+ title: "Invite to private message",+ description:+ "Adds one user or group, or submits one email invitation, to a private message.",+ implementation: Tools::InviteToPrivateMessage,+ input_schema:+ object_schema(+ {+ topic_id: {+ type: "integer",+ minimum: 1,+ },+ username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ group_name: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ email_address: {+ type: "string",+ format: "email",+ },+ notify_group_members: {+ type: "boolean",+ },+ custom_message: {+ type: "string",+ minLength: 1,+ maxLength: 3_000,+ },+ author_username: {+ type: "string",+ minLength: 1,+ maxLength: 60,+ },+ },+ required: %w[topic_id],+ ),+ required_scopes: %w[mcp:private-messages:write],+ annotations: EXTERNAL_SIDE_EFFECT,+ risk: :external_side_effect,)registry.register_tool("discourse_post_set_deleted",@@ -264,6 +1011,82 @@ module DiscourseMcpannotations: DESTRUCTIVE,risk: :destructive,)+ registry.register_tool(+ "discourse_save_draft",+ title: "Save draft",+ description: "Creates or updates a draft for the authenticated user.",+ implementation: Tools::SaveDraft,+ input_schema:+ object_schema(+ {+ draft_key: {+ type: "string",+ minLength: 1,+ maxLength: 40,+ },+ reply: {+ type: "string",+ minLength: 1,+ maxLength: 50_000,+ },+ title: {+ type: "string",+ minLength: 1,+ maxLength: 300,+ },+ category_id: {+ type: "integer",+ minimum: 1,+ },+ tags: {+ type: "array",+ items: {+ type: "string",+ minLength: 1,+ maxLength: 100,+ },+ maxItems: 10,+ },+ sequence: {+ type: "integer",+ minimum: 0,+ default: 0,+ },+ action: {+ type: "string",+ enum: %w[createTopic reply edit privateMessage],+ },+ },+ required: %w[draft_key reply],+ ),+ required_scopes: %w[mcp:drafts:write],+ annotations: WRITE,+ risk: :write,+ )+ registry.register_tool(+ "discourse_delete_draft",+ title: "Delete draft",+ description: "Deletes one of the authenticated user's drafts at its current sequence.",+ implementation: Tools::DeleteDraft,+ input_schema:+ object_schema(+ {+ draft_key: {+ type: "string",+ minLength: 1,+ maxLength: 40,+ },+ sequence: {+ type: "integer",+ minimum: 0,+ },+ },+ required: %w[draft_key sequence],+ ),+ required_scopes: %w[mcp:drafts:write],+ annotations: DESTRUCTIVE,+ risk: :destructive,+ )registry.register_tool("discourse_user_status_set",title: "Set user status",@@ -380,7 +1203,7 @@ module DiscourseMcp{uri: uri,mimeType: "application/json",- text: JSON.generate(ToolHelpers.topic_json(topic)),+ text: JSON.generate(ToolHelpers.topic_json(topic, request_context.guardian)),}endenddiff --git a/lib/discourse_mcp/core_tools.rb b/lib/discourse_mcp/core_tools.rbindex 9ec246cb7eb..8a91698d537 100644--- a/lib/discourse_mcp/core_tools.rb+++ b/lib/discourse_mcp/core_tools.rb@@ -1,7 +1,13 @@# frozen_string_literal: true+require "base64"+require "directory_items_query"+require "tempfile"+module DiscourseMcpmodule ToolHelpers+ MAX_READ_LENGTH = 50_000+module_functiondef text_and_structured(value)@@ -25,13 +31,15 @@ module DiscourseMcp}end- def topic_json(topic)+ def topic_json(topic, guardian, visible_tag_ids: nil)+ visible_tag_ids ||= self.visible_tag_ids([topic], guardian)+{id: topic.id,title: topic.title,slug: topic.slug,category_id: topic.category_id,- tags: topic.tags.map(&:name),+ tags: topic.tags.select { |tag| visible_tag_ids.include?(tag.id) }.map(&:name),posts_count: topic.posts_count,created_at: topic.created_at.iso8601,last_posted_at: topic.last_posted_at&.iso8601,@@ -40,6 +48,135 @@ module DiscourseMcpurl: topic.url,}end++ def discovery_topic_json(topic, visible_tag_ids)+ posters = topic.posters || topic.posters_summary+ latest_poster = posters.find { |poster| poster.extras.to_s.split.include?("latest") }++ {+ id: topic.id,+ slug: topic.slug,+ title: topic.title,+ category_id: topic.category_id,+ tags: topic.tags.select { |tag| visible_tag_ids.include?(tag.id) }.map(&:name),+ created_at: topic.created_at.iso8601,+ last_posted_at: topic.last_posted_at&.iso8601,+ bumped_at: topic.bumped_at&.iso8601,+ posts_count: topic.posts_count,+ reply_count: topic.reply_count,+ views: topic.views,+ like_count: topic.like_count,+ posters_count: topic.participant_count,+ closed: topic.closed,+ archived: topic.archived,+ pinned: PinnedCheck.pinned?(topic, topic.user_data),+ visible: topic.visible,+ last_poster_username: latest_poster&.user&.username,+ posters:+ posters.map do |poster|+ {+ user_id: poster.user&.id,+ username: poster.user&.username,+ description: poster.description,+ }+ end,+ }+ end++ def evidence_post_json(post, excerpt: nil, include_raw: false)+ user = post.user+ topic = post.topic+ result = {+ id: post.id,+ topic_id: post.topic_id,+ post_number: post.post_number,+ post_type: post.post_type,+ username: user&.username,+ user_id: post.user_id,+ name: SiteSetting.enable_names? ? user&.name : nil,+ created_at: post.created_at.iso8601,+ updated_at: post.updated_at.iso8601,+ excerpt: excerpt,+ reply_to_post_number: post.reply_to_post_number,+ reply_count: post.reply_count,+ like_count: post.like_count,+ category_id: topic&.category_id,+ topic_slug: topic&.slug,+ topic_title: topic&.title,+ staff: user&.staff?,+ moderator: user&.moderator?,+ admin: user&.admin?,+ hidden: post.hidden,+ deleted_at: post.deleted_at&.iso8601,+ }++ if include_raw+ result[:raw] = post.raw.to_s.first(MAX_READ_LENGTH)+ result[:truncated] = post.raw.to_s.length > MAX_READ_LENGTH+ end++ %i[accepted_answer topic_accepted_answer].each do |field|+ result[field] = post.public_send(field) if post.respond_to?(field)+ end+ result+ end++ def visible_tag_ids(topics, guardian)+ DiscourseTagging.visible_tag_ids(topics.flat_map(&:tags), guardian)+ end++ def post_excerpt(post, guardian)+ cooked = ContentLocalization.translated_post_cooked(post, guardian)+ cooked ? Post.excerpt(cooked, nil, post:) : post.excerpt+ end++ def visible_user!(username, guardian)+ user = User.find_by_username(username)+ if user.blank? || !guardian.can_see_profile?(user)+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.user_not_found")+ end++ user+ end++ def visible_post!(post_id, guardian)+ post = Post.with_deleted.find_by(id: post_id)+ topic = Topic.with_deleted.find_by(id: post&.topic_id)+ post.association(:topic).target = topic if post && topic++ if post.blank? || topic.blank? || !guardian.can_see?(topic) || !guardian.can_see?(post)+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.post_not_found")+ end++ post+ end++ def ensure_current_author!(arguments, user)+ requested_author = arguments["author_username"]+ return if requested_author.blank? || requested_author.casecmp?(user.username)++ raise Discourse::InvalidAccess+ end++ def user_post_json(action)+ {+ id: action.post_id || action.id,+ topic_id: action.topic_id,+ post_number: action.post_number,+ slug: Slug.for(action.title),+ title: action.title,+ created_at: action.created_at&.iso8601,+ excerpt:+ (+ if action.cooked.present?+ PrettyText.excerpt(action.cooked, 300, keep_emoji_images: true)+ else+ nil+ end+ ),+ category_id: action.category_id,+ }+ endendmodule Tools@@ -62,42 +199,628 @@ module DiscourseMcpclass Searchdef self.call(arguments:, request_context:)query = arguments.fetch("query").to_s- limit = arguments.fetch("limit", 20).to_i.clamp(1, 50)+ limit = arguments.fetch("max_results", 10)results = ::Search.execute(query, guardian: request_context.guardian)- posts = results.posts.first(limit).map { |post| ToolHelpers.post_json(post) }- ToolHelpers.text_and_structured(query: query, posts: posts)+ topics = results.posts.filter_map(&:topic).uniq(&:id).first(limit + 1)+ has_more = topics.length > limit+ topics = topics.first(limit)+ ToolHelpers.text_and_structured(+ results: topics.map { |topic| topic.slice(:id, :slug, :title).symbolize_keys },+ meta: {+ total: topics.length,+ has_more:,+ },+ )+ end+ end++ class FilterTopics+ TOP_PERIODS = %w[daily weekly monthly quarterly yearly all].freeze++ def self.call(arguments:, request_context:)+ view = arguments.fetch("view", "filtered")+ filter = arguments["filter"]&.strip+ top_period = arguments["top_period"]+ page = arguments.fetch("page", 0)+ per_page = arguments.fetch("per_page", 20)+ validate_arguments!(view:, filter:, top_period:)++ period = view == "hot" ? "daily" : (top_period || "weekly" if view == "top")+ topics = topic_page(view:, filter:, period:, page:, per_page:, request_context:)+ next_topics =+ topic_page(+ view:,+ filter:,+ period:,+ page: (page + 1) * per_page,+ per_page: 1,+ request_context:,+ )++ visible_tag_ids = ToolHelpers.visible_tag_ids(topics, request_context.guardian)+ results = topics.map { |topic| ToolHelpers.discovery_topic_json(topic, visible_tag_ids) }+ ToolHelpers.text_and_structured(+ results:,+ meta: {+ view:,+ top_period: period,+ page:,+ per_page:,+ returned: results.length,+ has_more: next_topics.present?,+ },+ )+ end++ def self.validate_arguments!(view:, filter:, top_period:)+ if view == "filtered" && filter.blank?+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.filter_required")+ end+ if view != "filtered" && filter.present?+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.filter_only_for_filtered_view")+ end+ if view != "top" && top_period.present?+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.top_period_only_for_top_view")+ end+ end+ private_class_method :validate_arguments!++ def self.topic_page(view:, filter:, period:, page:, per_page:, request_context:)+ options = { page:, per_page: }+ options[:q] = filter if view == "filtered"+ query = TopicQuery.new(request_context.user, options)+ list =+ if view == "filtered"+ query.list_filter+ else+ query.list_top_for(period.to_sym)+ end+ list.topics+ end+ private_class_method :topic_page+ end++ class SearchPosts+ def self.call(arguments:, request_context:)+ query = arguments.fetch("query")+ page = arguments.fetch("page", 1)+ guardian = request_context.guardian+ results =+ ::Search.execute(+ query,+ guardian:,+ type_filter: "topic",+ search_type: :full_page,+ page:,+ blurb_length: 300,+ )+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.invalid_search_query") if results.blank?++ posts = results.posts+ ActiveRecord::Associations::Preloader.new(+ records: posts,+ associations: [:post_search_data, { user: :primary_group }, { topic: %i[category tags] }],+ ).call+ topics = posts.map(&:topic).compact.uniq(&:id)+ visible_tag_ids = ToolHelpers.visible_tag_ids(topics, guardian)++ ToolHelpers.text_and_structured(+ posts:+ posts.map do |post|+ ToolHelpers.evidence_post_json(post, excerpt: results.blurb(post, scope: guardian))+ end,+ topics: topics.map { |topic| search_topic_json(topic, visible_tag_ids) },+ users: users_json(posts),+ categories: categories_json(topics),+ groups: [],+ tags:+ topics+ .flat_map do |topic|+ topic.tags.select { |tag| visible_tag_ids.include?(tag.id) }.map(&:name)+ end+ .uniq,+ meta: {+ page:,+ returned: posts.length,+ has_more: results.more_full_page_results == true,+ exhaustive: false,+ term: results.term || query,+ },+ )+ end++ def self.search_topic_json(topic, visible_tag_ids)+ {+ id: topic.id,+ slug: topic.slug,+ title: topic.title,+ category_id: topic.category_id,+ posts_count: topic.posts_count,+ reply_count: topic.reply_count,+ views: topic.views,+ like_count: topic.like_count,+ created_at: topic.created_at.iso8601,+ last_posted_at: topic.last_posted_at&.iso8601,+ closed: topic.closed,+ archived: topic.archived,+ tags: topic.tags.select { |tag| visible_tag_ids.include?(tag.id) }.map(&:name),+ }+ end+ private_class_method :search_topic_json++ def self.users_json(posts)+ posts+ .filter_map(&:user)+ .uniq(&:id)+ .map do |user|+ {+ id: user.id,+ username: user.username,+ name: SiteSetting.enable_names? ? user.name : nil,+ avatar_template: user.avatar_template,+ primary_group_name: user.primary_group&.name,+ }+ end+ end+ private_class_method :users_json++ def self.categories_json(topics)+ topics+ .filter_map(&:category)+ .uniq(&:id)+ .map { |category| { id: category.id, name: category.name, slug: category.slug } }+ end+ private_class_method :categories_json+ end++ class ReadTopicPosts+ SELECTION_KEYS = {+ "latest" => %w[limit replies_only],+ "earliest" => %w[limit replies_only],+ "post_ids" => %w[post_ids],+ "around_post" => %w[post_number limit],+ "usernames" => %w[usernames limit replies_only],+ }.freeze++ def self.call(arguments:, request_context:)+ validate_selection!(arguments)+ topic = Topic.with_deleted.find_by(id: arguments.fetch("topic_id"))+ guardian = request_context.guardian+ if topic.blank? || !guardian.can_see?(topic)+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.topic_not_found")+ end++ selection_mode = arguments.fetch("selection_mode")+ limit = arguments.fetch("limit", 20)+ stream_size = nil+ selected_ids = nil+ posts = nil++ if selection_mode == "post_ids"+ selected_ids = arguments.fetch("post_ids")+ elsif selection_mode == "around_post"+ posts = around_posts(topic, arguments.fetch("post_number"), limit, request_context.user)+ else+ stream_size, selected_ids = stream_selection(topic, arguments, request_context)+ end++ posts ||= posts_for_ids(topic, selected_ids, request_context.user, guardian)+ ToolHelpers.text_and_structured(+ topic_id: topic.id,+ selection_mode:,+ posts: posts.map { |post| ToolHelpers.evidence_post_json(post, include_raw: true) },+ meta: {+ visible_stream_size: stream_size,+ selected: selected_ids&.length || posts.length,+ returned: posts.length,+ max_requests: %w[post_ids around_post].include?(selection_mode) ? 1 : 2,+ exhaustive: false,+ },+ )+ end++ def self.validate_selection!(arguments)+ selection_mode = arguments["selection_mode"]+ allowed_keys = SELECTION_KEYS[selection_mode]+ supplied_keys = arguments.filter_map { |key, value| key unless value.nil? }+ supplied_selection_keys = supplied_keys - %w[topic_id selection_mode]+ required_key = "post_ids" if selection_mode == "post_ids"+ required_key = "post_number" if selection_mode == "around_post"+ required_key = "usernames" if selection_mode == "usernames"++ if allowed_keys.blank? ||+ supplied_selection_keys.any? { |key| allowed_keys.exclude?(key) } ||+ (required_key && arguments[required_key].blank?)+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.invalid_post_selection")+ end+ end+ private_class_method :validate_selection!++ def self.stream_selection(topic, arguments, request_context)+ options = { limit: 1, include_suggested: false, include_related: false }+ if arguments.fetch("selection_mode") == "usernames"+ options[:username_filters] = arguments.fetch("usernames")+ end+ topic_view = TopicView.new(topic, request_context.user, options)+ posts =+ request_context.guardian.filter_hidden_posts(+ topic_view.filtered_posts,+ category: topic.category,+ )+ stream_size = posts.count+ posts = posts.where("posts.post_number > 1") if arguments["replies_only"]+ limit = arguments.fetch("limit", 20)+ selected_ids =+ if arguments.fetch("selection_mode") == "latest"+ posts.reorder(sort_order: :desc).limit(limit).pluck(:id).reverse+ else+ posts.reorder(sort_order: :asc).limit(limit).pluck(:id)+ end+ [stream_size, selected_ids]+ end+ private_class_method :stream_selection++ def self.around_posts(topic, post_number, limit, user)+ topic_view =+ TopicView.new(+ topic,+ user,+ post_number:,+ limit:,+ include_suggested: false,+ include_related: false,+ )+ guardian = topic_view.guardian+ posts_visible_to_guardian(topic_view.posts, topic, guardian).first(limit)+ end+ private_class_method :around_posts++ def self.posts_for_ids(topic, post_ids, user, guardian)+ topic_view =+ TopicView.new(+ topic,+ user,+ post_ids:,+ limit: 50,+ include_suggested: false,+ include_related: false,+ )+ visible_posts = posts_visible_to_guardian(topic_view.posts, topic, guardian)+ posts = visible_posts.index_by(&:id)+ post_ids.filter_map { |post_id| posts[post_id] }end+ private_class_method :posts_for_ids++ def self.posts_visible_to_guardian(posts, topic, guardian)+ posts.select do |post|+ post.association(:topic).target = topic+ guardian.can_see?(post)+ end+ end+ private_class_method :posts_visible_to_guardian+ end++ class GetPostReplies+ DIRECT_REPLIES_LIMIT = 20+ MODES = %w[reply_ids direct_replies reply_history].freeze++ def self.call(arguments:, request_context:)+ guardian = request_context.guardian+ post = ToolHelpers.visible_post!(arguments.fetch("post_id"), guardian)+ mode = arguments.fetch("mode", "reply_ids")+ if MODES.exclude?(mode)+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.invalid_reply_mode")+ end++ return reply_ids_result(post, guardian) if mode == "reply_ids"++ posts =+ if mode == "direct_replies"+ direct_replies(post, arguments["after_post_number"], request_context)+ else+ reply_history(post, request_context)+ end++ ToolHelpers.text_and_structured(+ post_id: post.id,+ mode:,+ posts: posts.map { |reply| ToolHelpers.evidence_post_json(reply, include_raw: true) },+ meta: {+ returned: posts.length,+ has_more: nil,+ page_was_full: mode == "direct_replies" ? posts.length == DIRECT_REPLIES_LIMIT : nil,+ upstream_limit:+ mode == "direct_replies" ? DIRECT_REPLIES_LIMIT : "site max_reply_history",+ },+ )+ end++ def self.reply_ids_result(post, guardian)+ replies = post.reply_ids(guardian)+ reply_posts = Post.with_deleted.where(id: replies.pluck(:id)).index_by(&:id)+ visible_replies =+ replies.select do |reply|+ reply_post = reply_posts[reply[:id]]+ next false if reply_post.blank?++ reply_post.association(:topic).target = post.topic+ guardian.can_see?(reply_post)+ end++ ToolHelpers.text_and_structured(+ post_id: post.id,+ mode: "reply_ids",+ replies: visible_replies,+ meta: {+ returned: visible_replies.length,+ exhaustive: false,+ upstream_bounded: "recursive descendants up to depth 1000",+ },+ )+ end+ private_class_method :reply_ids_result++ def self.direct_replies(post, after_post_number, request_context)+ after_post_number = [after_post_number.to_i, 1].max+ post_ids =+ post+ .replies+ .secured(request_context.guardian)+ .where(post_number: after_post_number + 1..)+ .order(:post_number)+ .limit(DIRECT_REPLIES_LIMIT)+ .pluck(:id)+ posts_for_ids(post.topic, post_ids, request_context)+ end+ private_class_method :direct_replies++ def self.reply_history(post, request_context)+ topic_view =+ TopicView.new(+ post.topic,+ request_context.user,+ include_suggested: false,+ include_related: false,+ reply_history_for: post.id,+ )+ topic_view.posts.select { |reply| request_context.guardian.can_see?(reply) }+ end+ private_class_method :reply_history++ def self.posts_for_ids(topic, post_ids, request_context)+ return [] if post_ids.empty?++ topic_view =+ TopicView.new(+ topic,+ request_context.user,+ post_ids:,+ include_related: false,+ include_suggested: false,+ )+ posts = topic_view.posts.index_by(&:id)+ post_ids.filter_map do |post_id|+ post = posts[post_id]+ post if request_context.guardian.can_see?(post)+ end+ end+ private_class_method :posts_for_ids+ end++ class ListLatestPosts+ def self.call(arguments:, request_context:)+ before_post_id = arguments["before_post_id"]+ posts =+ LatestPostsQuery+ .new(user: request_context.user, guardian: request_context.guardian)+ .public_posts(before_post_id:)+ .to_a+ rows =+ (+ if arguments.fetch("replies_only", false)+ posts.select { |post| post.post_number > 1 }+ else+ posts+ end+ )++ ToolHelpers.text_and_structured(+ posts:+ rows.map do |post|+ ToolHelpers.evidence_post_json(+ post,+ excerpt: ToolHelpers.post_excerpt(post, request_context.guardian),+ include_raw: true,+ )+ end,+ meta: {+ before_post_id:,+ upstream_page_size: LatestPostsQuery::PAGE_SIZE,+ upstream_returned: posts.length,+ returned: rows.length,+ has_more: nil,+ page_was_full: posts.length == LatestPostsQuery::PAGE_SIZE,+ next_before_post_id: posts.last&.id,+ replies_only_projection: arguments.fetch("replies_only", false),+ anonymous_cache_seconds: 60,+ },+ )+ end+ end++ class GetTopicViewStats+ def self.call(arguments:, request_context:)+ topic = Topic.find_by(id: arguments.fetch("topic_id"))+ if topic.blank? || !request_context.guardian.can_see?(topic)+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.topic_not_found")+ end++ from = arguments["from"] ? parse_date(arguments["from"]) : 30.days.ago.to_date+ to = arguments["to"] ? parse_date(arguments["to"]) : Date.current+ stats = TopicViewStatsQuery.call(topic:, guardian: request_context.guardian, from:, to:)+ rows =+ stats.map do |stat|+ {+ viewed_at: stat.viewed_at.iso8601,+ views: stat.anonymous_views + stat.logged_in_views,+ }+ end++ ToolHelpers.text_and_structured(+ topic_id: topic.id,+ view_stats: rows,+ meta: {+ from: arguments["from"],+ to: arguments["to"],+ default_range_days: arguments["from"] || arguments["to"] ? nil : 30,+ upstream_max_rows: TopicViewStatsQuery::MAX_STATS,+ returned: rows.length,+ },+ )+ end++ def self.parse_date(value)+ Date.iso8601(value)+ rescue Date::Error+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.invalid_date")+ end+ private_class_method :parse_date+ end++ class ListDirectoryItems+ PAGE_SIZE = ::DirectoryItemsQuery::PAGE_SIZE+ PAGE_LIMIT = ::DirectoryItemsQuery::PAGE_LIMIT++ def self.call(arguments:, request_context:)+ unless SiteSetting.enable_user_directory?+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.user_directory_disabled")+ end++ period = arguments.fetch("period")+ period_type = DirectoryItem.period_types[period.to_sym]+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.invalid_directory_period") if !period_type++ page = arguments.fetch("page", 0)+ limit = arguments.fetch("limit", DirectoryItemsQuery::PAGE_SIZE)+ begin+ query_result =+ ::DirectoryItemsQuery.new(+ user: request_context.user,+ guardian: request_context.guardian,+ ).call(+ period_type:,+ group_name: arguments["group"],+ exclude_group_names: arguments["exclude_groups"],+ exclude_usernames: arguments["exclude_usernames"],+ order: arguments["order"],+ ascending: arguments.fetch("ascending", false),+ name: arguments["name"],+ username: arguments["username"],+ page:,+ limit:,+ )+ rescue ::DirectoryItemsQuery::GroupNotFound, Discourse::InvalidAccess+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.group_not_found")+ end+ rows =+ query_result.items.map do |item|+ item_json(item, period_type, query_result.active_column_names)+ end+ has_more = (page + 1) * limit < query_result.total++ ToolHelpers.text_and_structured(+ directory_items: rows,+ meta: {+ page:,+ limit:,+ returned: rows.length,+ total: query_result.total,+ has_more:,+ next_page: has_more ? page + 1 : nil,+ last_updated_at: query_result.last_updated_at&.iso8601,+ },+ )+ end++ def self.item_json(item, period_type, active_attributes)+ user = item.user+ result = {+ id: user.id,+ user: {+ id: user.id,+ username: user.username,+ name: SiteSetting.enable_names? ? user.name : nil,+ avatar_template: user.avatar_template,+ primary_group_name: user.primary_group&.name,+ },+ time_read:+ period_type == DirectoryItem.period_types[:all] ? item.user_stat&.time_read : nil,+ }+ DirectoryColumn.automatic_column_names.each do |attribute|+ result[attribute] = (+ if active_attributes.include?(attribute)+ item.public_send(attribute)+ else+ nil+ end+ )+ end+ result+ end+ private_class_method :item_jsonendclass GetTopicdef self.call(arguments:, request_context:)topic = Topic.find_by(id: arguments.fetch("topic_id").to_i)if topic.blank? || !request_context.guardian.can_see?(topic)- raise DiscourseMcp::ToolError, "Topic not found"+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.topic_not_found")end- limit = arguments.fetch("post_limit", 50).to_i.clamp(1, 100)+ limit = arguments.fetch("post_limit", 5)+ start_post_number = arguments.fetch("start_post_number", 1)posts =Post.secured(request_context.guardian).where(topic_id: topic.id)+ .where(post_number: start_post_number..).order(:post_number)- .limit(limit)- ToolHelpers.text_and_structured(- topic: ToolHelpers.topic_json(topic),- posts: posts.map { |post| ToolHelpers.post_json(post) },- )+ .limit(limit + 1)+ .includes(:topic, :user)+ .to_a+ has_more = posts.length > limit+ posts = posts.first(limit)+ visible_tag_ids = ToolHelpers.visible_tag_ids([topic], request_context.guardian)+ result =+ ToolHelpers.topic_json(topic, request_context.guardian, visible_tag_ids:).merge(+ posts: posts.map { |post| ToolHelpers.evidence_post_json(post, include_raw: true) },+ meta: {+ start_post: start_post_number,+ returned: posts.length,+ has_more:,+ },+ )+ ToolHelpers.text_and_structured(result)endendclass GetPostdef self.call(arguments:, request_context:)- post = Post.secured(request_context.guardian).find_by(id: arguments.fetch("post_id").to_i)- if post.blank? || !request_context.guardian.can_see?(post)- raise DiscourseMcp::ToolError, "Post not found"- end-- ToolHelpers.text_and_structured(post: ToolHelpers.post_json(post))+ post = ToolHelpers.visible_post!(arguments.fetch("post_id"), request_context.guardian)+ result =+ ToolHelpers.evidence_post_json(post, include_raw: true).slice(+ :id,+ :topic_id,+ :topic_slug,+ :post_number,+ :username,+ :created_at,+ :raw,+ :truncated,+ :accepted_answer,+ :topic_accepted_answer,+ )+ ToolHelpers.text_and_structured(result)endend@@ -106,8 +829,12 @@ module DiscourseMcplimit = arguments.fetch("limit", 30).to_i.clamp(1, 50)topics = TopicQuery.new(request_context.user).list_latest.topics.first(limit)ActiveRecord::Associations::Preloader.new(records: topics, associations: :tags).call+ visible_tag_ids = ToolHelpers.visible_tag_ids(topics, request_context.guardian)ToolHelpers.text_and_structured(- topics: topics.map { |topic| ToolHelpers.topic_json(topic) },+ topics:+ topics.map do |topic|+ ToolHelpers.topic_json(topic, request_context.guardian, visible_tag_ids:)+ end,)endend@@ -146,22 +873,178 @@ module DiscourseMcpclass GetUserdef self.call(arguments:, request_context:)- user = User.find_by_username(arguments.fetch("username"))- if user.blank? || !request_context.guardian.can_see_profile?(user)- raise DiscourseMcp::ToolError, "User not found"- end+ user = ToolHelpers.visible_user!(arguments.fetch("username"), request_context.guardian)details = {id: user.id,username: user.username,+ name: SiteSetting.enable_names? ? user.name : nil,trust_level: user.trust_level,created_at: user.created_at.iso8601,+ bio: user.user_profile.bio_raw.to_s.first(500),+ admin: user.admin,+ moderator: user.moderator,}- details[:name] = user.name if SiteSetting.enable_names?- ToolHelpers.text_and_structured(user: details)+ ToolHelpers.text_and_structured(details)endend+ class ListUserPosts+ def self.call(arguments:, request_context:)+ guardian = request_context.guardian+ user = ToolHelpers.visible_user!(arguments.fetch("username"), guardian)+ unless guardian.can_see_user_actions?(user, [UserAction::NEW_TOPIC, UserAction::REPLY])+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.user_not_found")+ end++ page = arguments.fetch("page", 0)+ limit = arguments.fetch("limit", 30)+ actions =+ UserAction.stream(+ user_id: user.id,+ user:,+ offset: page * limit,+ limit: limit + 1,+ action_types: [UserAction::NEW_TOPIC, UserAction::REPLY],+ guardian:,+ ignore_private_messages: true,+ ).to_a+ has_more = actions.length > limit+ posts = actions.first(limit).map { |action| ToolHelpers.user_post_json(action) }++ ToolHelpers.text_and_structured(posts:, meta: { page:, limit:, has_more: })+ end+ end++ class GetUserSummary+ METRICS = %i[+ likes_given+ likes_received+ topics_entered+ posts_read_count+ days_visited+ topic_count+ post_count+ time_read+ recent_time_read+ bookmark_count+ can_see_summary_stats+ can_see_user_actions+ ].freeze++ def self.call(arguments:, request_context:)+ guardian = request_context.guardian+ user = ToolHelpers.visible_user!(arguments.fetch("username"), guardian)+ summary =+ UserSummarySerializer.new(UserSummary.new(user, guardian), scope: guardian, root: false)+ serialized = summary.as_json.deep_symbolize_keys+ result = { username: user.username }+ METRICS.each { |metric| result[metric] = serialized[metric] }+ result[:top_topics] = serialized[:topics] || []+ result[:top_replies] = serialized[:replies] || []+ result[:top_links] = serialized[:links] || []+ result[:most_liked_by_users] = serialized[:most_liked_by_users] || []+ result[:most_liked_users] = serialized[:most_liked_users] || []+ result[:most_replied_to_users] = serialized[:most_replied_to_users] || []+ result[:top_categories] = serialized[:top_categories] || []+ result[:badges] = serialized[:badges] || []+ ToolHelpers.text_and_structured(result)+ end+ end++ class ListUserActions+ ACTION_TYPES = {+ "likes" => 1,+ "was_liked" => 2,+ "topics" => 4,+ "replies" => 5,+ "responses" => 6,+ "mentions" => 7,+ "quotes" => 9,+ "edits" => 11,+ "private_messages_sent" => 12,+ "private_messages_received" => 13,+ "solved" => 15,+ "assigned" => 16,+ "linked" => 17,+ }.freeze+ ACTION_NAMES = ACTION_TYPES.invert.freeze++ def self.call(arguments:, request_context:)+ guardian = request_context.guardian+ user = ToolHelpers.visible_user!(arguments.fetch("username"), guardian)+ requested_types = Array(arguments["action_types"]).map { |name| ACTION_TYPES.fetch(name) }+ if !guardian.can_see_user_actions?(user, requested_types)+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.user_not_found")+ end++ action_types = requested_types+ if action_types.empty? && !guardian.can_see_user_actions?(user, UserAction.private_types)+ action_types = UserAction.types.values - UserAction.private_types+ end++ offset = arguments.fetch("offset", 0)+ limit = arguments.fetch("limit", 30)+ actions =+ UserAction.stream(+ user_id: user.id,+ user:,+ offset:,+ limit: limit + 1,+ action_types:,+ guardian:,+ ignore_private_messages: arguments["action_types"].blank?,+ acting_username: arguments["acting_username"],+ ).to_a+ has_more = actions.length > limit+ rows = actions.first(limit).map { |action| action_json(action) }+ categories = categories_json(actions.first(limit), guardian)++ ToolHelpers.text_and_structured(+ actions: rows,+ categories:,+ meta: {+ offset:,+ limit:,+ returned: rows.length,+ has_more:,+ next_offset: has_more ? offset + rows.length : nil,+ },+ )+ end++ def self.action_json(action)+ ToolHelpers.user_post_json(action).merge(+ action_type: ACTION_NAMES.fetch(action.action_type, "unknown"),+ action_type_id: action.action_type,+ id: action.id,+ post_id: action.post_id,+ username: action.username,+ acting_username: action.acting_username,+ target_username: action.target_username,+ )+ end+ private_class_method :action_json++ def self.categories_json(actions, guardian)+ category_ids = actions.filter_map(&:category_id).uniq+ return [] if category_ids.empty?++ Category+ .secured(guardian)+ .with_parents(category_ids)+ .map do |category|+ {+ id: category.id,+ name: category.name,+ slug: category.slug,+ parent_category_id: category.parent_category_id,+ }+ end+ end+ private_class_method :categories_json+ end+class ListBookmarksdef self.call(arguments:, request_context:)bookmarks =@@ -217,6 +1100,7 @@ module DiscourseMcpclass CreateTopicdef self.call(arguments:, request_context:)+ ToolHelpers.ensure_current_author!(arguments, request_context.user)post =PostCreator.create!(request_context.user,@@ -226,15 +1110,23 @@ module DiscourseMcptags: Array(arguments["tags"]),skip_validations: false,)+ requested_author = arguments["author_username"]ToolHelpers.text_and_structured(- post: ToolHelpers.post_json(post),- topic: ToolHelpers.topic_json(post.topic),+ id: post.id,+ topic_id: post.topic_id,+ slug: post.topic.slug,+ title: post.topic.title,+ username: post.user.username,+ requested_author:,+ author_applied:+ requested_author.present? ? post.user.username.casecmp?(requested_author) : nil,)endendclass ReplyTopicdef self.call(arguments:, request_context:)+ ToolHelpers.ensure_current_author!(arguments, request_context.user)post =PostCreator.create!(request_context.user,@@ -242,7 +1134,16 @@ module DiscourseMcpraw: arguments.fetch("raw"),reply_to_post_number: arguments["reply_to_post_number"],)- ToolHelpers.text_and_structured(post: ToolHelpers.post_json(post))+ requested_author = arguments["author_username"]+ ToolHelpers.text_and_structured(+ id: post.id,+ topic_id: post.topic_id,+ post_number: post.post_number,+ username: post.user.username,+ requested_author:,+ author_applied:+ requested_author.present? ? post.user.username.casecmp?(requested_author) : nil,+ )endend@@ -250,16 +1151,664 @@ module DiscourseMcpdef self.call(arguments:, request_context:)post = Post.find_by(id: arguments.fetch("post_id").to_i)if post.blank? || !request_context.guardian.can_edit_post?(post)- raise DiscourseMcp::ToolError, "Post not found"+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.post_not_found")endfields = { raw: arguments.fetch("raw") }fields[:edit_reason] = arguments["edit_reason"] if arguments["edit_reason"].present?- PostRevisor.new(post, post.topic).revise!(request_context.user, fields)- ToolHelpers.text_and_structured(post: ToolHelpers.post_json(post.reload))+ success = PostRevisor.new(post, post.topic).revise!(request_context.user, fields)+ raise ToolError, post.errors.full_messages.join(", ") if !success+ post.reload+ ToolHelpers.text_and_structured(+ id: post.id,+ topic_id: post.topic_id,+ post_number: post.post_number,+ raw: post.raw,+ updated_at: post.updated_at.iso8601,+ edit_reason: post.edit_reason,+ )endend+ class UpdateTopic+ MUTABLE_FIELDS = %w[title category_id tags featured_link].freeze++ def self.call(arguments:, request_context:)+ topic = Topic.find_by(id: arguments.fetch("topic_id"))+ raise ToolError, I18n.t("mcp.errors.topic_not_found") if topic.blank?++ guardian = request_context.guardian+ guardian.ensure_can_edit!(topic)+ verify_original_values!(topic, arguments, guardian)+ changes = requested_changes(topic, arguments, guardian)+ shared_draft = topic.shared_draft+ destination_category_id = changes.delete("category_id") if shared_draft+ updated_fields = changes.keys+ updated_fields << "category_id" if destination_category_id+ raise ToolError, I18n.t("mcp.errors.topic_update_required") if updated_fields.empty?++ Topic.transaction do+ shared_draft.update!(category_id: destination_category_id) if destination_category_id++ if changes.present?+ category_changed = changes.key?("category_id")+ success =+ PostRevisor.new(topic.first_post, topic).revise!(+ request_context.user,+ changes.symbolize_keys,+ validate_post: false,+ )+ if !success+ raise ToolError,+ TopicCategoryChangeValidator.safe_revision_errors(+ topic:,+ guardian:,+ category_changed:,+ ).join(", ")+ end+ end+ end++ topic.reload+ visible_tag_ids = ToolHelpers.visible_tag_ids([topic], guardian)+ ToolHelpers.text_and_structured(+ success: true,+ topic_id: topic.id,+ updated_fields:,+ topic: {+ id: topic.id,+ title: topic.title,+ slug: topic.slug,+ category_id: topic.category_id,+ destination_category_id: topic.shared_draft&.category_id,+ tags: topic.tags.select { |tag| visible_tag_ids.include?(tag.id) }.map(&:name),+ featured_link: topic.featured_link,+ },+ )+ end++ def self.verify_original_values!(topic, arguments, guardian)+ if arguments.key?("original_title") && arguments["original_title"] != topic.title+ raise ToolError, I18n.t("edit_conflict")+ end+ visible_tag_ids = ToolHelpers.visible_tag_ids([topic], guardian)+ visible_tag_names =+ topic.tags.select { |tag| visible_tag_ids.include?(tag.id) }.map(&:name).sort+ if arguments.key?("original_tags") && arguments["original_tags"].sort != visible_tag_names+ raise ToolError, I18n.t("edit_conflict")+ end+ end+ private_class_method :verify_original_values!++ def self.requested_changes(topic, arguments, guardian)+ changes = arguments.slice(*MUTABLE_FIELDS)+ changes.delete("title") if changes["title"] == topic.title+ current_category_id = topic.shared_draft&.category_id || topic.category_id+ changes.delete("category_id") if changes["category_id"].to_i == current_category_id.to_i+ if changes.key?("tags") && PostRevisor.tag_change_noop?(topic, changes["tags"])+ changes.delete("tags")+ end+ changes.delete("featured_link") if changes["featured_link"] == topic.featured_link++ if changes.key?("category_id")+ category_validation =+ TopicCategoryChangeValidator.call(+ topic:,+ category_id: changes["category_id"],+ guardian:,+ tag_names: changes.fetch("tags", topic.tags.map(&:name)),+ tags_changed: changes.key?("tags"),+ )+ if !category_validation.success?+ raise Discourse::InvalidAccess if category_validation.status == :forbidden++ raise ToolError, category_validation.error+ end+ end+ changes+ end+ private_class_method :requested_changes+ end++ class UpdateUser+ PROFILE_FIELDS = %w[+ name+ bio_raw+ location+ website+ title+ date_of_birth+ locale+ profile_background_upload_url+ card_background_upload_url+ ].freeze++ def self.call(arguments:, request_context:)+ user = User.find_by_username(arguments.fetch("username"))+ raise Discourse::InvalidAccess if user.blank? || user.id != request_context.user_id++ attributes = arguments.slice(*PROFILE_FIELDS).symbolize_keys+ upload = avatar_upload(arguments["upload_id"], user, request_context.guardian)+ if attributes.empty? && upload.blank?+ raise ToolError, I18n.t("mcp.errors.user_update_required")+ end+ validate_background_uploads!(attributes, user)++ User.transaction do+ updated = UserUpdater.new(request_context.user, user).update(attributes)+ raise ToolError, user.errors.full_messages.join(", ") if !updated+ update_avatar!(user, upload) if upload+ end++ user.reload+ ToolHelpers.text_and_structured(+ success: true,+ username: user.username,+ updated_fields: attributes.keys.map(&:to_s) + (upload ? ["upload_id"] : []),+ avatar_updated: upload.present?,+ user: {+ id: user.id,+ username: user.username,+ name: user.name,+ bio_raw: user.user_profile.bio_raw,+ location: user.user_profile.location,+ website: user.user_profile.website,+ title: user.title,+ date_of_birth: user.date_of_birth&.iso8601,+ locale: user.locale,+ },+ )+ end++ def 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++ 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)+ upload+ end+ private_class_method :avatar_upload++ def self.validate_background_uploads!(attributes, user)+ %i[profile_background_upload_url card_background_upload_url].each do |field|+ next if !attributes.key?(field) || attributes[field].blank?++ upload = Upload.get_from_url(attributes[field])+ if upload.blank? || upload.user_id != user.id+ raise ToolError, I18n.t("mcp.errors.upload_not_found")+ end+ end+ end+ private_class_method :validate_background_uploads!++ def self.update_avatar!(user, upload)+ (user.user_avatar || user.build_user_avatar).update!(custom_upload_id: upload.id)+ user.update!(uploaded_avatar_id: upload.id)+ end+ private_class_method :update_avatar!+ end++ class UploadFile+ UPLOAD_TYPES = %w[avatar profile_background card_background composer].freeze++ def self.call(arguments:, request_context:)+ user = request_context.user or raise Discourse::InvalidAccess+ if UPLOAD_TYPES.exclude?(arguments.fetch("upload_type"))+ raise ToolError, I18n.t("mcp.errors.invalid_upload_type")+ end+ if arguments["user_id"].present? && arguments["user_id"] != user.id+ raise Discourse::InvalidAccess+ end+ validate_source!(arguments)+ validate_avatar!(arguments.fetch("upload_type"), user)++ RateLimiter.new(+ user,+ "uploads-per-minute",+ SiteSetting.max_uploads_per_minute,+ 1.minute,+ ).performed!+ file = uploaded_file(arguments)+ upload =+ UploadsController.create_upload(+ current_user: user,+ file:,+ url: arguments["url"],+ type: arguments.fetch("upload_type"),+ for_private_message: false,+ for_site_setting: false,+ pasted: false,+ is_api: true,+ retain_hours: 0,+ )+ if !upload.is_a?(Upload)+ raise ToolError, Array(upload[:errors] || upload["errors"]).join(", ")+ end++ serialized = UploadsController.serialize_upload(upload).deep_symbolize_keys+ ToolHelpers.text_and_structured(+ serialized.slice(+ :id,+ :url,+ :short_url,+ :short_path,+ :original_filename,+ :extension,+ :width,+ :height,+ :filesize,+ :human_filesize,+ ),+ )+ end++ def self.validate_source!(arguments)+ sources = [arguments["image_data"].present?, arguments["url"].present?].count(true)+ if sources != 1 || (arguments["image_data"].present? && arguments["filename"].blank?)+ raise ToolError, I18n.t("mcp.errors.invalid_upload_source")+ end+ return if arguments["url"].blank?++ uri = URI.parse(arguments["url"])+ unless uri.is_a?(URI::HTTP) && uri.host.present? && uri.userinfo.blank?+ raise ToolError, I18n.t("mcp.errors.invalid_upload_url")+ end+ rescue URI::InvalidURIError+ raise ToolError, I18n.t("mcp.errors.invalid_upload_url")+ end+ private_class_method :validate_source!++ def self.validate_avatar!(upload_type, user)+ return if upload_type != "avatar"+ if SiteSetting.discourse_connect_overrides_avatar || SiteSetting.auth_overrides_avatar ||+ !user.in_any_groups?(SiteSetting.uploaded_avatars_allowed_groups_map)+ raise Discourse::InvalidAccess+ end+ end+ private_class_method :validate_avatar!++ def self.uploaded_file(arguments)+ return if arguments["image_data"].blank?++ maximum_size = [+ SiteSetting.max_image_size_kb,+ SiteSetting.max_attachment_size_kb,+ ].max.kilobytes+ encoded = arguments.fetch("image_data")+ if encoded.bytesize > ((maximum_size * 4) / 3) + 4+ raise ToolError, I18n.t("mcp.errors.upload_too_large")+ end+ decoded = Base64.strict_decode64(encoded)+ raise ToolError, I18n.t("mcp.errors.upload_too_large") if decoded.bytesize > maximum_size++ tempfile = Tempfile.new("discourse-mcp-upload")+ tempfile.binmode+ tempfile.write(decoded)+ tempfile.rewind+ ActionDispatch::Http::UploadedFile.new(tempfile:, filename: arguments.fetch("filename"))+ rescue ArgumentError+ raise ToolError, I18n.t("mcp.errors.invalid_upload_data")+ end+ private_class_method :uploaded_file+ end++ class ListPrivateMessages+ MAILBOXES = %w[inbox sent archive unread new].freeze++ def self.call(arguments:, request_context:)+ mailbox = arguments.fetch("mailbox", "inbox")+ page = arguments.fetch("page", 0)+ per_page = arguments.fetch("per_page", 30)+ target = User.find_by_username(arguments["username"] || request_context.user.username)+ guardian = request_context.guardian+ if target.blank? || !guardian.can_see_private_messages?(target.id) ||+ (%w[unread new].include?(mailbox) && target.id != request_context.user_id)+ raise Discourse::InvalidAccess+ end++ group = group_for(arguments["group_name"], mailbox, guardian)+ list = message_list(target, mailbox, group, page, per_page, guardian)+ topics = list.topics+ lookahead_page = (page + 1) * per_page+ has_more = message_list(target, mailbox, group, lookahead_page, 1, guardian).topics.present?+ preload_participants(topics, target)+ archive_state = archive_state(topics, target)+ topic_users =+ TopicUser.where(user_id: target.id, topic_id: topics.map(&:id)).index_by(&:topic_id)++ ToolHelpers.text_and_structured(+ mailbox:,+ username: target.username,+ group_name: group&.name,+ messages:+ topics.map do |topic|+ message_json(+ topic,+ target,+ guardian,+ topic_users[topic.id],+ archive_state.fetch(topic.id, false),+ )+ end,+ meta: {+ page:,+ per_page:,+ has_more:,+ },+ )+ end++ def self.group_for(group_name, mailbox, guardian)+ return if group_name.blank?+ raise ToolError, I18n.t("mcp.errors.group_mailbox_sent") if mailbox == "sent"++ group = Group.find_by("LOWER(name) = ?", group_name.downcase)+ raise ToolError, I18n.t("mcp.errors.group_not_found") if group.blank?+ raise Discourse::InvalidAccess if !guardian.can_see_group_messages?(group)+ group+ end+ private_class_method :group_for++ def self.message_list(target, mailbox, group, page, per_page, guardian)+ query = TopicQuery.new(target, page:, per_page:, group_name: group&.name, guardian:)+ method_name = "list_private_messages"+ method_name += "_group" if group+ method_name += "_#{mailbox}" if mailbox != "inbox"+ query.public_send(method_name, target)+ end+ private_class_method :message_list++ def self.preload_participants(topics, target)+ user_ids = topics.flat_map(&:allowed_user_ids)+ user_lookup = UserLookup.new(user_ids)+ topics.each do |topic|+ topic.participants = topic.participants_summary(user: target, user_lookup:)+ end+ end+ private_class_method :preload_participants++ def self.archive_state(topics, target)+ topic_ids = topics.map(&:id)+ user_archived_ids =+ UserArchivedMessage.where(user_id: target.id, topic_id: topic_ids).pluck(:topic_id).to_set+ group_ids = topics.flat_map(&:allowed_group_ids).uniq+ member_group_ids = GroupUser.where(user_id: target.id, group_id: group_ids).pluck(:group_id)+ archived_pairs =+ GroupArchivedMessage+ .where(topic_id: topic_ids, group_id: member_group_ids)+ .pluck(:topic_id, :group_id)+ .to_set++ topics.to_h do |topic|+ topic_group_ids = topic.allowed_group_ids & member_group_ids+ all_groups_archived =+ topic_group_ids.present? &&+ topic_group_ids.all? { |group_id| archived_pairs.include?([topic.id, group_id]) }+ [topic.id, user_archived_ids.include?(topic.id) || all_groups_archived]+ end+ end+ private_class_method :archive_state++ def self.message_json(topic, target, guardian, topic_user, message_archived)+ seen =+ topic_user&.last_read_post_number.present? || topic.dismissed ||+ topic.created_at < target.user_option.treat_as_new_topic_start_date+ {+ topic_id: topic.id,+ slug: topic.slug,+ title: topic.title,+ posts_count: topic.posts_count,+ reply_count: topic.reply_count,+ created_at: topic.created_at.iso8601,+ last_posted_at: topic.last_posted_at&.iso8601,+ bumped_at: topic.bumped_at&.iso8601,+ last_read_post_number: topic_user&.last_read_post_number,+ unread_posts: topic_user ? Unread.new(topic, topic_user, guardian).unread_posts : 0,+ unseen: !seen,+ topic_archived: topic.archived,+ message_archived:,+ notification_level: topic_user&.notification_level,+ recent_participants:+ Array(topic.participants).map do |poster|+ {+ user_id: poster.user&.id,+ username: poster.user&.username,+ name: SiteSetting.enable_names? ? poster.user&.name : nil,+ }+ end,+ }+ end+ private_class_method :message_json+ end++ class ReadPrivateMessage+ def self.call(arguments:, request_context:)+ topic = private_message_topic!(arguments.fetch("topic_id"), request_context.guardian)+ start_post_number = arguments.fetch("start_post_number", 1)+ post_limit = arguments.fetch("post_limit", 5)+ posts =+ Post+ .secured(request_context.guardian)+ .where(topic_id: topic.id, post_number: start_post_number..)+ .order(:post_number)+ .includes(:topic, :user)+ .limit(post_limit + 1)+ .to_a+ has_more = posts.length > post_limit+ posts = posts.first(post_limit)+ topic_user = TopicUser.find_by(topic:, user: request_context.user)++ ToolHelpers.text_and_structured(+ topic_id: topic.id,+ slug: topic.slug,+ title: topic.title,+ archetype: topic.archetype,+ subtype: topic.subtype,+ posts_count: topic.posts_count,+ last_read_post_number: topic_user&.last_read_post_number,+ topic_archived: topic.archived,+ message_archived: topic.message_archived?(request_context.user),+ allowed_users: topic.allowed_users.map { |user| user_json(user) },+ allowed_groups: topic.allowed_groups.map { |group| group_json(group) },+ posts: posts.map { |post| ToolHelpers.evidence_post_json(post, include_raw: true) },+ meta: {+ start_post: start_post_number,+ returned: posts.length,+ has_more:,+ },+ )+ end++ def self.private_message_topic!(topic_id, guardian)+ topic = Topic.includes(:allowed_users, :allowed_groups).find_by(id: topic_id)+ if topic.blank? || !topic.private_message? || !guardian.can_see?(topic)+ raise ToolError, I18n.t("mcp.errors.private_message_not_found")+ end+ topic+ end++ def self.user_json(user)+ { id: user.id, username: user.username, name: SiteSetting.enable_names? ? user.name : nil }+ end++ def self.group_json(group)+ { id: group.id, name: group.name, full_name: group.full_name }+ end+ end++ class CreatePrivateMessage+ def self.call(arguments:, request_context:)+ ToolHelpers.ensure_current_author!(arguments, request_context.user)+ usernames = Array(arguments["usernames"])+ group_names = Array(arguments["group_names"])+ emails = Array(arguments["email_addresses"])+ if usernames.empty? && group_names.empty? && emails.empty?+ raise ToolError, I18n.t("mcp.errors.private_message_recipient_required")+ end+ ensure_recipient_limit!(request_context.user, usernames, group_names, emails)++ options = {+ title: arguments.fetch("title"),+ raw: arguments.fetch("raw"),+ archetype: Archetype.private_message,+ }+ options[:target_usernames] = usernames.uniq.join(",") if usernames.present?+ options[:target_group_names] = group_names.uniq.join(",") if group_names.present?+ options[:target_emails] = emails.uniq.join(",") if emails.present?+ post = PostCreator.create!(request_context.user, options)+ ToolHelpers.text_and_structured(+ id: post.id,+ topic_id: post.topic_id,+ post_number: post.post_number,+ slug: post.topic.slug,+ title: post.topic.title,+ )+ end++ def self.ensure_recipient_limit!(user, usernames, group_names, emails)+ return if user.staff?++ recipient_count =+ [usernames, group_names, emails].sum do |recipients|+ recipients.uniq { |recipient| recipient.downcase }.length+ end+ return if recipient_count <= SiteSetting.max_allowed_message_recipients++ raise ToolError,+ I18n.t(+ :max_pm_recipients,+ recipients_limit: SiteSetting.max_allowed_message_recipients,+ )+ end+ private_class_method :ensure_recipient_limit!+ end++ class ReplyPrivateMessage+ def self.call(arguments:, request_context:)+ ToolHelpers.ensure_current_author!(arguments, request_context.user)+ topic =+ ReadPrivateMessage.private_message_topic!(+ arguments.fetch("topic_id"),+ request_context.guardian,+ )+ post =+ PostCreator.create!(+ request_context.user,+ topic_id: topic.id,+ raw: arguments.fetch("raw"),+ reply_to_post_number: arguments["reply_to_post_number"],+ )+ ToolHelpers.text_and_structured(+ id: post.id,+ topic_id: post.topic_id,+ post_number: post.post_number,+ reply_to_post_number: post.reply_to_post_number,+ slug: topic.slug,+ )+ end+ end++ class InviteToPrivateMessage+ def self.call(arguments:, request_context:)+ ToolHelpers.ensure_current_author!(arguments, request_context.user)+ topic =+ ReadPrivateMessage.private_message_topic!(+ arguments.fetch("topic_id"),+ request_context.guardian,+ )+ recipients = arguments.values_at("username", "group_name", "email_address").compact_blank+ if recipients.length != 1+ raise ToolError, I18n.t("mcp.errors.private_message_single_recipient")+ end+ if arguments.key?("notify_group_members") && arguments["group_name"].blank?+ raise ToolError, I18n.t("mcp.errors.private_message_group_notification")+ end+ if arguments["custom_message"].present? && arguments["email_address"].blank?+ raise ToolError, I18n.t("mcp.errors.private_message_email_message")+ end+ ensure_recipient_slot!(topic, request_context.guardian)++ if arguments["group_name"].present?+ invite_group!(topic, arguments, request_context)+ elsif arguments["username"].present?+ invite_user!(topic, arguments.fetch("username"), request_context)+ else+ invite_email!(topic, arguments, request_context)+ end+ end++ def self.invite_group!(topic, arguments, request_context)+ group = Group.find_by(name: arguments.fetch("group_name"))+ raise ToolError, I18n.t("mcp.errors.group_not_found") if group.blank?+ request_context.guardian.ensure_can_invite_group_to_private_message!(group, topic)++ notifications_requested = arguments.fetch("notify_group_members", true)+ topic.invite_group(request_context.user, group, should_notify: notifications_requested)+ ToolHelpers.text_and_structured(+ topic_id: topic.id,+ recipient_type: "group",+ status: "added",+ group: ReadPrivateMessage.group_json(group),+ notifications_requested:,+ )+ end+ private_class_method :invite_group!++ def self.ensure_recipient_slot!(topic, guardian)+ return if guardian.is_staff? || !topic.reached_recipients_limit?++ raise ToolError,+ I18n.t(+ "pm_reached_recipients_limit",+ recipients_limit: SiteSetting.max_allowed_message_recipients,+ )+ end+ private_class_method :ensure_recipient_slot!++ def self.invite_user!(topic, username, request_context)+ user = User.find_by_username(username)+ raise ToolError, I18n.t("mcp.errors.user_not_found") if user.blank?+ raise Discourse::InvalidAccess if !request_context.guardian.can_invite_to?(topic)++ added = topic.invite(request_context.user, user.username)+ raise ToolError, I18n.t("mcp.errors.private_message_invite_failed") if !added+ ToolHelpers.text_and_structured(+ topic_id: topic.id,+ recipient_type: "user",+ status: "added",+ user: ReadPrivateMessage.user_json(user),+ )+ end+ private_class_method :invite_user!++ def self.invite_email!(topic, arguments, request_context)+ raise Discourse::InvalidAccess if !request_context.guardian.can_invite_via_email?(topic)++ added =+ topic.invite(+ request_context.user,+ arguments.fetch("email_address"),+ nil,+ arguments["custom_message"],+ )+ raise ToolError, I18n.t("mcp.errors.private_message_invite_failed") if !added+ ToolHelpers.text_and_structured(+ topic_id: topic.id,+ recipient_type: "email",+ status: "submitted",+ participant_added: false,+ outcome_confirmed: false,+ )+ end+ private_class_method :invite_email!+ end+class SetPostDeleteddef self.call(arguments:, request_context:)post = Post.find_by(id: arguments.fetch("post_id").to_i, user_id: request_context.user_id)@@ -276,6 +1825,103 @@ module DiscourseMcpendend+ class GetDraft+ def self.call(arguments:, request_context:)+ user = request_context.user or raise Discourse::InvalidAccess+ draft_key = arguments.fetch("draft_key")+ sequence =+ if arguments.key?("sequence")+ arguments.fetch("sequence")+ else+ DraftSequence.current(user, draft_key)+ end+ draft = Draft.get(user, draft_key, sequence)++ return ToolHelpers.text_and_structured(draft_key:, found: false) if draft.blank?++ parsed = JSON.parse(draft)+ parsed = {} if !parsed.is_a?(Hash)+ ToolHelpers.text_and_structured(+ draft_key:,+ sequence:,+ found: true,+ data: {+ title: parsed["title"],+ reply: parsed["reply"],+ category_id: parsed["categoryId"],+ tags: parsed["tags"].is_a?(Array) ? parsed["tags"] : [],+ action: parsed["action"],+ },+ )+ rescue Draft::OutOfSequence+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.draft_sequence_conflict")+ rescue JSON::ParserError+ ToolHelpers.text_and_structured(+ draft_key:,+ sequence:,+ found: true,+ data: {+ title: nil,+ reply: nil,+ category_id: nil,+ tags: [],+ action: nil,+ },+ )+ end+ end++ class SaveDraft+ def self.call(arguments:, request_context:)+ user = request_context.user or raise Discourse::InvalidAccess+ draft_key = arguments.fetch("draft_key")++ if !Draft.exists?(user_id: user.id, draft_key:) &&+ Draft.where(user_id: user.id).count >= SiteSetting.max_drafts_per_user+ raise DiscourseMcp::ToolError, I18n.t("draft.too_many_drafts.title")+ end++ data = { reply: arguments.fetch("reply") }+ action = arguments["action"] || default_action(draft_key)+ data[:action] = action if action.present?+ data[:title] = arguments["title"] if arguments.key?("title")+ data[:categoryId] = arguments["category_id"] if arguments.key?("category_id")+ data[:tags] = arguments["tags"] if arguments["tags"].present?++ if (match = draft_key.match(/\Atopic_(\d+)\z/))+ data[:topic_id] = match[1].to_i+ end++ serialized_data = data.to_json+ if serialized_data.length > SiteSetting.max_draft_length+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.draft_too_long")+ end++ sequence = Draft.set(user, draft_key, arguments.fetch("sequence", 0), serialized_data)+ ToolHelpers.text_and_structured(draft_key:, sequence:, saved: true)+ rescue Draft::OutOfSequence+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.draft_sequence_conflict")+ end++ def self.default_action(draft_key)+ return "createTopic" if draft_key == Draft::NEW_TOPIC+ return "privateMessage" if draft_key == Draft::NEW_PRIVATE_MESSAGE+ "reply" if draft_key.match?(/\Atopic_\d+\z/)+ end+ private_class_method :default_action+ end++ class DeleteDraft+ def self.call(arguments:, request_context:)+ user = request_context.user or raise Discourse::InvalidAccess+ draft_key = arguments.fetch("draft_key")+ Draft.clear(user, draft_key, arguments.fetch("sequence"))+ ToolHelpers.text_and_structured(draft_key:, deleted: true)+ rescue Draft::OutOfSequence+ raise DiscourseMcp::ToolError, I18n.t("mcp.errors.draft_sequence_conflict")+ end+ end+class SetUserStatusdef self.call(arguments:, request_context:)user = request_context.user or raise Discourse::InvalidAccessdiff --git a/plugins/chat/lib/chat/mcp_tools.rb b/plugins/chat/lib/chat/mcp_tools.rbindex 04d60587e90..e2084e55b0b 100644--- a/plugins/chat/lib/chat/mcp_tools.rb+++ b/plugins/chat/lib/chat/mcp_tools.rb@@ -26,7 +26,10 @@ module ChatChat::ListChannelMessages.call(params: {channel_id: arguments.fetch("channel_id"),- page_size: arguments.fetch("limit", 50),+ page_size: arguments.fetch("page_size", 50),+ target_message_id: arguments["target_message_id"],+ direction: arguments["direction"],+ target_date: arguments["target_date"],},guardian: request_context.guardian,)@@ -40,10 +43,22 @@ module Chatusername: message.user&.username,message: message.message,created_at: message.created_at.iso8601,+ edited: message.revisions.any?,thread_id: message.thread_id,+ in_reply_to_id: message.in_reply_to_id,}end- DiscourseMcp::ToolHelpers.text_and_structured(messages: messages)+ metadata = result.metadata || {}+ DiscourseMcp::ToolHelpers.text_and_structured(+ channel_id: arguments.fetch("channel_id"),+ messages:,+ meta: {+ returned: messages.length,+ can_load_more_past: metadata[:can_load_more_past],+ can_load_more_future: metadata[:can_load_more_future],+ target_message_id: metadata[:target_message_id] || arguments["target_message_id"],+ },+ )endenddiff --git a/plugins/chat/plugin.rb b/plugins/chat/plugin.rbindex 4e20149c93f..a529093629d 100644--- a/plugins/chat/plugin.rb+++ b/plugins/chat/plugin.rb@@ -664,8 +664,8 @@ after_initialize doavailability: -> { SiteSetting.chat_enabled },)register_mcp_tool(- "chat_message_list",- title: "List chat messages",+ "discourse_get_chat_messages",+ title: "Get chat messages",description: "Reads a bounded page of messages from a visible chat channel.",implementation: Chat::McpTools::ListMessages,input_schema: {@@ -675,10 +675,23 @@ after_initialize dotype: "integer",minimum: 1,},- limit: {+ page_size: {type: "integer",minimum: 1,- maximum: 100,+ maximum: 50,+ default: 50,+ },+ target_message_id: {+ type: "integer",+ minimum: 1,+ },+ direction: {+ type: "string",+ enum: %w[past future],+ },+ target_date: {+ type: "string",+ format: "date-time",},},required: ["channel_id"],diff --git a/plugins/chat/spec/lib/chat/mcp_tools_spec.rb b/plugins/chat/spec/lib/chat/mcp_tools_spec.rbnew file mode 100644index 00000000000..60dfb1c92b6--- /dev/null+++ b/plugins/chat/spec/lib/chat/mcp_tools_spec.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++describe Chat::McpTools::ListMessages do+ fab!(:user)+ fab!(:channel, :chat_channel)+ fab!(:first_message) do+ Fabricate(:chat_message, chat_channel: channel, user:, message: "First message")+ end+ fab!(:second_message) do+ Fabricate(:chat_message, chat_channel: channel, user:, message: "Second message")+ end++ let(:request_context) do+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ end++ before do+ SiteSetting.chat_allowed_groups = Group::AUTO_GROUPS[:everyone]+ channel.add(user)+ end++ it "returns the compatible bounded chat message contract" do+ result =+ described_class.call(+ arguments: {+ "channel_id" => channel.id,+ "page_size" => 1,+ "target_message_id" => second_message.id,+ "direction" => "past",+ },+ request_context:,+ ).fetch(:structuredContent)++ expect(result[:channel_id]).to eq(channel.id)+ expect(result[:messages].sole).to include(+ id: first_message.id,+ message: "First message",+ edited: false,+ in_reply_to_id: nil,+ )+ expect(result[:meta]).to include(+ returned: 1,+ can_load_more_past: true,+ can_load_more_future: nil,+ target_message_id: second_message.id,+ )+ end++ it "does not expose a channel the user cannot view" do+ private_channel = Fabricate(:private_category_channel)++ expect do+ described_class.call(arguments: { "channel_id" => private_channel.id }, request_context:)+ end.to raise_error(DiscourseMcp::ToolError)+ end+enddiff --git a/spec/lib/discourse_mcp/core_tools_spec.rb b/spec/lib/discourse_mcp/core_tools_spec.rbindex da0b1a2f192..d6b58a16abc 100644--- a/spec/lib/discourse_mcp/core_tools_spec.rb+++ b/spec/lib/discourse_mcp/core_tools_spec.rb@@ -10,6 +10,1295 @@ describe DiscourseMcp::Tools::GetUser doresult = described_class.call(arguments: { "username" => user.username }, request_context:)- expect(result.dig(:structuredContent, :user)).not_to have_key(:name)+ expect(result.dig(:structuredContent, :name)).to be_nil+ end+end++describe DiscourseMcp::Tools::FilterTopics do+ fab!(:viewer, :user)+ fab!(:member, :user)+ fab!(:moderator)+ fab!(:admin)+ fab!(:group)+ fab!(:private_category) { Fabricate(:private_category, group:) }+ fab!(:public_topic, :topic)+ fab!(:private_topic) { Fabricate(:topic, category: private_category) }++ before { group.add(member) }++ it "filters topics using each caller's category access" do+ query = "topic:#{public_topic.id},#{private_topic.id}"++ expectations = {+ viewer => [public_topic.id],+ moderator => [public_topic.id],+ member => [public_topic.id, private_topic.id],+ admin => [public_topic.id, private_topic.id],+ }++ expectations.each do |user, expected_ids|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ result =+ described_class.call(+ arguments: {+ "filter" => query,+ "view" => "filtered",+ },+ request_context:,+ )++ expect(result.dig(:structuredContent, :results).pluck(:id)).to eq(expected_ids)+ end+ end++ it "honors the setting that removes automatic admin access to secured categories" do+ SiteSetting.suppress_secured_categories_from_admin = true+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: admin, guardian: admin.guardian)++ result =+ described_class.call(+ arguments: {+ "filter" => "topic:#{public_topic.id},#{private_topic.id}",+ "view" => "filtered",+ },+ request_context:,+ )++ expect(result.dig(:structuredContent, :results).pluck(:id)).to eq([public_topic.id])+ end++ it "returns truthful pagination and the requested top view" do+ TopTopic.create!(topic: public_topic, weekly_score: 2, daily_score: 1)+ second_topic = Fabricate(:topic)+ TopTopic.create!(topic: second_topic, weekly_score: 1, daily_score: 2)+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ first_page =+ described_class.call(+ arguments: {+ "view" => "top",+ "top_period" => "weekly",+ "page" => 0,+ "per_page" => 1,+ },+ request_context:,+ ).fetch(:structuredContent)+ second_page =+ described_class.call(+ arguments: {+ "view" => "top",+ "top_period" => "weekly",+ "page" => 1,+ "per_page" => 1,+ },+ request_context:,+ ).fetch(:structuredContent)+ hot =+ described_class.call(+ arguments: {+ "view" => "hot",+ "page" => 0,+ "per_page" => 1,+ },+ request_context:,+ ).fetch(:structuredContent)++ expect(first_page[:results].sole[:id]).to eq(public_topic.id)+ expect(first_page[:meta]).to eq(+ view: "top",+ top_period: "weekly",+ page: 0,+ per_page: 1,+ returned: 1,+ has_more: true,+ )+ expect(second_page[:results].sole[:id]).to eq(second_topic.id)+ expect(second_page[:meta]).to include(page: 1, returned: 1, has_more: false)+ expect(hot[:results].sole[:id]).to eq(second_topic.id)+ expect(hot[:meta][:top_period]).to eq("daily")+ end++ it "rejects options that do not belong to the selected view" do+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ expect do+ described_class.call(arguments: { "view" => "filtered" }, request_context:)+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.filter_required"))++ expect do+ described_class.call(+ arguments: {+ "view" => "hot",+ "filter" => "status:open",+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.filter_only_for_filtered_view"))+ end+end++describe DiscourseMcp::Tools::SearchPosts do+ fab!(:viewer, :user)+ fab!(:member, :user)+ fab!(:moderator)+ fab!(:admin)+ fab!(:group)+ fab!(:private_category) { Fabricate(:private_category, group:) }+ fab!(:public_post) { Fabricate(:post, raw: "parityneedle public evidence") }+ fab!(:private_topic) { Fabricate(:topic, category: private_category) }+ fab!(:private_post) do+ Fabricate(:post, topic: private_topic, raw: "parityneedle private evidence")+ end++ before do+ group.add(member)+ SearchIndexer.enable+ [public_post, private_post].each { |post| SearchIndexer.index(post, force: true) }+ end++ after { SearchIndexer.disable }++ it "returns matched post evidence using each caller's category access" do+ expectations = {+ viewer => [public_post.id],+ moderator => [public_post.id],+ member => [public_post.id, private_post.id],+ admin => [public_post.id, private_post.id],+ }++ expectations.each do |user, expected_ids|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ result =+ described_class.call(+ arguments: {+ "query" => "parityneedle",+ "page" => 1,+ },+ request_context:,+ ).fetch(:structuredContent)++ expect(result[:posts].pluck(:id)).to contain_exactly(*expected_ids)+ expect(result[:posts].pluck(:excerpt).join).to include("parityneedle")+ expect(result[:meta]).to include(page: 1, returned: expected_ids.length, exhaustive: false)+ end+ end++ it "honors the setting that removes automatic admin access to secured categories" do+ SiteSetting.suppress_secured_categories_from_admin = true+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: admin, guardian: admin.guardian)++ result =+ described_class.call(arguments: { "query" => "parityneedle", "page" => 1 }, request_context:)++ expect(result.dig(:structuredContent, :posts).pluck(:id)).to eq([public_post.id])+ end++ it "reports truthful bounded continuation" do+ SiteSetting.search_page_size = 1+ second_post = Fabricate(:post, raw: "paginationneedle second evidence")+ first_post = Fabricate(:post, raw: "paginationneedle first evidence")+ [first_post, second_post].each { |post| SearchIndexer.index(post, force: true) }+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ first_page =+ described_class.call(+ arguments: {+ "query" => "paginationneedle order:latest",+ "page" => 1,+ },+ request_context:,+ ).fetch(:structuredContent)+ second_page =+ described_class.call(+ arguments: {+ "query" => "paginationneedle order:latest",+ "page" => 2,+ },+ request_context:,+ ).fetch(:structuredContent)++ expect(first_page[:posts].sole[:id]).to eq(first_post.id)+ expect(first_page[:meta]).to include(page: 1, returned: 1, has_more: true)+ expect(second_page[:posts].sole[:id]).to eq(second_post.id)+ expect(second_page[:meta]).to include(page: 2, returned: 1, has_more: false)+ end++ it "searches private messages only for participants" do+ author = Fabricate(:user)+ message =+ Fabricate(+ :private_message_post,+ user: author,+ recipient: member,+ raw: "privatesearchneedle evidence",+ )+ SearchIndexer.index(message, force: true)++ expectations = {+ viewer => [],+ moderator => [],+ member => [message.id],+ author => [message.id],+ admin => [],+ }++ expectations.each do |user, expected_ids|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ result =+ described_class.call(+ arguments: {+ "query" => "in:messages privatesearchneedle",+ },+ request_context:,+ )++ expect(result.dig(:structuredContent, :posts).pluck(:id)).to eq(expected_ids)+ end+ end++ it "rejects a search term that Discourse cannot execute" do+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ expect do+ described_class.call(arguments: { "query" => "x" }, request_context:)+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.invalid_search_query"))+ end+end++describe DiscourseMcp::Tools::ReadTopicPosts do+ fab!(:viewer, :user)+ fab!(:member, :user)+ fab!(:moderator)+ fab!(:admin)+ fab!(:author, :user)+ fab!(:group)+ fab!(:private_category) { Fabricate(:private_category, group:) }+ fab!(:private_topic) { Fabricate(:topic, category: private_category, user: author) }+ fab!(:private_post) do+ Fabricate(:post, topic: private_topic, user: author, raw: "restricted evidence")+ end++ before { group.add(member) }++ it "reads a secured topic only for callers with category access" do+ expectations = { viewer => false, moderator => false, member => true, admin => true }++ expectations.each do |user, allowed|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ operation =+ lambda do+ described_class.call(+ arguments: {+ "topic_id" => private_post.topic_id,+ "selection_mode" => "earliest",+ },+ request_context:,+ )+ end++ if allowed+ expect(operation.call.dig(:structuredContent, :posts).sole[:raw]).to eq(private_post.raw)+ else+ expect(&operation).to raise_error(DiscourseMcp::ToolError)+ end+ end+ end++ it "honors the setting that removes automatic admin access to secured categories" do+ SiteSetting.suppress_secured_categories_from_admin = true+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: admin, guardian: admin.guardian)++ expect do+ described_class.call(+ arguments: {+ "topic_id" => private_post.topic_id,+ "selection_mode" => "earliest",+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError)+ end++ it "reads a private message only for participants and admins" do+ message = Fabricate(:private_message_post, user: author, recipient: member)+ expectations = { viewer => false, moderator => false, member => true, admin => true }++ expectations.each do |user, allowed|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ operation =+ lambda do+ described_class.call(+ arguments: {+ "topic_id" => message.topic_id,+ "selection_mode" => "post_ids",+ "post_ids" => [message.id],+ },+ request_context:,+ )+ end++ if allowed+ expect(operation.call.dig(:structuredContent, :posts).sole[:raw]).to eq(message.raw)+ else+ expect(&operation).to raise_error(DiscourseMcp::ToolError)+ end+ end+ end++ it "reads a deleted topic only for staff who may see deleted topics" do+ deleted_post = Fabricate(:post, user: author, raw: "deleted topic evidence")+ deleted_post.topic.update!(deleted_at: 1.minute.ago)+ expectations = { viewer => false, moderator => true, admin => true }++ expectations.each do |user, allowed|+ aggregate_failures(user.username) do+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ operation =+ lambda do+ described_class.call(+ arguments: {+ "topic_id" => deleted_post.topic_id,+ "selection_mode" => "post_ids",+ "post_ids" => [deleted_post.id],+ },+ request_context:,+ )+ end++ if allowed+ posts = operation.call.dig(:structuredContent, :posts)+ expect(posts.length).to eq(1), user.username+ expect(posts.first[:raw]).to eq(deleted_post.raw)+ else+ expect(&operation).to raise_error(DiscourseMcp::ToolError)+ end+ end+ end+ end++ it "supports bounded selection modes without exposing hidden or staff-only posts" do+ SiteSetting.whispers_allowed_groups = Group::AUTO_GROUPS[:staff].to_s+ first_post = Fabricate(:post, user: author, raw: "first evidence")+ topic = first_post.topic+ second_post = Fabricate(:post, topic:, user: viewer, raw: "second evidence")+ hidden_post = Fabricate(:post, topic:, user: author, raw: "hidden evidence", hidden: true)+ whisper =+ Fabricate(+ :post,+ topic:,+ user: moderator,+ raw: "staff evidence",+ post_type: Post.types[:whisper],+ )+ last_post = Fabricate(:post, topic:, user: author, raw: "last evidence")+ deleted_post = Fabricate(:post, topic:, user: author, raw: "deleted evidence")+ deleted_post.trash!(admin)+ viewer_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)+ moderator_context =+ instance_double(DiscourseMcp::RequestContext, user: moderator, guardian: moderator.guardian)++ earliest =+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "selection_mode" => "earliest",+ "limit" => 2,+ },+ request_context: viewer_context,+ ).fetch(:structuredContent)+ latest =+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "selection_mode" => "latest",+ "limit" => 2,+ },+ request_context: viewer_context,+ ).fetch(:structuredContent)+ exact =+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "selection_mode" => "post_ids",+ "post_ids" => [last_post.id, hidden_post.id, second_post.id],+ },+ request_context: viewer_context,+ ).fetch(:structuredContent)+ by_username =+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "selection_mode" => "usernames",+ "usernames" => [author.username],+ "replies_only" => true,+ },+ request_context: viewer_context,+ ).fetch(:structuredContent)+ around =+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "selection_mode" => "around_post",+ "post_number" => second_post.post_number,+ "limit" => 2,+ },+ request_context: viewer_context,+ ).fetch(:structuredContent)+ staff =+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "selection_mode" => "post_ids",+ "post_ids" => [hidden_post.id, whisper.id, deleted_post.id],+ },+ request_context: moderator_context,+ ).fetch(:structuredContent)++ expect(earliest[:posts].pluck(:id)).to eq([first_post.id, second_post.id])+ expect(latest[:posts].pluck(:id)).to eq([second_post.id, last_post.id])+ expect(exact[:posts].pluck(:id)).to eq([last_post.id, second_post.id])+ expect(by_username[:posts].pluck(:id)).to eq([last_post.id])+ expect(around[:posts].pluck(:id)).to eq([first_post.id, second_post.id])+ expect(staff[:posts].pluck(:id)).to eq([hidden_post.id, whisper.id, deleted_post.id])+ expect(earliest[:meta]).to include(+ visible_stream_size: 3,+ selected: 2,+ returned: 2,+ exhaustive: false,+ )+ end++ it "rejects options from another selection mode" do+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ expect do+ described_class.call(+ arguments: {+ "topic_id" => private_post.topic_id,+ "selection_mode" => "post_ids",+ "post_ids" => [private_post.id],+ "replies_only" => false,+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.invalid_post_selection"))+ end+end++describe DiscourseMcp::Tools::GetPostReplies do+ fab!(:viewer, :user)+ fab!(:member, :user)+ fab!(:moderator)+ fab!(:admin)+ fab!(:author, :user)+ fab!(:group)+ fab!(:private_category) { Fabricate(:private_category, group:) }+ fab!(:private_topic) { Fabricate(:topic, category: private_category, user: author) }+ fab!(:private_post) { Fabricate(:post, topic: private_topic, user: author) }++ before { group.add(member) }++ it "reads reply relationships only when the root post is visible" do+ reply = Fabricate(:post, topic: private_topic, user: author)+ PostReply.create!(post: private_post, reply:)+ expectations = { viewer => false, moderator => false, member => true, admin => true }++ expectations.each do |user, allowed|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ operation =+ lambda do+ described_class.call(+ arguments: {+ "post_id" => private_post.id,+ "mode" => "reply_ids",+ },+ request_context:,+ )+ end++ if allowed+ expect(operation.call.dig(:structuredContent, :replies)).to eq([{ id: reply.id, level: 1 }])+ else+ expect(&operation).to raise_error(DiscourseMcp::ToolError)+ end+ end+ end++ it "honors the setting that removes automatic admin access to secured categories" do+ SiteSetting.suppress_secured_categories_from_admin = true+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: admin, guardian: admin.guardian)++ expect do+ described_class.call(+ arguments: {+ "post_id" => private_post.id,+ "mode" => "direct_replies",+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError)+ end++ it "reads private-message reply relationships only for participants and admins" do+ message = Fabricate(:private_message_post, user: author, recipient: member)+ reply = Fabricate(:post, topic: message.topic, user: member)+ PostReply.create!(post: message, reply:)+ expectations = { viewer => false, moderator => false, member => true, admin => true }++ expectations.each do |user, allowed|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ operation =+ lambda do+ described_class.call(+ arguments: {+ "post_id" => message.id,+ "mode" => "direct_replies",+ },+ request_context:,+ )+ end++ if allowed+ expect(operation.call.dig(:structuredContent, :posts).pluck(:id)).to eq([reply.id])+ else+ expect(&operation).to raise_error(DiscourseMcp::ToolError)+ end+ end+ end++ it "returns bounded direct replies and reply history without exposing hidden posts" do+ SiteSetting.whispers_allowed_groups = Group::AUTO_GROUPS[:staff].to_s+ root = Fabricate(:post, user: author)+ direct_reply =+ Fabricate(:post, topic: root.topic, user: viewer, reply_to_post_number: root.post_number)+ hidden_reply = Fabricate(:post, topic: root.topic, user: author, hidden: true)+ whisper = Fabricate(:post, topic: root.topic, user: moderator, post_type: Post.types[:whisper])+ deleted_reply = Fabricate(:post, topic: root.topic, user: author)+ deleted_reply.trash!(admin)+ child_reply =+ Fabricate(+ :post,+ topic: root.topic,+ user: viewer,+ reply_to_post_number: direct_reply.post_number,+ )+ PostReply.create!(post: root, reply: direct_reply)+ PostReply.create!(post: root, reply: hidden_reply)+ PostReply.create!(post: root, reply: whisper)+ PostReply.create!(post: root, reply: deleted_reply)+ PostReply.create!(post: direct_reply, reply: child_reply)+ SiteSetting.max_reply_history = 2+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ ids =+ described_class.call(+ arguments: {+ "post_id" => root.id,+ "mode" => "reply_ids",+ },+ request_context:,+ ).fetch(:structuredContent)+ direct =+ described_class.call(+ arguments: {+ "post_id" => root.id,+ "mode" => "direct_replies",+ "after_post_number" => 0,+ },+ request_context:,+ ).fetch(:structuredContent)+ history =+ described_class.call(+ arguments: {+ "post_id" => child_reply.id,+ "mode" => "reply_history",+ },+ request_context:,+ ).fetch(:structuredContent)+ moderator_context =+ instance_double(DiscourseMcp::RequestContext, user: moderator, guardian: moderator.guardian)+ staff_direct =+ described_class.call(+ arguments: {+ "post_id" => root.id,+ "mode" => "direct_replies",+ },+ request_context: moderator_context,+ ).fetch(:structuredContent)++ expect(ids[:replies]).to eq(+ [{ id: direct_reply.id, level: 1 }, { id: child_reply.id, level: 2 }],+ )+ expect(ids[:meta]).to include(returned: 2, exhaustive: false)+ expect(direct[:posts].pluck(:id)).to eq([direct_reply.id])+ expect(direct[:posts].sole[:raw]).to eq(direct_reply.raw)+ expect(direct[:meta]).to include(returned: 1, page_was_full: false, upstream_limit: 20)+ expect(history[:posts].pluck(:id)).to eq([root.id, direct_reply.id])+ expect(staff_direct[:posts].pluck(:id)).to eq([direct_reply.id, hidden_reply.id, whisper.id])+ expect(staff_direct[:posts].pluck(:id)).not_to include(deleted_reply.id)+ end+end++describe DiscourseMcp::Tools::ListLatestPosts do+ fab!(:viewer, :user)+ fab!(:member, :user)+ fab!(:moderator)+ fab!(:admin)+ fab!(:group)+ fab!(:private_category) { Fabricate(:private_category, group:) }+ fab!(:public_post, :post)+ fab!(:private_post) { Fabricate(:post, topic: Fabricate(:topic, category: private_category)) }++ before { group.add(member) }++ it "returns only public posts visible through the caller's category access" do+ private_message = Fabricate(:private_message_post, user: viewer, recipient: member)+ expectations = {+ viewer => [public_post.id],+ moderator => [public_post.id],+ member => [private_post.id, public_post.id],+ admin => [private_post.id, public_post.id],+ }++ expectations.each do |user, expected_ids|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ result = described_class.call(arguments: {}, request_context:).fetch(:structuredContent)++ expect(result[:posts].pluck(:id)).to eq(expected_ids)+ expect(result[:posts].pluck(:id)).not_to include(private_message.id)+ expect(result[:posts].find { |post| post[:id] == public_post.id }[:excerpt]).to be_present+ end+ end++ it "uses a post ID cursor and applies replies-only after the fixed upstream page" do+ topic = Fabricate(:topic)+ first_post = Fabricate(:post, topic:)+ reply = Fabricate(:post, topic:)+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ result =+ described_class.call(+ arguments: {+ "before_post_id" => reply.id + 1,+ "replies_only" => true,+ },+ request_context:,+ ).fetch(:structuredContent)++ expect(result[:posts].pluck(:id)).to include(reply.id)+ expect(result[:posts].pluck(:id)).not_to include(first_post.id)+ expect(result[:meta]).to include(+ before_post_id: reply.id + 1,+ upstream_page_size: 50,+ replies_only_projection: true,+ next_before_post_id: public_post.id,+ )+ end++ it "honors the setting that removes automatic admin access to secured categories" do+ SiteSetting.suppress_secured_categories_from_admin = true+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: admin, guardian: admin.guardian)++ result = described_class.call(arguments: {}, request_context:).fetch(:structuredContent)++ expect(result[:posts].pluck(:id)).to eq([public_post.id])+ end+end++describe DiscourseMcp::Tools::GetTopicViewStats do+ fab!(:viewer, :user)+ fab!(:member, :user)+ fab!(:moderator)+ fab!(:admin)+ fab!(:group)+ fab!(:private_category) { Fabricate(:private_category, group:) }+ fab!(:topic) { Fabricate(:topic, category: private_category) }++ before { group.add(member) }++ it "returns ascending daily totals only to callers who can see the topic" do+ first = Fabricate(:topic_view_stat, topic:, viewed_at: 2.days.ago, anonymous_views: 2)+ second = Fabricate(:topic_view_stat, topic:, viewed_at: 1.day.ago, logged_in_views: 3)+ expectations = { viewer => false, moderator => false, member => true, admin => true }++ expectations.each do |user, allowed|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ operation =+ lambda { described_class.call(arguments: { "topic_id" => topic.id }, request_context:) }++ if allowed+ result = operation.call.fetch(:structuredContent)+ expect(result[:view_stats]).to eq(+ [+ { viewed_at: first.viewed_at.to_date.iso8601, views: 3 },+ { viewed_at: second.viewed_at.to_date.iso8601, views: 4 },+ ],+ )+ expect(result[:meta]).to include(default_range_days: 30, returned: 2)+ else+ expect(&operation).to raise_error(DiscourseMcp::ToolError)+ end+ end+ end++ it "validates and applies an explicit date range" do+ included = Fabricate(:topic_view_stat, topic:, viewed_at: 3.days.ago)+ Fabricate(:topic_view_stat, topic:, viewed_at: 10.days.ago)+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: member, guardian: member.guardian)++ result =+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "from" => 5.days.ago.to_date.iso8601,+ "to" => Date.current.iso8601,+ },+ request_context:,+ ).fetch(:structuredContent)++ expect(result[:view_stats].sole[:viewed_at]).to eq(included.viewed_at.to_date.iso8601)+ expect(result[:meta][:default_range_days]).to be_nil+ expect do+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "from" => "not-a-date",+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError)+ end++ it "honors the setting that removes automatic admin access to secured categories" do+ SiteSetting.suppress_secured_categories_from_admin = true+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: admin, guardian: admin.guardian)++ expect do+ described_class.call(arguments: { "topic_id" => topic.id }, request_context:)+ end.to raise_error(DiscourseMcp::ToolError)+ end++ it "returns private-message stats only to participants and admins" do+ author = Fabricate(:user)+ message = Fabricate(:private_message_post, user: author, recipient: member)+ Fabricate(:topic_view_stat, topic: message.topic)+ expectations = { viewer => false, moderator => false, member => true, admin => true }++ expectations.each do |user, allowed|+ request_context =+ instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)+ operation =+ lambda do+ described_class.call(arguments: { "topic_id" => message.topic_id }, request_context:)+ end++ if allowed+ expect(operation.call.dig(:structuredContent, :view_stats).length).to eq(1)+ else+ expect(&operation).to raise_error(DiscourseMcp::ToolError)+ end+ end+ end+end++describe DiscourseMcp::Tools::ListDirectoryItems do+ fab!(:viewer, :user)+ fab!(:member, :user)+ fab!(:target, :user)+ fab!(:group) do+ Fabricate(+ :group,+ members_visibility_level: Group.visibility_levels[:members],+ users: [member, target],+ )+ end++ before do+ DirectoryItem.create!(+ period_type: DirectoryItem.period_types[:all],+ user: target,+ likes_received: 7,+ likes_given: 6,+ topics_entered: 5,+ days_visited: 4,+ posts_read: 3,+ topic_count: 2,+ post_count: 1,+ )+ end++ it "returns bounded directory metrics and truthful continuation" do+ target.user_stat.update!(time_read: 120)+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ result =+ described_class.call(+ arguments: {+ "period" => "all",+ "username" => target.username,+ "limit" => 1,+ },+ request_context:,+ ).fetch(:structuredContent)++ expect(result[:directory_items].sole).to include(+ id: target.id,+ likes_received: 7,+ post_count: 1,+ time_read: 120,+ )+ expect(result.dig(:directory_items, 0, :user, :username)).to eq(target.username)+ expect(result[:meta]).to include(page: 0, limit: 1, returned: 1, total: 1, has_more: false)+ end++ it "orders by a public user field and reports the next page" do+ other_user = Fabricate(:user)+ DirectoryItem.create!(+ period_type: DirectoryItem.period_types[:all],+ user: other_user,+ likes_received: 0,+ likes_given: 0,+ topics_entered: 0,+ days_visited: 0,+ posts_read: 0,+ topic_count: 0,+ post_count: 0,+ )+ user_field = Fabricate(:user_field, name: "rank_field", show_on_profile: true)+ UserCustomField.create!(+ user: target,+ name: "#{User::USER_FIELD_PREFIX}#{user_field.id}",+ value: "zulu",+ )+ UserCustomField.create!(+ user: other_user,+ name: "#{User::USER_FIELD_PREFIX}#{user_field.id}",+ value: "alpha",+ )+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ result =+ described_class.call(+ arguments: {+ "period" => "all",+ "order" => user_field.name,+ "ascending" => true,+ "limit" => 1,+ },+ request_context:,+ ).fetch(:structuredContent)++ expect(result[:directory_items].sole[:id]).to eq(other_user.id)+ expect(result[:meta]).to include(total: 2, has_more: true, next_page: 1)+ end++ it "requires access to a requested group's membership list" do+ denied_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)+ allowed_context =+ instance_double(DiscourseMcp::RequestContext, user: member, guardian: member.guardian)++ expect do+ described_class.call(+ arguments: {+ "period" => "all",+ "group" => group.name,+ },+ request_context: denied_context,+ )+ end.to raise_error(DiscourseMcp::ToolError)++ result =+ described_class.call(+ arguments: {+ "period" => "all",+ "group" => group.name,+ },+ request_context: allowed_context,+ )+ expect(result.dig(:structuredContent, :directory_items).pluck(:id)).to eq([target.id])+ end++ it "ignores exclusions for groups whose membership is not visible to the caller" do+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ result =+ described_class.call(+ arguments: {+ "period" => "all",+ "exclude_groups" => [group.name],+ },+ request_context:,+ )++ expect(result.dig(:structuredContent, :directory_items).pluck(:id)).to eq([target.id])+ end++ it "is unavailable when the user directory is disabled" do+ SiteSetting.enable_user_directory = false+ request_context =+ instance_double(DiscourseMcp::RequestContext, user: viewer, guardian: viewer.guardian)++ expect do+ described_class.call(arguments: { "period" => "all" }, request_context:)+ end.to raise_error(DiscourseMcp::ToolError)+ end+end++describe DiscourseMcp::Tools::GetDraft do+ fab!(:user)+ fab!(:other_user, :user)++ let(:request_context) { instance_double(DiscourseMcp::RequestContext, user:) }++ it "returns the authenticated user's draft in the compatibility format" do+ draft_data = {+ title: "A topic",+ reply: "A draft reply",+ categoryId: 4,+ tags: ["support"],+ action: "createTopic",+ }.to_json+ Draft.set(user, Draft::NEW_TOPIC, 0, draft_data)+ Draft.set(other_user, Draft::NEW_TOPIC, 0, { reply: "Private draft" }.to_json)++ result = described_class.call(arguments: { "draft_key" => Draft::NEW_TOPIC }, request_context:)++ expect(result.dig(:structuredContent)).to eq(+ draft_key: Draft::NEW_TOPIC,+ sequence: 0,+ found: true,+ data: {+ title: "A topic",+ reply: "A draft reply",+ category_id: 4,+ tags: ["support"],+ action: "createTopic",+ },+ )+ end++ it "reports a missing draft without returning another user's draft" do+ Draft.set(other_user, "topic_123", 0, { reply: "Private draft" }.to_json)++ result = described_class.call(arguments: { "draft_key" => "topic_123" }, request_context:)++ expect(result.dig(:structuredContent)).to eq(draft_key: "topic_123", found: false)+ end++ it "rejects a stale sequence" do+ sequence = Draft.set(user, Draft::NEW_TOPIC, 0, { reply: "First version" }.to_json)+ Draft.set(user, Draft::NEW_TOPIC, sequence, { reply: "Second version" }.to_json)++ expect do+ described_class.call(+ arguments: {+ "draft_key" => Draft::NEW_TOPIC,+ "sequence" => 0,+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.draft_sequence_conflict"))+ end+end++describe DiscourseMcp::Tools::SaveDraft do+ fab!(:user)+ fab!(:topic)++ let(:request_context) { instance_double(DiscourseMcp::RequestContext, user:) }++ it "creates and updates a topic reply draft" do+ draft_key = "topic_#{topic.id}"+ created =+ described_class.call(+ arguments: {+ "draft_key" => draft_key,+ "reply" => "First version",+ "tags" => ["support"],+ },+ request_context:,+ )++ expect(created.dig(:structuredContent)).to eq(draft_key:, sequence: 0, saved: true)+ expect(Draft.find_by!(user:, draft_key:).parsed_data).to include(+ "reply" => "First version",+ "action" => "reply",+ "topic_id" => topic.id,+ "tags" => ["support"],+ )++ updated =+ described_class.call(+ arguments: {+ "draft_key" => draft_key,+ "reply" => "Second version",+ "sequence" => 0,+ },+ request_context:,+ )++ expect(updated.dig(:structuredContent)).to eq(draft_key:, sequence: 1, saved: true)+ expect(Draft.find_by!(user:, draft_key:).parsed_data["reply"]).to eq("Second version")+ end++ it "rejects a stale sequence" do+ Draft.set(user, Draft::NEW_TOPIC, 0, { reply: "First version" }.to_json)+ Draft.set(user, Draft::NEW_TOPIC, 0, { reply: "Second version" }.to_json)++ expect do+ described_class.call(+ arguments: {+ "draft_key" => Draft::NEW_TOPIC,+ "reply" => "Stale version",+ "sequence" => 0,+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.draft_sequence_conflict"))+ end++ it "enforces the site's maximum draft length" do+ SiteSetting.max_draft_length = 20++ expect do+ described_class.call(+ arguments: {+ "draft_key" => Draft::NEW_TOPIC,+ "reply" => "This draft is too long",+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.draft_too_long"))+ end++ it "enforces the maximum number of drafts per user" do+ SiteSetting.max_drafts_per_user = 1+ Draft.set(user, Draft::NEW_TOPIC, 0, { reply: "Existing draft" }.to_json)++ expect do+ described_class.call(+ arguments: {+ "draft_key" => "topic_#{topic.id}",+ "reply" => "Another draft",+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("draft.too_many_drafts.title"))+ end+end++describe DiscourseMcp::Tools::DeleteDraft do+ fab!(:user)++ let(:request_context) { instance_double(DiscourseMcp::RequestContext, user:) }++ it "deletes only the draft at the current sequence" do+ sequence = Draft.set(user, Draft::NEW_TOPIC, 0, { reply: "First version" }.to_json)+ sequence = Draft.set(user, Draft::NEW_TOPIC, sequence, { reply: "Second version" }.to_json)++ expect do+ described_class.call(+ arguments: {+ "draft_key" => Draft::NEW_TOPIC,+ "sequence" => sequence - 1,+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.draft_sequence_conflict"))++ result =+ described_class.call(+ arguments: {+ "draft_key" => Draft::NEW_TOPIC,+ "sequence" => sequence,+ },+ request_context:,+ )++ expect(result.dig(:structuredContent)).to eq(draft_key: Draft::NEW_TOPIC, deleted: true)+ expect(Draft.find_by(user:, draft_key: Draft::NEW_TOPIC)).to be_nil+ end+end++describe DiscourseMcp::Tools::ListUserPosts do+ fab!(:viewer, :user)+ fab!(:user)+ fab!(:topic) { Fabricate(:topic, user:) }++ let(:request_context) { instance_double(DiscourseMcp::RequestContext, guardian: viewer.guardian) }++ it "returns a permission-aware page of the user's topics and replies" do+ first_post = Fabricate(:post, topic:, user:, raw: "First post", created_at: 2.minutes.ago)+ second_post = Fabricate(:post, topic:, user:, raw: "Second post", created_at: 1.minute.ago)+ [first_post, second_post].each do |post|+ UserAction.create!(+ action_type: UserAction::REPLY,+ user:,+ acting_user: user,+ target_topic: topic,+ target_post: post,+ created_at: post.created_at,+ )+ end++ private_category = Fabricate(:private_category, group: Fabricate(:group))+ private_topic = Fabricate(:topic, user:, category: private_category)+ private_post = Fabricate(:post, topic: private_topic, user:, raw: "Private post")+ UserAction.create!(+ action_type: UserAction::REPLY,+ user:,+ acting_user: user,+ target_topic: private_topic,+ target_post: private_post,+ )++ deleted_post = Fabricate(:post, topic:, user:, raw: "Deleted post")+ deleted_post.trash!+ UserAction.create!(+ action_type: UserAction::REPLY,+ user:,+ acting_user: user,+ target_topic: topic,+ target_post: deleted_post,+ )++ result =+ described_class.call(+ arguments: {+ "username" => user.username,+ "page" => 0,+ "limit" => 1,+ },+ request_context:,+ )++ expect(result.dig(:structuredContent, :posts).sole).to include(+ id: second_post.id,+ topic_id: topic.id,+ post_number: second_post.post_number,+ title: topic.title,+ category_id: topic.category_id,+ )+ expect(result.dig(:structuredContent, :meta)).to eq(page: 0, limit: 1, has_more: true)+ end++ it "does not expose activity for a hidden profile" do+ SiteSetting.allow_users_to_hide_profile = true+ user.user_option.update!(hide_profile: true)++ expect do+ described_class.call(arguments: { "username" => user.username }, request_context:)+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.user_not_found"))+ end+end++describe DiscourseMcp::Tools::GetUserSummary do+ fab!(:viewer, :user)+ fab!(:user)++ let(:request_context) { instance_double(DiscourseMcp::RequestContext, guardian: viewer.guardian) }++ it "returns profile-visible summary metrics without private bookmark counts" do+ user.user_stat.update!(post_count: 3, topic_count: 2, days_visited: 7)++ result = described_class.call(arguments: { "username" => user.username }, request_context:)++ expect(result.dig(:structuredContent)).to include(+ username: user.username,+ post_count: 3,+ topic_count: 2,+ days_visited: 7,+ bookmark_count: nil,+ top_topics: [],+ top_replies: [],+ )+ end++ it "does not expose a hidden user's summary" do+ SiteSetting.allow_users_to_hide_profile = true+ user.user_option.update!(hide_profile: true)++ expect do+ described_class.call(arguments: { "username" => user.username }, request_context:)+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.user_not_found"))+ end+end++describe DiscourseMcp::Tools::ListUserActions do+ fab!(:viewer, :user)+ fab!(:user)+ fab!(:topic) { Fabricate(:topic, user:) }+ fab!(:post) { Fabricate(:post, topic:, user:, raw: "Visible reply") }++ let(:request_context) { instance_double(DiscourseMcp::RequestContext, guardian: viewer.guardian) }++ before do+ user.user_stat.update!(post_count: 1)+ UserAction.create!(+ action_type: UserAction::REPLY,+ user:,+ acting_user: user,+ target_topic: topic,+ target_post: post,+ )+ UserAction.create!(+ action_type: UserAction::RESPONSE,+ user:,+ acting_user: user,+ target_topic: topic,+ target_post: post,+ )+ end++ it "returns named public actions and omits private action types for another user" do+ result = described_class.call(arguments: { "username" => user.username }, request_context:)++ expect(result.dig(:structuredContent, :actions).sole).to include(+ action_type: "replies",+ action_type_id: UserAction::REPLY,+ post_id: post.id,+ topic_id: topic.id,+ )+ end++ it "rejects a request for another user's private action types" do+ expect do+ described_class.call(+ arguments: {+ "username" => user.username,+ "action_types" => ["responses"],+ },+ request_context:,+ )+ end.to raise_error(DiscourseMcp::ToolError, I18n.t("mcp.errors.user_not_found"))endenddiff --git a/spec/lib/discourse_mcp/oauth_spec.rb b/spec/lib/discourse_mcp/oauth_spec.rbindex 299c69941be..024d56c0f63 100644--- a/spec/lib/discourse_mcp/oauth_spec.rb+++ b/spec/lib/discourse_mcp/oauth_spec.rb@@ -443,7 +443,7 @@ describe DiscourseMcp::OAuth doaccess_token = McpOauthAccessToken.issue!(authorization: authorization)McpPrimitive.create!(kind: "tool",- identifier: "discourse_post_get",+ identifier: "discourse_read_post",enabled: true,consent_required_at: 1.second.from_now,)diff --git a/spec/lib/discourse_mcp/regular_user_tools_spec.rb b/spec/lib/discourse_mcp/regular_user_tools_spec.rbnew file mode 100644index 00000000000..18bb9ed1c86--- /dev/null+++ b/spec/lib/discourse_mcp/regular_user_tools_spec.rb@@ -0,0 +1,684 @@+# frozen_string_literal: true++describe DiscourseMcp::Tools do+ def request_context(user)+ instance_double(DiscourseMcp::RequestContext, user:, user_id: user.id, guardian: user.guardian)+ end++ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }+ fab!(:other_user, :user)+ fab!(:moderator)+ fab!(:admin)++ describe DiscourseMcp::Tools::Search do+ fab!(:post) { Fabricate(:post, user:, raw: "regular parity search needle") }++ before do+ SearchIndexer.enable+ SearchIndexer.index(post, force: true)+ end++ after { SearchIndexer.disable }++ it "returns the compatible topic search contract" do+ result =+ described_class.call(+ arguments: {+ "query" => "regular parity search needle",+ "max_results" => 1,+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result[:results].sole).to eq(+ id: post.topic_id,+ slug: post.topic.slug,+ title: post.topic.title,+ )+ expect(result[:meta]).to eq(total: 1, has_more: false)+ end+ end++ describe DiscourseMcp::Tools::GetTopic do+ fab!(:post) { Fabricate(:post, user:) }+ fab!(:reply) { Fabricate(:post, topic: post.topic, user: other_user) }++ it "returns the compatible bounded topic contract" do+ result =+ described_class.call(+ arguments: {+ "topic_id" => post.topic_id,+ "post_limit" => 1,+ "start_post_number" => reply.post_number,+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result).to include(id: post.topic_id, posts_count: 2)+ expect(result[:posts].sole).to include(id: reply.id, raw: reply.raw)+ expect(result[:meta]).to eq(start_post: reply.post_number, returned: 1, has_more: false)+ end++ it "does not expose a topic from a private category" do+ group = Fabricate(:group)+ private_category = Fabricate(:private_category, group:)+ private_post = Fabricate(:post, topic: Fabricate(:topic, category: private_category))++ expect do+ described_class.call(+ arguments: {+ "topic_id" => private_post.topic_id,+ },+ request_context: request_context(user),+ )+ end.to raise_error(DiscourseMcp::ToolError)++ group.add(user)+ result =+ described_class.call(+ arguments: {+ "topic_id" => private_post.topic_id,+ },+ request_context: request_context(user),+ )++ expect(result.dig(:structuredContent, :id)).to eq(private_post.topic_id)+ end+ end++ describe DiscourseMcp::Tools::ListTopics do+ it "does not expose tags hidden from the caller" do+ hidden_tag = Fabricate(:tag)+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])+ topic = Fabricate(:topic, user:, tags: [hidden_tag])+ Fabricate(:post, topic:, user:)++ result =+ described_class.call(+ arguments: {+ "limit" => 50,+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ listed_topic = result.fetch(:topics).find { |listed| listed[:id] == topic.id }+ expect(listed_topic.fetch(:tags)).not_to include(hidden_tag.name)+ end+ end++ describe DiscourseMcp::Resources::Topic do+ it "does not expose tags hidden from the caller" do+ hidden_tag = Fabricate(:tag)+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])+ topic = Fabricate(:topic, user:, tags: [hidden_tag])++ result =+ described_class.call(+ uri: "discourse://topic/#{topic.id}",+ request_context: request_context(user),+ )++ tags = JSON.parse(result.fetch(:text)).fetch("tags")+ expect(tags).not_to include(hidden_tag.name)+ end+ end++ describe DiscourseMcp::Tools::GetPost do+ fab!(:post) { Fabricate(:post, user:) }++ it "returns the compatible post contract" do+ result =+ described_class.call(+ arguments: {+ "post_id" => post.id,+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result).to include(+ id: post.id,+ topic_id: post.topic_id,+ topic_slug: post.topic.slug,+ raw: post.raw,+ truncated: false,+ )+ end+ end++ describe DiscourseMcp::Tools::GetUser do+ it "returns profile fields visible to the caller" do+ user.user_profile.update!(bio_raw: "Hello")++ result =+ described_class.call(+ arguments: {+ "username" => user.username,+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result).to include(+ id: user.id,+ username: user.username,+ bio: "Hello",+ admin: false,+ moderator: false,+ )+ end+ end++ describe DiscourseMcp::Tools::UpdateTopic do+ fab!(:topic) { Fabricate(:topic, user:) }+ fab!(:post) { Fabricate(:post, topic:, user:) }++ it "lets an author update an editable topic" do+ result =+ described_class.call(+ arguments: {+ "topic_id" => post.topic_id,+ "title" => "A much better topic title",+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result).to include(success: true, updated_fields: ["title"])+ expect(post.topic.reload.title).to eq("A much better topic title")+ end++ it "does not let another regular user update the topic" do+ expect do+ described_class.call(+ arguments: {+ "topic_id" => post.topic_id,+ "title" => "Not allowed",+ },+ request_context: request_context(other_user),+ )+ end.to raise_error(Discourse::InvalidAccess)+ end++ it "preserves and does not expose tags hidden from the caller" do+ hidden_tag = Fabricate(:tag)+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])+ topic.tags << hidden_tag++ result =+ described_class.call(+ arguments: {+ "topic_id" => post.topic_id,+ "title" => "A title changed without seeing hidden tags",+ "original_tags" => [],+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result.dig(:topic, :tags)).to be_empty+ expect(topic.reload.tags).to contain_exactly(hidden_tag)+ end++ it "does not reveal a hidden tag when a category change is rejected" do+ hidden_tag = Fabricate(:tag)+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])+ topic.tags << hidden_tag+ allowed_tag = Fabricate(:tag)+ category = Fabricate(:category, allow_global_tags: false)+ category.allowed_tags = [allowed_tag.name]++ expect do+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "category_id" => category.id,+ },+ request_context: request_context(user),+ )+ end.to raise_error(DiscourseMcp::ToolError) { |error|+ expect(error.message).not_to include(hidden_tag.name)+ }+ end++ it "changes a shared draft destination without moving the draft topic" do+ shared_drafts_category = Fabricate(:category)+ original_destination = Fabricate(:category)+ new_destination = Fabricate(:category)+ SiteSetting.shared_drafts_category = shared_drafts_category.id+ SiteSetting.shared_drafts_allowed_groups = Group::AUTO_GROUPS[:staff]+ topic.update!(category: shared_drafts_category)+ shared_draft = Fabricate(:shared_draft, topic:, category: original_destination)++ result =+ described_class.call(+ arguments: {+ "topic_id" => topic.id,+ "category_id" => new_destination.id,+ },+ request_context: request_context(admin),+ ).fetch(:structuredContent)++ expect(result[:updated_fields]).to eq(["category_id"])+ expect(result.dig(:topic, :destination_category_id)).to eq(new_destination.id)+ expect(topic.reload.category).to eq(shared_drafts_category)+ expect(shared_draft.reload.category).to eq(new_destination)+ end+ end++ describe "authored content" do+ fab!(:topic) { Fabricate(:topic, user:) }+ fab!(:post) { Fabricate(:post, topic:, user:) }++ it "does not allow author_username to impersonate another user" do+ expect do+ DiscourseMcp::Tools::ReplyTopic.call(+ arguments: {+ "topic_id" => topic.id,+ "raw" => "A complete reply body.",+ "author_username" => other_user.username,+ },+ request_context: request_context(user),+ )+ end.to raise_error(Discourse::InvalidAccess)+ end++ it "creates a compatible topic and post response as the current user" do+ created_topic =+ DiscourseMcp::Tools::CreateTopic.call(+ arguments: {+ "title" => "A valid regular user topic",+ "raw" => "A complete topic body for this test.",+ "author_username" => user.username,+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)+ created_post =+ DiscourseMcp::Tools::ReplyTopic.call(+ arguments: {+ "topic_id" => created_topic[:topic_id],+ "raw" => "A complete reply body for this test.",+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(created_topic[:id]).to be_a(Integer)+ expect(created_topic).to include(username: user.username, author_applied: true)+ expect(created_post).to include(topic_id: created_topic[:topic_id], post_number: 2)+ end++ it "updates a post only when the caller may edit it" do+ result =+ DiscourseMcp::Tools::EditPost.call(+ arguments: {+ "post_id" => post.id,+ "raw" => "An updated complete post body.",+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result).to include(id: post.id, raw: "An updated complete post body.")+ expect do+ DiscourseMcp::Tools::EditPost.call(+ arguments: {+ "post_id" => post.id,+ "raw" => "An unauthorized complete post body.",+ },+ request_context: request_context(other_user),+ )+ end.to raise_error(DiscourseMcp::ToolError)+ end+ end++ describe DiscourseMcp::Tools::UpdateUser do+ it "lets a user update their own profile" do+ result =+ described_class.call(+ arguments: {+ "username" => user.username,+ "bio_raw" => "Updated profile",+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result).to include(success: true, username: user.username)+ expect(user.user_profile.reload.bio_raw).to eq("Updated profile")+ end++ it "does not turn staff access into permission to edit another profile" do+ [moderator, admin].each do |staff_user|+ expect do+ described_class.call(+ arguments: {+ "username" => user.username,+ "bio_raw" => "Staff edit",+ },+ request_context: request_context(staff_user),+ )+ end.to raise_error(Discourse::InvalidAccess)+ end+ end+ end++ describe DiscourseMcp::Tools::UploadFile do+ it "creates a composer upload owned by the authenticated user" do+ image_data = Base64.strict_encode64(file_from_fixtures("logo.png").read)++ result =+ described_class.call(+ arguments: {+ "upload_type" => "composer",+ "image_data" => image_data,+ "filename" => "logo.png",+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result[:id]).to be_a(Integer)+ expect(result[:original_filename]).to eq("logo.png")+ expect(Upload.find(result[:id]).user_id).to eq(user.id)+ end++ it "does not accept another user's id" do+ expect do+ described_class.call(+ arguments: {+ "upload_type" => "avatar",+ "image_data" => Base64.strict_encode64("image"),+ "filename" => "image.png",+ "user_id" => other_user.id,+ },+ request_context: request_context(user),+ )+ end.to raise_error(Discourse::InvalidAccess)+ end+ end++ describe "private messages" do+ fab!(:message) { Fabricate(:private_message_post, user:, recipient: other_user) }++ before { SiteSetting.personal_message_enabled_groups = Group::AUTO_GROUPS[:everyone] }++ it "lists only a mailbox the caller may access" do+ result =+ DiscourseMcp::Tools::ListPrivateMessages.call(+ arguments: {+ "username" => other_user.username,+ },+ request_context: request_context(other_user),+ ).fetch(:structuredContent)++ expect(result[:messages].pluck(:topic_id)).to include(message.topic_id)+ expect do+ DiscourseMcp::Tools::ListPrivateMessages.call(+ arguments: {+ "username" => other_user.username,+ },+ request_context: request_context(moderator),+ )+ end.to raise_error(Discourse::InvalidAccess)+ end++ it "paginates a mailbox without skipping messages" do+ newer_message = Fabricate(:private_message_post, user:, recipient: other_user)+ newer_message.topic.update!(bumped_at: 1.minute.from_now)++ first_page =+ DiscourseMcp::Tools::ListPrivateMessages.call(+ arguments: {+ "per_page" => 1,+ },+ request_context: request_context(other_user),+ ).fetch(:structuredContent)+ second_page =+ DiscourseMcp::Tools::ListPrivateMessages.call(+ arguments: {+ "page" => 1,+ "per_page" => 1,+ },+ request_context: request_context(other_user),+ ).fetch(:structuredContent)++ expect(first_page[:messages].sole[:topic_id]).to eq(newer_message.topic_id)+ expect(first_page[:meta][:has_more]).to eq(true)+ expect(second_page[:messages].sole[:topic_id]).to eq(message.topic_id)+ end++ it "lists a group mailbox only for group members and admins" do+ group = Fabricate(:group, has_messages: true)+ group.add(other_user)+ group_message = Fabricate(:group_private_message_post, user:, recipients: group)++ [other_user, admin].each do |viewer|+ result =+ DiscourseMcp::Tools::ListPrivateMessages.call(+ arguments: {+ "username" => viewer.username,+ "group_name" => group.name,+ },+ request_context: request_context(viewer),+ ).fetch(:structuredContent)++ expect(result[:messages].pluck(:topic_id)).to include(group_message.topic_id)+ end++ expect do+ DiscourseMcp::Tools::ListPrivateMessages.call(+ arguments: {+ "username" => moderator.username,+ "group_name" => group.name,+ },+ request_context: request_context(moderator),+ )+ end.to raise_error(Discourse::InvalidAccess)+ end++ it "reads a private message only for participants and admins" do+ expectations = { user => true, other_user => true, moderator => false, admin => true }++ expectations.each do |viewer, allowed|+ operation =+ lambda do+ DiscourseMcp::Tools::ReadPrivateMessage.call(+ arguments: {+ "topic_id" => message.topic_id,+ },+ request_context: request_context(viewer),+ )+ end++ if allowed+ expect(operation.call.dig(:structuredContent, :posts).sole[:id]).to eq(message.id)+ else+ expect(&operation).to raise_error(DiscourseMcp::ToolError)+ end+ end+ end++ it "rejects a public topic as a private message" do+ topic = Fabricate(:topic)++ expect do+ DiscourseMcp::Tools::ReadPrivateMessage.call(+ arguments: {+ "topic_id" => topic.id,+ },+ request_context: request_context(user),+ )+ end.to raise_error(DiscourseMcp::ToolError)+ end++ it "creates and replies to a private message as the authenticated user" do+ created =+ DiscourseMcp::Tools::CreatePrivateMessage.call(+ arguments: {+ "title" => "Private hello",+ "raw" => "First message",+ "usernames" => [other_user.username],+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)+ reply =+ DiscourseMcp::Tools::ReplyPrivateMessage.call(+ arguments: {+ "topic_id" => created[:topic_id],+ "raw" => "A complete private reply.",+ },+ request_context: request_context(other_user),+ ).fetch(:structuredContent)++ expect(created).to include(title: "Private hello")+ expect(reply).to include(topic_id: created[:topic_id], post_number: 2)+ end++ it "limits all recipient types together when creating a message" do+ group = Fabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone])+ SiteSetting.max_allowed_message_recipients = 1++ expect do+ DiscourseMcp::Tools::CreatePrivateMessage.call(+ arguments: {+ "title" => "Too many recipients",+ "raw" => "This message has too many recipients.",+ "usernames" => [other_user.username],+ "group_names" => [group.name],+ },+ request_context: request_context(user),+ )+ end.to raise_error(DiscourseMcp::ToolError, I18n.t(:max_pm_recipients, recipients_limit: 1))+ end++ it "invites a user only when the caller may invite to the message" do+ invited_user = Fabricate(:user)+ result =+ DiscourseMcp::Tools::InviteToPrivateMessage.call(+ arguments: {+ "topic_id" => message.topic_id,+ "username" => invited_user.username,+ },+ request_context: request_context(user),+ ).fetch(:structuredContent)++ expect(result).to include(topic_id: message.topic_id, recipient_type: "user", status: "added")+ expect(message.topic.reload.allowed_users).to include(invited_user)++ expect do+ DiscourseMcp::Tools::InviteToPrivateMessage.call(+ arguments: {+ "topic_id" => message.topic_id,+ "username" => Fabricate(:user).username,+ },+ request_context: request_context(moderator),+ )+ end.to raise_error(DiscourseMcp::ToolError)+ end++ it "does not let a regular user invite a group after reaching the recipient limit" do+ group = Fabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone])+ SiteSetting.max_allowed_message_recipients = 2++ expect do+ DiscourseMcp::Tools::InviteToPrivateMessage.call(+ arguments: {+ "topic_id" => message.topic_id,+ "group_name" => group.name,+ },+ request_context: request_context(user),+ )+ end.to raise_error(+ DiscourseMcp::ToolError,+ I18n.t("pm_reached_recipients_limit", recipients_limit: 2),+ )+ expect(message.topic.reload.allowed_groups).to be_empty+ end++ it "lets staff invite a group after reaching the recipient limit" do+ group = Fabricate(:group, messageable_level: Group::ALIAS_LEVELS[:everyone])+ SiteSetting.max_allowed_message_recipients = 2++ result =+ DiscourseMcp::Tools::InviteToPrivateMessage.call(+ arguments: {+ "topic_id" => message.topic_id,+ "group_name" => group.name,+ },+ request_context: request_context(admin),+ ).fetch(:structuredContent)++ expect(result).to include(recipient_type: "group", status: "added")+ expect(message.topic.reload.allowed_groups).to contain_exactly(group)+ end+ end+end++describe DiscourseMcp::CorePrimitives do+ it "registers the compatible regular-user tool names" do+ expected_names = %w[+ discourse_create_post+ discourse_create_private_message+ discourse_create_topic+ discourse_get_user+ discourse_invite_to_private_message+ discourse_list_private_messages+ discourse_read_post+ discourse_read_private_message+ discourse_read_topic+ discourse_reply_private_message+ discourse_update_post+ discourse_update_topic+ discourse_update_user+ discourse_upload_file+ ]++ expect(expected_names).to all(satisfy { |name| DiscourseMcp.registry.find(:tool, name) })+ expect(DiscourseMcp.registry.find(:tool, "discourse_topic_get")).to be_nil+ end++ it "uses a separate write scope for profile updates" do+ primitive = DiscourseMcp.registry.find(:tool, "discourse_update_user")++ expect(primitive.required_scopes).to eq(["mcp:profile:write"])+ end++ it "uses separate scopes for private messages and drafts" do+ private_message_scopes =+ %w[+ discourse_list_private_messages+ discourse_read_private_message+ discourse_create_private_message+ discourse_reply_private_message+ discourse_invite_to_private_message+ ].to_h do |identifier|+ primitive = DiscourseMcp.registry.find(:tool, identifier)+ [identifier, primitive.required_scopes]+ end+ draft_scopes =+ %w[discourse_get_draft discourse_save_draft discourse_delete_draft].to_h do |identifier|+ primitive = DiscourseMcp.registry.find(:tool, identifier)+ [identifier, primitive.required_scopes]+ end++ expect(private_message_scopes).to eq(+ "discourse_list_private_messages" => ["mcp:private-messages:read"],+ "discourse_read_private_message" => ["mcp:private-messages:read"],+ "discourse_create_private_message" => ["mcp:private-messages:write"],+ "discourse_reply_private_message" => ["mcp:private-messages:write"],+ "discourse_invite_to_private_message" => ["mcp:private-messages:write"],+ )+ expect(draft_scopes).to eq(+ "discourse_get_draft" => ["mcp:drafts:read"],+ "discourse_save_draft" => ["mcp:drafts:write"],+ "discourse_delete_draft" => ["mcp:drafts:write"],+ )+ end++ it "requires renewed consent for tools that can affect external systems" do+ primitive_names = %w[+ discourse_create_private_message+ discourse_invite_to_private_message+ discourse_upload_file+ ]++ primitives = primitive_names.map { |name| DiscourseMcp.registry.find(:tool, name) }++ expect(primitives.map(&:risk)).to all(eq(:external_side_effect))+ expect(primitives.map { |primitive| primitive.annotations["openWorldHint"] }).to all(eq(true))+ expect(primitives).to all(be_consent_relevant)+ end+enddiff --git a/spec/requests/admin/mcp_activity_controller_spec.rb b/spec/requests/admin/mcp_activity_controller_spec.rbindex 4a8ee588eea..199a7c57b63 100644--- a/spec/requests/admin/mcp_activity_controller_spec.rb+++ b/spec/requests/admin/mcp_activity_controller_spec.rb@@ -18,7 +18,7 @@ describe Admin::McpActivityController doMcpAuditLog.create!(occurred_at: Time.zone.now,method: "tools/call",- tool: "discourse_topic_create",+ tool: "discourse_create_topic",outcome: "error",occurrences: 3,duration_ms: 100,diff --git a/spec/requests/admin/mcp_controller_spec.rb b/spec/requests/admin/mcp_controller_spec.rbindex 39a8b805c7b..1d9c2a087d0 100644--- a/spec/requests/admin/mcp_controller_spec.rb+++ b/spec/requests/admin/mcp_controller_spec.rb@@ -28,7 +28,12 @@ describe Admin::McpController doexpect(response.status).to eq(200)scopes = response.parsed_body["available_scopes"]expect(scopes).to eq(scopes.uniq.sort)- expect(scopes).to include("mcp:profile:read", "mcp:content:read", "mcp:content:write")+ expect(scopes).to include(+ "mcp:profile:read",+ "mcp:profile:write",+ "mcp:content:read",+ "mcp:content:write",+ )expect(response.parsed_body["primitives"]).to be_presentendenddiff --git a/spec/requests/mcp_controller_spec.rb b/spec/requests/mcp_controller_spec.rbindex 4377330b0da..553eb222c6f 100644--- a/spec/requests/mcp_controller_spec.rb+++ b/spec/requests/mcp_controller_spec.rb@@ -98,18 +98,18 @@ describe "MCP transport" doendit "returns an OAuth insufficient-scope challenge for an exposed tool" do- McpPrimitive.create!(kind: "tool", identifier: "discourse_post_get", enabled: true)+ McpPrimitive.create!(kind: "tool", identifier: "discourse_read_post", enabled: true)scoped_payload =payload.deep_merge(method: "tools/call",params: {- name: "discourse_post_get",+ name: "discourse_read_post",arguments: {post_id: 1,},},)- scoped_headers = headers.merge("HTTP_MCP_NAME" => "discourse_post_get")+ scoped_headers = headers.merge("HTTP_MCP_NAME" => "discourse_read_post")post "/mcp", params: scoped_payload.to_json, headers: scoped_headers@@ -120,6 +120,39 @@ describe "MCP transport" do)end+ it "does not allow content-write access to update a profile" do+ McpPrimitive.create!(kind: "tool", identifier: "discourse_update_user", enabled: true)+ scoped_payload =+ payload.deep_merge(+ params: {+ name: "discourse_update_user",+ arguments: {+ username: admin.username,+ bio_raw: "Changed without profile access",+ },+ },+ )+ scoped_headers = headers.merge("HTTP_MCP_NAME" => "discourse_update_user")+ content_write_authorization =+ DiscourseMcp::OAuth::AuthorizationGrant.create!(+ user: admin,+ client:,+ redirect_uri: client.redirect_uris.first,+ requested_scopes: %w[mcp:profile:read mcp:content:write],+ )+ content_write_token = McpOauthAccessToken.issue!(authorization: content_write_authorization)+ scoped_headers["HTTP_AUTHORIZATION"] = "Bearer #{content_write_token}"++ post "/mcp", params: scoped_payload.to_json, headers: scoped_headers++ expect(response.status).to eq(403)+ expect(response.headers["WWW-Authenticate"]).to include(+ 'error="insufficient_scope"',+ 'scope="mcp:profile:write"',+ )+ expect(admin.user_profile.reload.bio_raw).not_to eq("Changed without profile access")+ end+it "negotiates a compatible protocol through the standard initialize request" dopost "/mcp",params: initialize_payload.to_json,diff --git a/spec/requests/topics_controller_spec.rb b/spec/requests/topics_controller_spec.rbindex 63eb93ebf5e..4caa4006516 100644--- a/spec/requests/topics_controller_spec.rb+++ b/spec/requests/topics_controller_spec.rb@@ -2973,6 +2973,18 @@ RSpec.describe TopicsController doexpect(topic.reload.tags).to include(tag1)end+ it "does not reveal a hidden current tag when a category change is rejected" do+ hidden_tag = Fabricate(:tag)+ Fabricate(:tag_group, permissions: { "staff" => 1 }, tag_names: [hidden_tag.name])+ topic.update!(tags: [hidden_tag])+ restricted_category.allowed_tags = [tag2.name]++ put "/t/#{topic.slug}/#{topic.id}.json", params: { category_id: restricted_category.id }++ expect(response.status).to eq(422)+ expect(response.parsed_body["errors"].first).not_to include(hidden_tag.name)+ end+it "allows category change when topic has a read-only tag" doFabricate(:tag_group,