Skip to content

A platform for community discussion. Free, open, simple.

SECURITY: Enforce MCP private-message scopes and content visibility

Isaac Janzen12f263e580ae
diff --git a/lib/discourse_mcp/tool_helpers.rb b/lib/discourse_mcp/tool_helpers.rb
index 552bd014d52..b7a76049834 100644
--- a/lib/discourse_mcp/tool_helpers.rb
+++ b/lib/discourse_mcp/tool_helpers.rb
@@ -155,6 +155,19 @@ module DiscourseMcp
request_context.ensure_scopes!("mcp:private-messages:#{access}")
end
+ def ensure_private_message_draft_scope!(draft_key, request_context, access:)
+ topic_id = draft_key.match(/\Atopic_(\d+)\z/)&.captures&.first
+ private_message_draft =
+ draft_key.start_with?(Draft::NEW_PRIVATE_MESSAGE) ||
+ (
+ topic_id &&
+ Topic.with_deleted.exists?(id: topic_id.to_i, archetype: Archetype.private_message)
+ )
+ return if !private_message_draft
+
+ request_context.ensure_scopes!("mcp:private-messages:#{access}")
+ end
+
def ensure_current_author!(arguments, user)
requested_author = arguments["author_username"]
return if requested_author.blank? || requested_author.casecmp?(user.username)
diff --git a/lib/discourse_mcp/tools/drafts.rb b/lib/discourse_mcp/tools/drafts.rb
index 0ad406577df..824730d7677 100644
--- a/lib/discourse_mcp/tools/drafts.rb
+++ b/lib/discourse_mcp/tools/drafts.rb
@@ -28,9 +28,13 @@ module DiscourseMcp
topic_id = draft_key.match(/\Atopic_(\d+)\z/)&.captures&.first
if draft_key.start_with?(Draft::NEW_PRIVATE_MESSAGE) ||
- (topic_id && Topic.exists?(id: topic_id.to_i, archetype: Archetype.private_message))
+ (
+ topic_id &&
+ Topic.with_deleted.exists?(id: topic_id.to_i, archetype: Archetype.private_message)
+ )
request_context.ensure_scopes!(Scopes::PRIVATE_MESSAGES_READ)
end
+ ToolHelpers.ensure_private_message_draft_scope!(draft_key, request_context, access: :read)
parsed = JSON.parse(draft)
parsed = {} if !parsed.is_a?(Hash)
@@ -76,6 +80,7 @@ module DiscourseMcp
def self.call(arguments:, request_context:)
user = request_context.user or raise Discourse::InvalidAccess
draft_key = arguments.fetch("draft_key")
+ ToolHelpers.ensure_private_message_draft_scope!(draft_key, request_context, access: :write)
if !Draft.exists?(user_id: user.id, draft_key:) &&
Draft.where(user_id: user.id).count >= SiteSetting.max_drafts_per_user
@@ -120,6 +125,7 @@ module DiscourseMcp
def self.call(arguments:, request_context:)
user = request_context.user or raise Discourse::InvalidAccess
draft_key = arguments.fetch("draft_key")
+ ToolHelpers.ensure_private_message_draft_scope!(draft_key, request_context, access: :write)
Draft.clear(user, draft_key, arguments.fetch("sequence"))
ToolHelpers.text_and_structured(draft_key:, deleted: true)
rescue Draft::OutOfSequence
diff --git a/lib/discourse_mcp/tools/notifications.rb b/lib/discourse_mcp/tools/notifications.rb
index 7c3a4f4b854..92edf6c2fea 100644
--- a/lib/discourse_mcp/tools/notifications.rb
+++ b/lib/discourse_mcp/tools/notifications.rb
@@ -17,10 +17,10 @@ module DiscourseMcp
.limit(limit)
if !request_context.has_scopes?(Scopes::PRIVATE_MESSAGES_READ)
notifications =
- notifications.left_joins(:topic).where(
- "topics.id IS NULL OR topics.archetype <> ?",
- Archetype.private_message,
- )
+ notifications
+ .where.not(notification_type: Notification.types[:group_message_summary])
+ .left_joins(:topic)
+ .where("topics.id IS NULL OR topics.archetype <> ?", Archetype.private_message)
end
notifications =
Notification.filter_inaccessible_topic_notifications(
diff --git a/lib/discourse_mcp/tools/private_messages.rb b/lib/discourse_mcp/tools/private_messages.rb
index 273f2426231..307082f589c 100644
--- a/lib/discourse_mcp/tools/private_messages.rb
+++ b/lib/discourse_mcp/tools/private_messages.rb
@@ -164,8 +164,12 @@ module DiscourseMcp
start_post_number = arguments.fetch("start_post_number", 1)
post_limit = arguments.fetch("post_limit", 5)
posts =
- Post
- .secured(request_context.guardian)
+ request_context
+ .guardian
+ .filter_hidden_posts(
+ Post.secured(request_context.guardian).joins(:topic),
+ category: topic.category,
+ )
.where(topic_id: topic.id, post_number: start_post_number..)
.order(:post_number)
.includes(:topic, :user)
diff --git a/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb b/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
index 9aefe2a7539..b5f766c6a78 100644
--- a/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
+++ b/plugins/discourse-data-explorer/lib/discourse_data_explorer/data_explorer.rb
@@ -56,6 +56,8 @@ module DiscourseDataExplorer
# skipping the declared-parameter casting `run_query` does. Callers with
# undeclared parameters, such as a workflow's raw SQL node, use this directly.
def self.run_query_with_values(query, values = {}, opts = {})
+ opts = opts.merge(explain: false) if opts[:explain] && !opts[:current_user]&.admin?
+
# Safety checks
# see test 'doesn't allow you to modify the database #2'
if query.sql =~ /;/
diff --git a/plugins/discourse-data-explorer/spec/requests/mcp_tools_spec.rb b/plugins/discourse-data-explorer/spec/requests/mcp_tools_spec.rb
index 817c5af156a..723110fe6e0 100644
--- a/plugins/discourse-data-explorer/spec/requests/mcp_tools_spec.rb
+++ b/plugins/discourse-data-explorer/spec/requests/mcp_tools_spec.rb
@@ -37,7 +37,7 @@ describe "Data Explorer MCP tools" do
@token = McpOauthAccessToken.issue!(authorization:)
end
- def call_run_query
+ def call_run_query(arguments = {})
post "/mcp",
params: {
jsonrpc: "2.0",
@@ -45,9 +45,7 @@ describe "Data Explorer MCP tools" do
method: "tools/call",
params: {
name: "discourse_run_query",
- arguments: {
- id: query.id,
- },
+ arguments: { id: query.id }.merge(arguments),
},
}.to_json,
headers: {
@@ -82,6 +80,17 @@ describe "Data Explorer MCP tools" do
)
end
+ it "does not return explain output for an assigned query" do
+ query.update!(sql: "SELECT id FROM users WHERE username = 'admin-only-query-predicate'")
+ authorize(DiscourseDataExplorer::McpTools::READ_SCOPE)
+
+ call_run_query(explain: true)
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("result", "structuredContent")).not_to have_key("explain")
+ expect(response.body).not_to include("admin-only-query-predicate")
+ end
+
it "does not run a query when the token has scope but the user lacks query access" do
query.query_groups.delete_all
Fabricate(:query_group, query:, group: other_group)
diff --git a/plugins/discourse-data-explorer/spec/requests/query_execution_security_spec.rb b/plugins/discourse-data-explorer/spec/requests/query_execution_security_spec.rb
index 9f37d329be9..5b722cfa700 100644
--- a/plugins/discourse-data-explorer/spec/requests/query_execution_security_spec.rb
+++ b/plugins/discourse-data-explorer/spec/requests/query_execution_security_spec.rb
@@ -21,6 +21,21 @@ describe "Data Explorer group report query execution" do
query
end
+ it "does not disclose an admin-only query predicate in explain output to group members" do
+ query =
+ DiscourseDataExplorer::Query.create!(
+ name: "Shared report",
+ sql: "SELECT id FROM users WHERE username = 'admin-only-query-predicate'",
+ )
+ query.query_groups.create!(group: group)
+
+ post "/g/#{group.name}/reports/#{query.id}/run.json", params: { explain: "true" }
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body["explain"]).to be_nil
+ expect(response.body).not_to include("admin-only-query-predicate")
+ end
+
it "rejects a group member's parameter inside a dollar-quoted literal" do
victim =
Fabricate(:user, username: SecureRandom.hex(8), email: "#{SecureRandom.hex(8)}@example.com")
diff --git a/plugins/discourse-events/lib/discourse_events/mcp_tools.rb b/plugins/discourse-events/lib/discourse_events/mcp_tools.rb
index a4fbb03e9be..2dc76271489 100644
--- a/plugins/discourse-events/lib/discourse_events/mcp_tools.rb
+++ b/plugins/discourse-events/lib/discourse_events/mcp_tools.rb
@@ -29,7 +29,11 @@ module DiscourseEvents
after: "now",
include_ongoing: true,
limit:,
- ).preload(post: :topic)
+ )
+ if !request_context.has_scopes?(DiscourseMcp::Scopes::PRIVATE_MESSAGES_READ)
+ events = events.where.not(topics: { archetype: Archetype.private_message })
+ end
+ events = events.preload(post: :topic)
values =
events.map do |event|
{
diff --git a/plugins/discourse-events/spec/lib/discourse_events/mcp_tools_spec.rb b/plugins/discourse-events/spec/lib/discourse_events/mcp_tools_spec.rb
index 7cbd6004626..da648f4b850 100644
--- a/plugins/discourse-events/spec/lib/discourse_events/mcp_tools_spec.rb
+++ b/plugins/discourse-events/spec/lib/discourse_events/mcp_tools_spec.rb
@@ -17,7 +17,13 @@ describe DiscourseEvents::McpTools::ListEvents do
original_starts_at: 1.day.from_now.iso8601,
original_ends_at: 2.days.from_now.iso8601,
)
- request_context = instance_double(DiscourseMcp::RequestContext, user:, guardian: user.guardian)
+ request_context =
+ instance_double(
+ DiscourseMcp::RequestContext,
+ user:,
+ guardian: user.guardian,
+ has_scopes?: false,
+ )
result = described_class.call(arguments: {}, request_context:)
diff --git a/plugins/discourse-events/spec/requests/mcp_tools_spec.rb b/plugins/discourse-events/spec/requests/mcp_tools_spec.rb
new file mode 100644
index 00000000000..7aba3651acc
--- /dev/null
+++ b/plugins/discourse-events/spec/requests/mcp_tools_spec.rb
@@ -0,0 +1,93 @@
+# frozen_string_literal: true
+
+describe "Calendar MCP tools" do
+ fab!(:user) { Fabricate(:user, refresh_auto_groups: true) }
+ fab!(:group)
+ fab!(:public_event) do
+ Fabricate(:event, name: "Public planning meeting", original_starts_at: 1.day.from_now.iso8601)
+ end
+ fab!(:private_event) do
+ Fabricate(
+ :event,
+ post: Fabricate(:private_message_post, recipient: user),
+ name: "Private acquisition meeting",
+ original_starts_at: 2.days.from_now.iso8601,
+ )
+ end
+
+ before do
+ SiteSetting.discourse_events_enabled = true
+ SiteSetting.discourse_post_event_enabled = true
+ SiteSetting.mcp_server_enabled = true
+ group.add(user)
+ McpPrimitive.find_or_create_by!(
+ kind: "tool",
+ identifier: "discourse_calendar_event_list",
+ ) { |primitive| primitive.enabled = true }
+ end
+
+ def authorize(*extra_scopes)
+ scopes = [DiscourseMcp::INITIAL_SCOPE, *extra_scopes]
+ scopes.each { |scope| McpGroupScope.find_or_create_by!(group:, scope:) }
+ client =
+ McpOauthClient.create!(
+ client_id: SecureRandom.hex,
+ name: "Calendar test client",
+ registration_type: "pre_registered",
+ trust_state: "approved",
+ redirect_uris: ["http://127.0.0.1/callback"],
+ )
+ authorization =
+ DiscourseMcp::OAuth::AuthorizationGrant.create!(
+ user:,
+ client:,
+ redirect_uri: client.redirect_uris.first,
+ requested_scopes: scopes,
+ )
+ @token = McpOauthAccessToken.issue!(authorization:)
+ end
+
+ def call_list_events
+ post "/mcp",
+ params: {
+ jsonrpc: "2.0",
+ id: 1,
+ method: "tools/call",
+ params: {
+ name: "discourse_calendar_event_list",
+ arguments: {
+ },
+ },
+ }.to_json,
+ headers: {
+ "HTTP_AUTHORIZATION" => "Bearer #{@token}",
+ "CONTENT_TYPE" => "application/json",
+ "HTTP_ACCEPT" => "application/json, text/event-stream",
+ "HTTP_MCP_PROTOCOL_VERSION" => DiscourseMcp::LEGACY_PROTOCOL_VERSION,
+ }
+ end
+
+ it "hides private-message event metadata without the private-message read scope" do
+ authorize("discourse-calendar:read")
+
+ call_list_events
+
+ aggregate_failures do
+ expect(response.status).to eq(200)
+ expect(
+ response.parsed_body.dig("result", "structuredContent", "events").pluck("id"),
+ ).to contain_exactly(public_event.id)
+ expect(response.body).not_to include(private_event.name)
+ end
+
+ authorize("discourse-calendar:read", DiscourseMcp::Scopes::PRIVATE_MESSAGES_READ)
+
+ call_list_events
+
+ expect(response.status).to eq(200)
+ expect(
+ response.parsed_body.dig("result", "structuredContent", "events").pluck("id"),
+ ).to contain_exactly(public_event.id, private_event.id)
+ expect(response.body).to include(private_event.name)
+ end
+end
diff --git a/spec/requests/mcp_content_access_spec.rb b/spec/requests/mcp_content_access_spec.rb
index 39d0dc54069..99468e64844 100644
--- a/spec/requests/mcp_content_access_spec.rb
+++ b/spec/requests/mcp_content_access_spec.rb
@@ -395,7 +395,7 @@ describe "MCP content access" do
end
end
- it "requires private-message read scope for private-message drafts" do
+ it "requires private-message read scope for live and soft-deleted private-message drafts" do
topic = Fabricate(:topic, user:)
topic_draft_key = "topic_#{topic.id}"
message_draft_key = "topic_#{message.topic_id}"
@@ -424,6 +424,11 @@ describe "MCP content access" do
end
expect(response.body).not_to include(private_title)
+ message.topic.trash!
+ call_tool("discourse_get_draft", { draft_key: message_draft_key })
+ expect_missing_scope("mcp:private-messages:read")
+ expect(response.body).not_to include(private_reply)
+
authorize("mcp:drafts:read", "mcp:private-messages:read")
call_tool("discourse_get_draft", { draft_key: compose_draft_key })
expect(response.status).to eq(200)
@@ -435,6 +440,102 @@ describe "MCP content access" do
)
end
+ it "requires private-message write scope for private-message draft mutations" do
+ draft_key = "topic_#{message.topic_id}"
+ original_reply = "Private reply draft"
+ Draft.set(user, draft_key, 0, { reply: original_reply }.to_json)
+ authorize("mcp:drafts:write")
+
+ call_tool(
+ "discourse_save_draft",
+ { draft_key:, reply: "Overwritten without private-message scope", sequence: 0 },
+ )
+
+ expect_missing_scope("mcp:private-messages:write")
+ expect(response.parsed_body.dig("error", "message")).to eq("Insufficient scope")
+ expect(Draft.find_by!(user:, draft_key:).parsed_data["reply"]).to eq(original_reply)
+
+ call_tool("discourse_delete_draft", { draft_key:, sequence: 0 })
+
+ expect_missing_scope("mcp:private-messages:write")
+ expect(Draft.find_by!(user:, draft_key:)).to be_present
+
+ authorize("mcp:drafts:write", "mcp:private-messages:write")
+ call_tool("discourse_save_draft", { draft_key:, reply: "Updated private reply", sequence: 0 })
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("result", "structuredContent", "saved")).to eq(true)
+
+ call_tool("discourse_delete_draft", { draft_key:, sequence: 1 })
+
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("result", "structuredContent", "deleted")).to eq(true)
+ expect(Draft.find_by(user:, draft_key:)).to be_nil
+ end
+
+ it "requires private-message write scope for soft-deleted private-message reply drafts" do
+ draft_key = "topic_#{message.topic_id}"
+ original_reply = "Retained private reply draft"
+ Draft.set(user, draft_key, 0, { reply: original_reply }.to_json)
+ message.topic.trash!
+ authorize("mcp:drafts:write")
+
+ call_tool(
+ "discourse_save_draft",
+ { draft_key:, reply: "Overwritten without private-message scope", sequence: 0 },
+ )
+
+ expect_missing_scope("mcp:private-messages:write")
+ expect(Draft.find_by!(user:, draft_key:).parsed_data["reply"]).to eq(original_reply)
+
+ call_tool("discourse_delete_draft", { draft_key:, sequence: 0 })
+
+ expect_missing_scope("mcp:private-messages:write")
+ expect(Draft.find_by!(user:, draft_key:).parsed_data["reply"]).to eq(original_reply)
+ end
+
+ it "requires private-message write scope for fixed and suffixed compose keys" do
+ public_draft_key = "topic_#{Fabricate(:topic, user:).id}"
+ compose_keys = [
+ Draft::NEW_PRIVATE_MESSAGE,
+ "#{Draft::NEW_PRIVATE_MESSAGE}_#{Time.zone.now.to_i}",
+ ]
+ authorize("mcp:drafts:write")
+
+ call_tool(
+ "discourse_save_draft",
+ { draft_key: public_draft_key, reply: "Public edit", sequence: 0 },
+ )
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("result", "structuredContent", "saved")).to eq(true)
+
+ compose_keys.each do |compose_key|
+ call_tool(
+ "discourse_save_draft",
+ { draft_key: compose_key, reply: "Blocked compose", sequence: 0 },
+ )
+ aggregate_failures(compose_key) do
+ expect_missing_scope("mcp:private-messages:write")
+ expect(Draft.exists?(user_id: user.id, draft_key: compose_key)).to eq(false)
+ end
+
+ call_tool("discourse_delete_draft", { draft_key: compose_key, sequence: 0 })
+ aggregate_failures(compose_key) { expect_missing_scope("mcp:private-messages:write") }
+ end
+
+ authorize("mcp:drafts:write", "mcp:private-messages:write")
+ compose_keys.each do |compose_key|
+ call_tool(
+ "discourse_save_draft",
+ { draft_key: compose_key, reply: "Allowed compose", sequence: 0 },
+ )
+ aggregate_failures(compose_key) do
+ expect(response.status).to eq(200)
+ expect(response.parsed_body.dig("result", "structuredContent", "saved")).to eq(true)
+ end
+ end
+ end
+
it "requires the read scope for private-message resources and draft prompts" do
authorize
{ "topic" => message.topic_id, "post" => message.id }.each do |type, id|
@@ -651,21 +752,35 @@ describe "MCP content access" do
it "filters private-message notifications before the limit unless the read scope is granted" do
public_notification = Fabricate(:notification, user:)
other_notification = Fabricate(:notification, user:, topic: nil)
+ group_summary_notification =
+ Fabricate(
+ :notification,
+ user:,
+ topic: nil,
+ notification_type: Notification.types[:group_message_summary],
+ data: { group_id: group.id, group_name: group.name, inbox_count: 2 }.to_json,
+ )
private_notification = Fabricate(:private_message_notification, user:, topic: message.topic)
authorize
- call_tool("discourse_notification_list", { limit: 2 })
+ call_tool("discourse_notification_list", { limit: 3 })
expect(response.status).to eq(200)
notifications = response.parsed_body.dig("result", "structuredContent", "notifications")
expect(notifications.pluck("id")).to eq([other_notification.id, public_notification.id])
+ expect(response.body).not_to include(group.name)
authorize("mcp:private-messages:read")
- call_tool("discourse_notification_list", { limit: 2 })
+ call_tool("discourse_notification_list", { limit: 3 })
expect(response.status).to eq(200)
notifications = response.parsed_body.dig("result", "structuredContent", "notifications")
- expect(notifications.pluck("id")).to eq([private_notification.id, other_notification.id])
+ expect(notifications.pluck("id")).to eq(
+ [private_notification.id, group_summary_notification.id, other_notification.id],
+ )
+ expect(
+ notifications.find { |notification| notification["id"] == group_summary_notification.id },
+ ).to include("data" => include("group_name" => group.name, "inbox_count" => 2))
end
it "filters private-message bookmarks before the limit unless the read scope is granted" do
diff --git a/spec/requests/mcp_controller_spec.rb b/spec/requests/mcp_controller_spec.rb
index f49ceb64de3..6e98618e950 100644
--- a/spec/requests/mcp_controller_spec.rb
+++ b/spec/requests/mcp_controller_spec.rb
@@ -78,6 +78,72 @@ describe "MCP transport" do
McpPrimitive.create!(kind: "tool", identifier: "discourse_current_user_get", enabled: true)
end
+ it "filters hidden private-message content before paginating for MCP participants" do
+ participant = Fabricate(:user)
+ author = Fabricate(:user)
+ message = Fabricate(:private_message_post, user: author, recipient: participant)
+ hidden_post =
+ Fabricate(
+ :post,
+ topic: message.topic,
+ user: author,
+ hidden: true,
+ raw: "Restricted PM content",
+ )
+ visible_post = Fabricate(:post, topic: message.topic, user: author)
+ trailing_hidden_post =
+ Fabricate(
+ :post,
+ topic: message.topic,
+ user: author,
+ hidden: true,
+ raw: "Further restricted content",
+ )
+ tool_name = "discourse_read_private_message"
+ McpPrimitive.create!(kind: "tool", identifier: tool_name, enabled: true)
+ group = Fabricate(:group)
+ group.add(participant)
+ group.add(author)
+ McpGroupScope.create!(group: group, scope: "mcp:private-messages:read")
+
+ [participant, author, admin].each do |viewer|
+ grant =
+ DiscourseMcp::OAuth::AuthorizationGrant.create!(
+ user: viewer,
+ client: client,
+ redirect_uri: client.redirect_uris.first,
+ requested_scopes: %w[mcp:profile:read mcp:private-messages:read],
+ )
+ token = McpOauthAccessToken.issue!(authorization: grant)
+ read_payload =
+ payload.deep_merge(
+ params: {
+ name: tool_name,
+ arguments: {
+ topic_id: message.topic_id,
+ start_post_number: hidden_post.post_number,
+ post_limit: 1,
+ },
+ },
+ )
+
+ post "/mcp",
+ params: read_payload.to_json,
+ headers:
+ headers.merge("HTTP_AUTHORIZATION" => "Bearer #{token}", "HTTP_MCP_NAME" => tool_name)
+
+ expect(response.status).to eq(200)
+ result = response.parsed_body.fetch("result").fetch("structuredContent")
+ expected_post = viewer == participant ? visible_post : hidden_post
+ if viewer == participant
+ expect(response.body).not_to include(hidden_post.raw, trailing_hidden_post.raw)
+ end
+ expect(result.fetch("posts").pluck("id")).to eq([expected_post.id])
+ expect(result.fetch("posts").sole.fetch("raw")).to eq(expected_post.raw)
+ expect(result.fetch("meta")).to include("returned" => 1, "has_more" => viewer != participant)
+ end
+ end
+
it "returns a structured internal error when a tool unexpectedly fails" do
failure_message = "private implementation failure"
primitive = DiscourseMcp.registry.find(:tool, "discourse_current_user_get")