Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
281 changes: 281 additions & 0 deletions app/controllers/discourse_member_subdomains/mcp_controller.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,281 @@
# frozen_string_literal: true

require "json"

module ::DiscourseMemberSubdomains
# Streamable HTTP MCP (JSON-RPC 2.0) endpoint at POST /jtech-subdomains/mcp.
# Authenticates via Discourse's built-in User-Api-Key (or Api-Key + Api-Username)
# and enforces the exact same eligibility, rate-limit, validation, and AI review
# rules as the web UI.
class McpController < ::ApplicationController
requires_plugin "jtech-tools"

PROTOCOL_VERSION = "2025-03-26"

TOOLS = [
{
name: "list_subdomains",
description:
"List your claimed DNS-only subdomains, available domain(s), and eligibility limits.",
inputSchema: {
type: "object",
properties: {
},
additionalProperties: false,
},
},
{
name: "claim_subdomain",
description: "Claim a new DNS-only (A, AAAA, or CNAME) subdomain.",
inputSchema: {
type: "object",
properties: {
label: {
type: "string",
description: "Subdomain label (3-32 lowercase letters, numbers, or hyphens).",
},
record_type: {
type: "string",
enum: %w[A AAAA CNAME],
},
target: {
type: "string",
description: "Public IPv4 (A), public IPv6 (AAAA), or public hostname (CNAME).",
},
},
required: %w[label record_type target],
additionalProperties: false,
},
},
{
name: "update_subdomain",
description: "Update the record type and target of an existing subdomain you own.",
inputSchema: {
type: "object",
properties: {
id: {
type: "integer",
description: "Subdomain ID from list_subdomains.",
},
record_type: {
type: "string",
enum: %w[A AAAA CNAME],
},
target: {
type: "string",
description: "New target IP or hostname.",
},
},
required: %w[id record_type target],
additionalProperties: false,
},
},
{
name: "delete_subdomain",
description: "Delete a subdomain you own (staff may revoke any subdomain).",
inputSchema: {
type: "object",
properties: {
id: {
type: "integer",
description: "Subdomain ID from list_subdomains.",
},
},
required: %w[id],
additionalProperties: false,
},
},
].freeze

before_action :ensure_mcp_enabled
before_action :ensure_logged_in

def handle
body = parse_json_body
return render_rpc_error(nil, -32_700, "Invalid JSON") unless body.is_a?(Hash)
Comment on lines +93 to +95

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Register subdomain tools with Discourse's existing MCP server

On Discourse installations with the bundled MCP server, this introduces a second MCP transport instead of using the existing tool registry. The repository already demonstrates the integration in sub_plugins/ads.rb through register_mcp_tool, availability predicates, and required scopes; spec/requests/ads_mcp_spec.rb exercises its OAuth and group-scope authorization. This separate endpoint does not participate in those controls or the existing /mcp tool discovery, requiring agents and administrators to configure another authentication and authorization path. Register the subdomain operations with that server rather than maintaining a parallel JSON-RPC controller, as required by the repository's “Don't rebuild Discourse” rule.

AGENTS.md reference: AGENTS.md:L13-L15

Useful? React with 👍 / 👎.


id = body["id"]
method = body["method"].to_s
rpc_params = body["params"].is_a?(Hash) ? body["params"] : {}

case method
when "initialize"
render_rpc_result(
id,
protocolVersion: PROTOCOL_VERSION,
capabilities: {
tools: {
},
},
serverInfo: {
name: "discourse-member-subdomains",
version: "1.0.0",
},
)
when "notifications/initialized"
head :accepted
when "ping"
render_rpc_result(id, {})
when "tools/list"
render_rpc_result(id, tools: TOOLS)
when "tools/call"
handle_tool_call(id, rpc_params)
else
render_rpc_error(id, -32_601, "Method not found: #{method}")
end
end

private

def ensure_mcp_enabled
unless DiscourseMemberSubdomains.enabled? && SiteSetting.member_subdomains_mcp_enabled
raise Discourse::NotFound
end
end

def parse_json_body
raw = request.raw_post.to_s
return nil if raw.strip.empty?

JSON.parse(raw)
rescue JSON::ParserError
nil
end

def handle_tool_call(id, rpc_params)
if SiteSetting.member_subdomains_staff_only && !current_user.staff?
return render_tool_error(id, "Subdomains are currently restricted to staff.")
end

name = rpc_params["name"].to_s
args = rpc_params["arguments"].is_a?(Hash) ? rpc_params["arguments"] : {}

result =
case name
when "list_subdomains"
tool_list_subdomains
when "claim_subdomain"
tool_claim_subdomain(args)
when "update_subdomain"
tool_update_subdomain(args)
when "delete_subdomain"
tool_delete_subdomain(args)
else
return render_rpc_error(id, -32_602, "Unknown tool: #{name}")
end

render_rpc_result(
id,
content: [{ type: "text", text: JSON.pretty_generate(result) }],
isError: false,
)
rescue ValidationError, ProviderError => e
render_tool_error(id, e.message)
rescue RateLimiter::LimitExceeded => e
render_tool_error(id, e.description.presence || "Rate limit exceeded. Try again shortly.")
rescue Discourse::InvalidAccess => e
render_tool_error(id, e.message.presence || "Not allowed.")
rescue Discourse::NotFound
render_tool_error(id, "Subdomain not found.")
end

def tool_list_subdomains
domains = DiscourseMemberSubdomains.visible_domains
mine =
Subdomain.where(user_id: current_user.id).order(:label).map { |s| serialize(s, domains) }

{
configured: DiscourseMemberSubdomains.configured?,
eligible: DiscourseMemberSubdomains.allowed?(current_user),
min_trust_level: SiteSetting.member_subdomains_min_trust_level,
max_per_user: SiteSetting.member_subdomains_max_per_user,
domains: domains.map(&:name),
allowed_types: Validator::ALLOWED_TYPES,
subdomains: mine,
}
end

def tool_claim_subdomain(args)
ensure_eligible!
enforce_write_rate_limit!

subdomain =
Manager.create!(
user: current_user,
label: args["label"],
record_type: args["record_type"],
target: args["target"],
)

{ subdomain: serialize(subdomain, DiscourseMemberSubdomains.visible_domains) }
end

def tool_update_subdomain(args)
ensure_eligible!
enforce_write_rate_limit!
subdomain = find_manageable_subdomain!(args["id"])

Manager.update!(
subdomain: subdomain,
record_type: args["record_type"],
target: args["target"],
user: current_user,
)

{ subdomain: serialize(subdomain, DiscourseMemberSubdomains.visible_domains) }
end

def tool_delete_subdomain(args)
subdomain = find_manageable_subdomain!(args["id"])
ensure_eligible! unless current_user.staff?
enforce_write_rate_limit!

Manager.destroy!(subdomain: subdomain)
{ deleted: true, id: subdomain.id, label: subdomain.label }
end

def ensure_eligible!
return if DiscourseMemberSubdomains.allowed?(current_user)

raise Discourse::InvalidAccess.new("Not allowed to manage subdomains.")
end

def enforce_write_rate_limit!
limit = current_user.staff? ? 30 : 10
RateLimiter.new(current_user, "member-subdomains-write", limit, 1.minute).performed!
end

def find_manageable_subdomain!(raw_id)
subdomain = Subdomain.find_by(id: raw_id)
raise Discourse::NotFound unless subdomain

unless subdomain.user_id == current_user.id || current_user.staff?
raise Discourse::InvalidAccess.new("Cannot manage another user's subdomain.")
end

subdomain
end

def serialize(subdomain, domains)
{
id: subdomain.id,
label: subdomain.label,
record_type: subdomain.record_type,
target: subdomain.target,
fqdns: subdomain.fqdns(domains),
}
end

def render_rpc_result(id, result)
render json: { jsonrpc: "2.0", id: id, result: result }
end

def render_rpc_error(id, code, message)
render json: { jsonrpc: "2.0", id: id, error: { code: code, message: message } }
end

def render_tool_error(id, message)
render_rpc_result(id, content: [{ type: "text", text: message }], isError: true)
end
end
end
6 changes: 6 additions & 0 deletions config/locales/server.en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,12 @@ en:
use for subdomain safety review. Leave at 0 to use the site's default LLM
model automatically.

member_subdomains_mcp_enabled: Expose a Streamable HTTP MCP (JSON-RPC 2.0)
endpoint at /jtech-subdomains/mcp so AI agents can list, claim, update,
and delete subdomains on a member's behalf using a Discourse User API Key
(User-Api-Key header). Enforces all trust-level, rate-limit, validation,
and AI review checks.

jtech_lean_palettes: Send the colour palettes in every page with only the
colours their previews and swatches use (primary, secondary, tertiary,
selected, header background and header text) instead of all of them.
Expand Down
1 change: 1 addition & 0 deletions config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,7 @@ def matches?(req)
post "/" => "subdomains#create"
put "/:id" => "subdomains#update"
delete "/:id" => "subdomains#destroy"
post "/mcp" => "mcp#handle"
end

get "/subdomains" => "discourse_member_subdomains/subdomains#page"
Expand Down
5 changes: 5 additions & 0 deletions config/settings.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2008,3 +2008,8 @@ jtech_discord_chat:
client: false
depends_on:
- "member_subdomains_enabled"
member_subdomains_mcp_enabled:
default: true
client: false
depends_on:
- "member_subdomains_enabled"
Loading
Loading