Skip to content

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

FIX: Improve MCP OAuth callback error handling (#38889)

Sama9bf76af1c10
diff --git a/config/initializers/000-zeitwerk.rb b/config/initializers/000-zeitwerk.rb
index 5dcdb8eaf74..81991bb7fc3 100644
--- a/config/initializers/000-zeitwerk.rb
+++ b/config/initializers/000-zeitwerk.rb
@@ -43,6 +43,7 @@ Rails.autoloaders.each do |autoloader|
"json" => "JSON",
"ssrf_detector" => "SSRFDetector",
"http" => "HTTP",
+ "oauth_client_registration" => "OAuthClientRegistration",
"oauth_discovery" => "OAuthDiscovery",
"oauth_flow" => "OAuthFlow",
"oauth_token_store" => "OAuthTokenStore",
diff --git a/frontend/discourse/admin/services/admin-search-data-source.js b/frontend/discourse/admin/services/admin-search-data-source.js
index b8144b760f5..99d76736248 100644
--- a/frontend/discourse/admin/services/admin-search-data-source.js
+++ b/frontend/discourse/admin/services/admin-search-data-source.js
@@ -283,11 +283,11 @@ export default class AdminSearchDataSource extends Service {
const labelPartialRegex = new RegExp(`\\b${escapedFilterRegExp}`, "i");
const exactKeywordRegexes = escapedFilterRegExp
.split(" ")
- .filter((keyword) => keyword.length > 3)
+ .filter((keyword) => keyword.length >= 3)
.map((keyword) => new RegExp(`(${keyword})\\b`, "i"));
const partialKeywordRegexes = escapedFilterRegExp
.split(" ")
- .filter((keyword) => keyword.length > 3)
+ .filter((keyword) => keyword.length >= 3)
.map((keyword) => new RegExp(`\\b${keyword}`, "i"));
const fallbackRegex = new RegExp(`${escapedFilterRegExp}`, "i");
@@ -316,7 +316,10 @@ export default class AdminSearchDataSource extends Service {
) {
dataSourceItem.score += SEARCH_SCORES.partialKeyword;
}
- if (filter.length > 3 && dataSourceItem.keywords.match(fallbackRegex)) {
+ if (
+ filter.length >= 3 &&
+ dataSourceItem.keywords.match(fallbackRegex)
+ ) {
dataSourceItem.score += SEARCH_SCORES.fallback;
}
diff --git a/frontend/discourse/tests/unit/services/admin-search-data-source-test.js b/frontend/discourse/tests/unit/services/admin-search-data-source-test.js
index 9da3493dccb..6fbe35d26e6 100644
--- a/frontend/discourse/tests/unit/services/admin-search-data-source-test.js
+++ b/frontend/discourse/tests/unit/services/admin-search-data-source-test.js
@@ -194,6 +194,34 @@ module("Unit | Service | AdminSearchDataSource", function (hooks) {
assert.deepEqual(results[0].label, "About your site > Title");
});
+ test("search - matches 3-character keywords like acronyms", async function (assert) {
+ this.subject.componentDataSourceItems = [];
+ this.subject.reportDataSourceItems = [];
+ this.subject.themeDataSourceItems = [];
+ this.subject.settingDataSourceItems = [];
+ this.subject.pageDataSourceItems = [
+ {
+ description: "Tools and MCP servers",
+ icon: "gear",
+ keywords: "mcp mcp server model context protocol",
+ label: "Plugins > Tools",
+ type: "page",
+ url: "/admin/plugins/discourse-ai/ai-tools",
+ },
+ {
+ description: "Unrelated page",
+ icon: "gear",
+ keywords: "something else entirely",
+ label: "Other Page",
+ type: "page",
+ url: "/admin/other",
+ },
+ ];
+ let results = this.subject.search("mcp");
+ assert.strictEqual(results.length, 1);
+ assert.strictEqual(results[0].label, "Plugins > Tools");
+ });
+
test("search - prioritize pages", async function (assert) {
this.subject.componentDataSourceItems = [];
this.subject.reportDataSourceItems = [];
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_mcp_servers_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_mcp_servers_controller.rb
index dab696f2d3a..dccdfa6ac3e 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_mcp_servers_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_mcp_servers_controller.rb
@@ -48,8 +48,14 @@ module DiscourseAi
def update
initial_attributes = @ai_mcp_server.attributes.dup
+ update_params = ai_mcp_server_params
- if @ai_mcp_server.update(ai_mcp_server_params)
+ if @ai_mcp_server.oauth? && update_params[:oauth_client_registration] != "manual" &&
+ @ai_mcp_server.oauth_client_registration != "manual"
+ update_params = update_params.except(:oauth_client_id, :oauth_client_secret_ai_secret_id)
+ end
+
+ if @ai_mcp_server.update(update_params)
log_ai_mcp_server_update(@ai_mcp_server, initial_attributes)
render json: AiMcpServerSerializer.new(@ai_mcp_server)
else
@@ -87,9 +93,19 @@ module DiscourseAi
ai_mcp_server =
DiscourseAi::Mcp::OAuthFlow.complete!(params: params, current_user: current_user)
redirect_to ai_mcp_server.admin_edit_url
- rescue StandardError => e
- Rails.logger.warn("Discourse AI MCP OAuth callback failed: #{e.message}")
- redirect_to "/admin/plugins/discourse-ai/ai-tools"
+ rescue DiscourseAi::Mcp::OAuthFlow::OAuthError => e
+ Rails.logger.warn(
+ "Discourse AI MCP OAuth callback failed: #{e.message} (#{e.cause&.class}: #{e.cause&.message})",
+ )
+ if e.server.present?
+ redirect_to e.server.admin_edit_url
+ else
+ flash[:error] = I18n.t(
+ "discourse_ai.mcp_servers.errors.oauth_callback_failed",
+ message: e.message,
+ )
+ redirect_to "/admin/plugins/discourse-ai/ai-tools"
+ end
end
def oauth_disconnect
@@ -103,11 +119,9 @@ module DiscourseAi
persisted_server = params[:id].present? ? AiMcpServer.find(params[:id]) : nil
ai_mcp_server = persisted_server || AiMcpServer.new
ai_mcp_server.assign_attributes(ai_mcp_server_params)
+ restore_dynamic_oauth_credentials!(ai_mcp_server, persisted_server)
return render_json_error ai_mcp_server if !ai_mcp_server.valid?
- if oauth_reauthorization_required_for_test?(ai_mcp_server)
- ai_mcp_server = sanitized_oauth_test_server(ai_mcp_server)
- end
if ai_mcp_server.oauth? && persisted_server.blank?
return(
@@ -118,6 +132,20 @@ module DiscourseAi
)
end
+ # For connected OAuth servers, use the persisted record directly so
+ # the token association is intact. Form params may dirty fields
+ # (e.g. "" vs nil) causing false reauth detection.
+ # However, if OAuth-relevant fields changed, build an ephemeral server
+ # without stale tokens so the new configuration is tested cleanly.
+ if persisted_server&.oauth? && persisted_server.oauth_status == "connected"
+ if (ai_mcp_server.changes.keys & AiMcpServer::OAUTH_REAUTH_TRIGGER_FIELDS).any?
+ ai_mcp_server = AiMcpServer.new(ai_mcp_server_params)
+ restore_dynamic_oauth_credentials!(ai_mcp_server, persisted_server)
+ else
+ ai_mcp_server = persisted_server.reload
+ end
+ end
+
client = DiscourseAi::Mcp::Client.new(ai_mcp_server)
initialized = client.initialize_session
tools = client.list_tools(session_id: initialized[:session_id])
@@ -250,21 +278,13 @@ module DiscourseAi
logger.log_deletion("mcp_server", details)
end
- def oauth_reauthorization_required_for_test?(ai_mcp_server)
- return false if !ai_mcp_server.oauth? || !ai_mcp_server.persisted?
+ def restore_dynamic_oauth_credentials!(ai_mcp_server, persisted_server)
+ return if persisted_server.blank? || !ai_mcp_server.oauth?
+ return if ai_mcp_server.oauth_client_registration == "manual"
- (ai_mcp_server.changes_to_save.keys & AiMcpServer::OAUTH_REAUTH_TRIGGER_FIELDS).present?
- end
-
- def sanitized_oauth_test_server(ai_mcp_server)
- ai_mcp_server.dup.tap do |server|
- server.oauth_status = "disconnected"
- server.oauth_access_token_expires_at = nil
- server.oauth_token_type = nil
- server.oauth_last_error = nil
- server.oauth_last_authorized_at = nil
- server.oauth_last_refreshed_at = nil
- end
+ ai_mcp_server.oauth_client_id = persisted_server.oauth_client_id
+ ai_mcp_server.oauth_client_secret_ai_secret_id =
+ persisted_server.oauth_client_secret_ai_secret_id
end
end
end
diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/mcp_oauth_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/mcp_oauth_controller.rb
index 6f412a3ef6b..c4f8257e646 100644
--- a/plugins/discourse-ai/app/controllers/discourse_ai/mcp_oauth_controller.rb
+++ b/plugins/discourse-ai/app/controllers/discourse_ai/mcp_oauth_controller.rb
@@ -5,6 +5,7 @@ module DiscourseAi
requires_plugin PLUGIN_NAME
skip_before_action :check_xhr, only: :client_metadata
skip_before_action :preload_json, only: :client_metadata
+ skip_before_action :redirect_to_login_if_required, only: :client_metadata
def client_metadata
render json: {
diff --git a/plugins/discourse-ai/app/models/ai_mcp_server.rb b/plugins/discourse-ai/app/models/ai_mcp_server.rb
index 4275e988fb6..ad5b9767955 100644
--- a/plugins/discourse-ai/app/models/ai_mcp_server.rb
+++ b/plugins/discourse-ai/app/models/ai_mcp_server.rb
@@ -61,7 +61,7 @@ class AiMcpServer < ActiveRecord::Base
token = oauth_token_store.access_token
return nil if token.blank?
- token_type = oauth_token_type.presence || "Bearer"
+ token_type = oauth_token_type.presence&.capitalize || "Bearer"
return "#{token_type} #{token}"
end
@@ -166,7 +166,7 @@ class AiMcpServer < ActiveRecord::Base
if oauth_client_registration == "manual"
oauth_client_id.presence
else
- oauth_client_metadata_url
+ oauth_client_id.presence || oauth_client_metadata_url
end
end
@@ -184,6 +184,7 @@ class AiMcpServer < ActiveRecord::Base
authorization_endpoint: oauth_authorization_endpoint,
token_endpoint: oauth_token_endpoint,
revocation_endpoint: oauth_revocation_endpoint,
+ registration_endpoint: oauth_registration_endpoint,
)
end
@@ -192,6 +193,7 @@ class AiMcpServer < ActiveRecord::Base
oauth_authorization_endpoint: discovery.authorization_endpoint,
oauth_token_endpoint: discovery.token_endpoint,
oauth_revocation_endpoint: discovery.revocation_endpoint,
+ oauth_registration_endpoint: discovery.registration_endpoint,
oauth_issuer: discovery.issuer,
oauth_resource_metadata_url: discovery.resource_metadata_url,
oauth_last_error: nil,
@@ -213,6 +215,21 @@ class AiMcpServer < ActiveRecord::Base
)
end
+ def store_dynamic_registration!(client_id:, client_secret: nil)
+ columns = { oauth_client_id: client_id }
+ if client_secret.present?
+ secret =
+ AiSecret
+ .find_or_initialize_by(name: "mcp_dynamic_#{id}_client_secret")
+ .tap do |s|
+ s.secret = client_secret
+ s.save!
+ end
+ columns[:oauth_client_secret_ai_secret_id] = secret.id
+ end
+ update_columns(columns)
+ end
+
def mark_oauth_authorized!
update_columns(
oauth_status: "connected",
@@ -232,7 +249,7 @@ class AiMcpServer < ActiveRecord::Base
def clear_oauth_credentials!
oauth_token_store.clear!
- update_columns(
+ columns = {
oauth_status: "disconnected",
oauth_token_type: nil,
oauth_access_token_expires_at: nil,
@@ -240,12 +257,15 @@ class AiMcpServer < ActiveRecord::Base
oauth_authorization_endpoint: nil,
oauth_token_endpoint: nil,
oauth_revocation_endpoint: nil,
+ oauth_registration_endpoint: nil,
oauth_issuer: nil,
oauth_resource_metadata_url: nil,
oauth_last_error: nil,
oauth_last_authorized_at: nil,
oauth_last_refreshed_at: nil,
- )
+ }
+ columns[:oauth_client_id] = nil if oauth_client_registration != "manual"
+ update_columns(columns)
end
def oauth_token_store
@@ -316,9 +336,6 @@ class AiMcpServer < ActiveRecord::Base
if !oauth?
self.oauth_client_registration =
oauth_client_registration.presence || "client_metadata_document"
- elsif oauth_client_registration != "manual"
- self.oauth_client_id = nil
- self.oauth_client_secret_ai_secret_id = nil
end
self.ai_secret_id = nil if !header_secret?
@@ -412,6 +429,7 @@ end
# oauth_last_authorized_at :datetime
# oauth_last_error :string(1000)
# oauth_last_refreshed_at :datetime
+# oauth_registration_endpoint :string(1000)
# oauth_resource_metadata_url :string(1000)
# oauth_revocation_endpoint :string(1000)
# oauth_scopes :string(2000)
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-mcp-server-editor-form.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-mcp-server-editor-form.gjs
index 7363ab515cb..4c420cd3a12 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-mcp-server-editor-form.gjs
+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-mcp-server-editor-form.gjs
@@ -22,6 +22,7 @@ export default class AiMcpServerEditorForm extends Component {
@tracked isDisconnecting = false;
@tracked testResult = null;
@tracked formData = {};
+ @tracked showOauthDetails = false;
constructor() {
super(...arguments);
@@ -227,6 +228,11 @@ export default class AiMcpServerEditorForm extends Component {
}
}
+ @action
+ toggleOauthDetails() {
+ this.showOauthDetails = !this.showOauthDetails;
+ }
+
@action
delete() {
return this.dialog.confirm({
@@ -413,87 +419,6 @@ export default class AiMcpServerEditorForm extends Component {
</span>
</div>
- {{#if @model.oauth_client_metadata_url}}
- <div class="ai-mcp-server-editor__oauth-row">
- <span class="ai-mcp-server-editor__oauth-label">
- {{i18n "discourse_ai.mcp_servers.oauth_client_metadata_url"}}
- </span>
- <code class="ai-mcp-server-editor__oauth-value">
- {{@model.oauth_client_metadata_url}}
- </code>
- </div>
- {{/if}}
-
- {{#if @model.oauth_granted_scopes}}
- <div class="ai-mcp-server-editor__oauth-row">
- <span class="ai-mcp-server-editor__oauth-label">
- {{i18n "discourse_ai.mcp_servers.oauth_granted_scopes"}}
- </span>
- <span class="ai-mcp-server-editor__oauth-value">
- {{@model.oauth_granted_scopes}}
- </span>
- </div>
- {{/if}}
-
- {{#if @model.oauth_access_token_expires_at}}
- <div class="ai-mcp-server-editor__oauth-row">
- <span class="ai-mcp-server-editor__oauth-label">
- {{i18n
- "discourse_ai.mcp_servers.oauth_access_token_expires_at"
- }}
- </span>
- <span class="ai-mcp-server-editor__oauth-value">
- {{@model.oauth_access_token_expires_at}}
- </span>
- </div>
- {{/if}}
-
- {{#if @model.oauth_issuer}}
- <div class="ai-mcp-server-editor__oauth-row">
- <span class="ai-mcp-server-editor__oauth-label">
- {{i18n "discourse_ai.mcp_servers.oauth_issuer"}}
- </span>
- <span class="ai-mcp-server-editor__oauth-value">
- {{@model.oauth_issuer}}
- </span>
- </div>
- {{/if}}
-
- {{#if @model.oauth_authorization_endpoint}}
- <div class="ai-mcp-server-editor__oauth-row">
- <span class="ai-mcp-server-editor__oauth-label">
- {{i18n
- "discourse_ai.mcp_servers.oauth_authorization_endpoint"
- }}
- </span>
- <code class="ai-mcp-server-editor__oauth-value">
- {{@model.oauth_authorization_endpoint}}
- </code>
- </div>
- {{/if}}
-
- {{#if @model.oauth_token_endpoint}}
- <div class="ai-mcp-server-editor__oauth-row">
- <span class="ai-mcp-server-editor__oauth-label">
- {{i18n "discourse_ai.mcp_servers.oauth_token_endpoint"}}
- </span>
- <code class="ai-mcp-server-editor__oauth-value">
- {{@model.oauth_token_endpoint}}
- </code>
- </div>
- {{/if}}
-
- {{#if @model.oauth_revocation_endpoint}}
- <div class="ai-mcp-server-editor__oauth-row">
- <span class="ai-mcp-server-editor__oauth-label">
- {{i18n "discourse_ai.mcp_servers.oauth_revocation_endpoint"}}
- </span>
- <code class="ai-mcp-server-editor__oauth-value">
- {{@model.oauth_revocation_endpoint}}
- </code>
- </div>
- {{/if}}
-
{{#if @model.oauth_last_error}}
<div class="ai-mcp-server-editor__oauth-row">
<span class="ai-mcp-server-editor__oauth-label">
@@ -504,6 +429,103 @@ export default class AiMcpServerEditorForm extends Component {
</span>
</div>
{{/if}}
+
+ {{#if this.showOauthDetails}}
+ {{#if @model.oauth_client_metadata_url}}
+ <div class="ai-mcp-server-editor__oauth-row">
+ <span class="ai-mcp-server-editor__oauth-label">
+ {{i18n
+ "discourse_ai.mcp_servers.oauth_client_metadata_url"
+ }}
+ </span>
+ <code class="ai-mcp-server-editor__oauth-value">
+ {{@model.oauth_client_metadata_url}}
+ </code>
+ </div>
+ {{/if}}
+
+ {{#if @model.oauth_granted_scopes}}
+ <div class="ai-mcp-server-editor__oauth-row">
+ <span class="ai-mcp-server-editor__oauth-label">
+ {{i18n "discourse_ai.mcp_servers.oauth_granted_scopes"}}
+ </span>
+ <span class="ai-mcp-server-editor__oauth-value">
+ {{@model.oauth_granted_scopes}}
+ </span>
+ </div>
+ {{/if}}
+
+ {{#if @model.oauth_access_token_expires_at}}
+ <div class="ai-mcp-server-editor__oauth-row">
+ <span class="ai-mcp-server-editor__oauth-label">
+ {{i18n
+ "discourse_ai.mcp_servers.oauth_access_token_expires_at"
+ }}
+ </span>
+ <span class="ai-mcp-server-editor__oauth-value">
+ {{@model.oauth_access_token_expires_at}}
+ </span>
+ </div>
+ {{/if}}
+
+ {{#if @model.oauth_issuer}}
+ <div class="ai-mcp-server-editor__oauth-row">
+ <span class="ai-mcp-server-editor__oauth-label">
+ {{i18n "discourse_ai.mcp_servers.oauth_issuer"}}
+ </span>
+ <span class="ai-mcp-server-editor__oauth-value">
+ {{@model.oauth_issuer}}
+ </span>
+ </div>
+ {{/if}}
+
+ {{#if @model.oauth_authorization_endpoint}}
+ <div class="ai-mcp-server-editor__oauth-row">
+ <span class="ai-mcp-server-editor__oauth-label">
+ {{i18n
+ "discourse_ai.mcp_servers.oauth_authorization_endpoint"
+ }}
+ </span>
+ <code class="ai-mcp-server-editor__oauth-value">
+ {{@model.oauth_authorization_endpoint}}
+ </code>
+ </div>
+ {{/if}}
+
+ {{#if @model.oauth_token_endpoint}}
+ <div class="ai-mcp-server-editor__oauth-row">
+ <span class="ai-mcp-server-editor__oauth-label">
+ {{i18n "discourse_ai.mcp_servers.oauth_token_endpoint"}}
+ </span>
+ <code class="ai-mcp-server-editor__oauth-value">
+ {{@model.oauth_token_endpoint}}
+ </code>
+ </div>
+ {{/if}}
+
+ {{#if @model.oauth_revocation_endpoint}}
+ <div class="ai-mcp-server-editor__oauth-row">
+ <span class="ai-mcp-server-editor__oauth-label">
+ {{i18n
+ "discourse_ai.mcp_servers.oauth_revocation_endpoint"
+ }}
+ </span>
+ <code class="ai-mcp-server-editor__oauth-value">
+ {{@model.oauth_revocation_endpoint}}
+ </code>
+ </div>
+ {{/if}}
+ {{/if}}
+
+ <form.Button
+ @action={{this.toggleOauthDetails}}
+ @label={{if
+ this.showOauthDetails
+ "discourse_ai.mcp_servers.oauth_hide_details"
+ "discourse_ai.mcp_servers.oauth_show_details"
+ }}
+ class="btn-flat btn-small ai-mcp-server-editor__oauth-details-toggle"
+ />
</div>
{{/unless}}
{{/if}}
diff --git a/plugins/discourse-ai/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js b/plugins/discourse-ai/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js
index 6c8d5d5b818..1fcab47f56c 100644
--- a/plugins/discourse-ai/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js
+++ b/plugins/discourse-ai/assets/javascripts/discourse/initializers/admin-plugin-configuration-nav.js
@@ -48,6 +48,7 @@ export default {
label: "discourse_ai.tools.short_title",
route: "adminPlugins.show.discourse-ai-tools",
description: "discourse_ai.tools.subheader_description",
+ keywords: "discourse_ai.tools.keywords",
},
{
label: "discourse_ai.spam.short_title",
diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.yml
index fad93df189d..3180d81b5ef 100644
--- a/plugins/discourse-ai/config/locales/client.en.yml
+++ b/plugins/discourse-ai/config/locales/client.en.yml
@@ -688,6 +688,7 @@ en:
tools:
back: "Back to tools"
short_title: "Tools"
+ keywords: "mcp|mcp server|model context protocol"
script_tools: "Script tools"
export: "Export"
import: "Import"
@@ -801,6 +802,8 @@ en:
oauth_revocation_endpoint: "Revocation endpoint"
oauth_issuer: "Issuer"
oauth_last_error: "Last OAuth error"
+ oauth_show_details: "Show details"
+ oauth_hide_details: "Hide details"
timeout_seconds: "Request timeout (seconds)"
timeout_seconds_tooltip: "How long Discourse waits for the MCP server before the request fails. Keep 30 unless the server is consistently slow."
enabled: "Enabled"
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.yml
index fadb1fe33d2..e2481a3b5bd 100644
--- a/plugins/discourse-ai/config/locales/server.en.yml
+++ b/plugins/discourse-ai/config/locales/server.en.yml
@@ -325,7 +325,11 @@ en:
oauth_state_invalid: "The OAuth authorization state is invalid or has expired. Start the connection again."
oauth_token_exchange_failed: "The OAuth token exchange failed with status %{status}."
oauth_https_required: "OAuth requires your site to be served over HTTPS."
+ oauth_callback_failed: "OAuth connection failed: %{message}"
oauth_client_metadata_public_https_required: "Client metadata document registration requires a public HTTPS site URL. Current client metadata URL: %{url}"
+ oauth_registration_endpoint_missing: "The OAuth authorization server does not advertise a registration endpoint."
+ oauth_client_registration_failed: "Dynamic client registration failed with status %{status}."
+ oauth_client_registration_failed_no_id: "Dynamic client registration succeeded but no client_id was returned."
ai_helper:
errors:
diff --git a/plugins/discourse-ai/db/migrate/20260326000000_add_registration_endpoint_to_ai_mcp_servers.rb b/plugins/discourse-ai/db/migrate/20260326000000_add_registration_endpoint_to_ai_mcp_servers.rb
new file mode 100644
index 00000000000..bff04bcb0cc
--- /dev/null
+++ b/plugins/discourse-ai/db/migrate/20260326000000_add_registration_endpoint_to_ai_mcp_servers.rb
@@ -0,0 +1,7 @@
+# frozen_string_literal: true
+
+class AddRegistrationEndpointToAiMcpServers < ActiveRecord::Migration[7.2]
+ def change
+ add_column :ai_mcp_servers, :oauth_registration_endpoint, :string, limit: 1000
+ end
+end
diff --git a/plugins/discourse-ai/lib/mcp/oauth_client_registration.rb b/plugins/discourse-ai/lib/mcp/oauth_client_registration.rb
new file mode 100644
index 00000000000..a46ff79f2e2
--- /dev/null
+++ b/plugins/discourse-ai/lib/mcp/oauth_client_registration.rb
@@ -0,0 +1,89 @@
+# frozen_string_literal: true
+
+module DiscourseAi
+ module Mcp
+ class OAuthClientRegistration
+ class << self
+ def register!(server:, discovery:)
+ endpoint = discovery.registration_endpoint
+ if endpoint.blank?
+ raise DiscourseAi::Mcp::Client::Error,
+ I18n.t("discourse_ai.mcp_servers.errors.oauth_registration_endpoint_missing")
+ end
+
+ validate_endpoint!(endpoint)
+
+ metadata = build_client_metadata(server)
+
+ connection =
+ Faraday.new(request: { timeout: server.timeout_seconds }) do |builder|
+ builder.request :json
+ builder.adapter FinalDestination::FaradayAdapter
+ end
+
+ response = connection.post(endpoint, metadata, { "Accept" => "application/json" })
+
+ if response.status != 201 && response.status != 200
+ message =
+ begin
+ parsed = JSON.parse(response.body)
+ parsed["error_description"] || parsed["error"]
+ rescue StandardError
+ nil
+ end
+ raise DiscourseAi::Mcp::Client::Error,
+ message.presence ||
+ I18n.t(
+ "discourse_ai.mcp_servers.errors.oauth_client_registration_failed",
+ status: response.status,
+ )
+ end
+
+ registration = JSON.parse(response.body)
+ client_id = registration["client_id"]
+ if client_id.blank?
+ raise DiscourseAi::Mcp::Client::Error,
+ I18n.t("discourse_ai.mcp_servers.errors.oauth_client_registration_failed_no_id")
+ end
+
+ server.store_dynamic_registration!(
+ client_id: client_id,
+ client_secret: registration["client_secret"],
+ )
+
+ registration
+ rescue JSON::ParserError
+ raise DiscourseAi::Mcp::Client::Error,
+ I18n.t("discourse_ai.mcp_servers.errors.invalid_response")
+ end
+
+ private
+
+ def build_client_metadata(server)
+ {
+ client_name: SiteSetting.title.presence || "Discourse AI MCP Client",
+ redirect_uris: [server.oauth_callback_url],
+ grant_types: %w[authorization_code refresh_token],
+ response_types: ["code"],
+ application_type: "web",
+ token_endpoint_auth_method: "none",
+ scope: server.oauth_scopes.presence,
+ }.compact
+ end
+
+ def validate_endpoint!(url)
+ uri = AiMcpServer.parse_public_uri(url)
+ if uri.nil?
+ raise DiscourseAi::Mcp::Client::Error,
+ I18n.t("discourse_ai.mcp_servers.invalid_url_not_https")
+ end
+
+ AiMcpServer.validate_hostname_public!(uri.hostname)
+ rescue FinalDestination::SSRFError, SocketError, URI::InvalidURIError
+ raise DiscourseAi::Mcp::Client::Error,
+ I18n.t("discourse_ai.mcp_servers.invalid_url_not_reachable")
+ end
+ end
+ end
+ end
+end
diff --git a/plugins/discourse-ai/lib/mcp/oauth_discovery.rb b/plugins/discourse-ai/lib/mcp/oauth_discovery.rb
index e6cca82d769..3137c82bc3a 100644
--- a/plugins/discourse-ai/lib/mcp/oauth_discovery.rb
+++ b/plugins/discourse-ai/lib/mcp/oauth_discovery.rb
@@ -11,6 +11,7 @@ module DiscourseAi
:authorization_endpoint,
:token_endpoint,
:revocation_endpoint,
+ :registration_endpoint,
keyword_init: true,
)
@@ -45,6 +46,9 @@ module DiscourseAi
revocation_endpoint = auth_server_metadata["revocation_endpoint"].presence
validate_discovered_url!(revocation_endpoint) if revocation_endpoint.present?
+ registration_endpoint = auth_server_metadata["registration_endpoint"].presence
+ validate_discovered_url!(registration_endpoint) if registration_endpoint.present?
+
Result.new(
resource: resource_metadata["resource"].presence || server.url,
resource_metadata_url: resource_metadata_url,
@@ -52,6 +56,7 @@ module DiscourseAi
authorization_endpoint: authorization_endpoint,
token_endpoint: token_endpoint,
revocation_endpoint: revocation_endpoint,
+ registration_endpoint: registration_endpoint,
)
end
diff --git a/plugins/discourse-ai/lib/mcp/oauth_flow.rb b/plugins/discourse-ai/lib/mcp/oauth_flow.rb
index b8e404fc12d..8f3105f3002 100644
--- a/plugins/discourse-ai/lib/mcp/oauth_flow.rb
+++ b/plugins/discourse-ai/lib/mcp/oauth_flow.rb
@@ -8,6 +8,16 @@ module DiscourseAi
class OAuthFlow
STATE_TTL = 10.minutes
+ OAuthError =
+ Class.new(StandardError) do
+ attr_reader :server
+
+ def initialize(message = nil, server: nil)
+ @server = server
+ super(message)
+ end
+ end
+
class << self
def start!(server:, user:)
validate_local_oauth_urls!(server)
@@ -15,6 +25,12 @@ module DiscourseAi
discovery = OAuthDiscovery.discover!(server)
server.store_oauth_discovery!(discovery)
+ if server.oauth_client_registration != "manual" && server.oauth_client_id.blank? &&
+ discovery.registration_endpoint.present?
+ OAuthClientRegistration.register!(server: server, discovery: discovery)
+ server.reload
+ end
+
state = SecureRandom.hex(32)
code_verifier = generate_code_verifier
Rails.cache.write(
@@ -73,7 +89,7 @@ module DiscourseAi
server
rescue StandardError => e
server&.mark_oauth_error!(e.message)
- raise
+ raise OAuthError.new(e.message, server: server), cause: e
end
def refresh!(server)
@@ -156,8 +172,7 @@ module DiscourseAi
validate_endpoint!(endpoint)
headers = { "Accept" => "application/json" }
- if server.oauth_client_registration == "manual" &&
- server.oauth_client_secret_value.present?
+ if server.oauth_client_secret_value.present?
headers["Authorization"] = basic_auth_header(
server.effective_oauth_client_id,
server.oauth_client_secret_value,
@@ -216,8 +231,7 @@ module DiscourseAi
end
headers = { "Accept" => "application/json" }
- if server.oauth_client_registration == "manual" &&
- server.oauth_client_secret_value.present?
+ if server.oauth_client_secret_value.present?
headers["Authorization"] = basic_auth_header(
server.effective_oauth_client_id,
server.oauth_client_secret_value,
diff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rb
index e381a93a7b1..cd103ec4968 100644
--- a/plugins/discourse-ai/plugin.rb
+++ b/plugins/discourse-ai/plugin.rb
@@ -71,6 +71,7 @@ require_relative "lib/engine"
require_relative "lib/configuration/module"
require_relative "lib/mcp/oauth_token_store"
require_relative "lib/mcp/oauth_discovery"
+require_relative "lib/mcp/oauth_client_registration"
require_relative "lib/mcp/oauth_flow"
DiscourseAi::Configuration::Module::NAMES.each do |module_name|
diff --git a/plugins/discourse-ai/spec/lib/mcp/oauth_client_registration_spec.rb b/plugins/discourse-ai/spec/lib/mcp/oauth_client_registration_spec.rb
new file mode 100644
index 00000000000..6b15d14918d
--- /dev/null
+++ b/plugins/discourse-ai/spec/lib/mcp/oauth_client_registration_spec.rb
@@ -0,0 +1,140 @@
+# frozen_string_literal: true
+
+RSpec.describe DiscourseAi::Mcp::OAuthClientRegistration do
+ fab!(:ai_mcp_server) { Fabricate(:ai_mcp_server, auth_type: "oauth") }
+
+ before do
+ enable_current_plugin
+ AiMcpServer.stubs(:validate_hostname_public!).returns(true)
+ end
+
+ let(:registration_endpoint) { "https://auth.example.com/register" }
+
+ let(:discovery) do
+ DiscourseAi::Mcp::OAuthDiscovery::Result.new(
+ resource: ai_mcp_server.url,
+ resource_metadata_url: "#{ai_mcp_server.url}/.well-known/oauth-protected-resource",
+ issuer: "https://auth.example.com",
+ authorization_endpoint: "https://auth.example.com/authorize",
+ token_endpoint: "https://auth.example.com/token",
+ revocation_endpoint: nil,
+ registration_endpoint: registration_endpoint,
+ )
+ end
+
+ describe ".register!" do
+ it "sends client metadata and stores the returned client_id" do
+ stub_request(:post, registration_endpoint).to_return(
+ status: 201,
+ body: { client_id: "dynamic-client-id-123" }.to_json,
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
+
+ result = described_class.register!(server: ai_mcp_server, discovery: discovery)
+
+ expect(result["client_id"]).to eq("dynamic-client-id-123")
+ expect(ai_mcp_server.reload.oauth_client_id).to eq("dynamic-client-id-123")
+
+ expect(
+ a_request(:post, registration_endpoint).with do |request|
+ body = JSON.parse(request.body)
+ body["redirect_uris"] == [ai_mcp_server.oauth_callback_url] &&
+ body["grant_types"] == %w[authorization_code refresh_token] &&
+ body["response_types"] == ["code"] && body["token_endpoint_auth_method"] == "none"
+ end,
+ ).to have_been_made.once
+ end
+
+ it "stores a dynamically issued client_secret" do
+ stub_request(:post, registration_endpoint).to_return(
+ status: 201,
+ body: { client_id: "dynamic-client-id", client_secret: "dynamic-secret-value" }.to_json,
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
+
+ described_class.register!(server: ai_mcp_server, discovery: discovery)
+
+ ai_mcp_server.reload
+ expect(ai_mcp_server.oauth_client_id).to eq("dynamic-client-id")
+ expect(ai_mcp_server.oauth_client_secret_value).to eq("dynamic-secret-value")
+ end
+
+ it "includes scope when configured on the server" do
+ ai_mcp_server.update_columns(oauth_scopes: "read write")
+
+ stub_request(:post, registration_endpoint).to_return(
+ status: 201,
+ body: { client_id: "scoped-client" }.to_json,
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
+
+ described_class.register!(server: ai_mcp_server, discovery: discovery)
+
+ expect(
+ a_request(:post, registration_endpoint).with do |request|
+ JSON.parse(request.body)["scope"] == "read write"
+ end,
+ ).to have_been_made.once
+ end
+
+ it "raises when the registration endpoint returns an error" do
+ stub_request(:post, registration_endpoint).to_return(
+ status: 400,
+ body: {
+ error: "invalid_client_metadata",
+ error_description: "Invalid redirect URI",
+ }.to_json,
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
+
+ expect {
+ described_class.register!(server: ai_mcp_server, discovery: discovery)
+ }.to raise_error(DiscourseAi::Mcp::Client::Error, "Invalid redirect URI")
+ end
+
+ it "raises when no client_id is returned" do
+ stub_request(:post, registration_endpoint).to_return(
+ status: 201,
+ body: { client_name: "test" }.to_json,
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
+
+ expect {
+ described_class.register!(server: ai_mcp_server, discovery: discovery)
+ }.to raise_error(
+ DiscourseAi::Mcp::Client::Error,
+ I18n.t("discourse_ai.mcp_servers.errors.oauth_client_registration_failed_no_id"),
+ )
+ end
+
+ it "raises when no registration_endpoint is in discovery" do
+ discovery_without_reg =
+ DiscourseAi::Mcp::OAuthDiscovery::Result.new(
+ resource: ai_mcp_server.url,
+ resource_metadata_url: "#{ai_mcp_server.url}/.well-known/oauth-protected-resource",
+ issuer: "https://auth.example.com",
+ authorization_endpoint: "https://auth.example.com/authorize",
+ token_endpoint: "https://auth.example.com/token",
+ revocation_endpoint: nil,
+ registration_endpoint: nil,
+ )
+
+ expect {
+ described_class.register!(server: ai_mcp_server, discovery: discovery_without_reg)
+ }.to raise_error(
+ DiscourseAi::Mcp::Client::Error,
+ I18n.t("discourse_ai.mcp_servers.errors.oauth_registration_endpoint_missing"),
+ )
+ end
+ end
+end
diff --git a/plugins/discourse-ai/spec/lib/mcp/oauth_flow_spec.rb b/plugins/discourse-ai/spec/lib/mcp/oauth_flow_spec.rb
index 50f8ee3e462..4082b2b5e12 100644
--- a/plugins/discourse-ai/spec/lib/mcp/oauth_flow_spec.rb
+++ b/plugins/discourse-ai/spec/lib/mcp/oauth_flow_spec.rb
@@ -19,6 +19,117 @@ RSpec.describe DiscourseAi::Mcp::OAuthFlow do
I18n.t("discourse_ai.mcp_servers.errors.oauth_https_required"),
)
end
+
+ it "performs dynamic client registration when a registration_endpoint is discovered" do
+ Discourse.stubs(:base_url).returns("https://discourse.example.com")
+ discovery =
+ DiscourseAi::Mcp::OAuthDiscovery::Result.new(
+ resource: ai_mcp_server.url,
+ resource_metadata_url: "#{ai_mcp_server.url}/.well-known/oauth-protected-resource",
+ issuer: "https://auth.example.com",
+ authorization_endpoint: "https://auth.example.com/authorize",
+ token_endpoint: "https://auth.example.com/token",
+ revocation_endpoint: nil,
+ registration_endpoint: "https://auth.example.com/register",
+ )
+ DiscourseAi::Mcp::OAuthDiscovery.stubs(:discover!).returns(discovery)
+
+ stub_request(:post, "https://auth.example.com/register").to_return(
+ status: 201,
+ body: { client_id: "dynamic-id-456" }.to_json,
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
+
+ url = described_class.start!(server: ai_mcp_server, user: user)
+
+ expect(ai_mcp_server.reload.oauth_client_id).to eq("dynamic-id-456")
+ expect(url).to include("client_id=dynamic-id-456")
+ end
+
+ it "skips dynamic registration when client_id is already present" do
+ Discourse.stubs(:base_url).returns("https://discourse.example.com")
+ ai_mcp_server.update_columns(oauth_client_id: "existing-client-id")
+
+ discovery =
+ DiscourseAi::Mcp::OAuthDiscovery::Result.new(
+ resource: ai_mcp_server.url,
+ resource_metadata_url: "#{ai_mcp_server.url}/.well-known/oauth-protected-resource",
+ issuer: "https://auth.example.com",
+ authorization_endpoint: "https://auth.example.com/authorize",
+ token_endpoint: "https://auth.example.com/token",
+ revocation_endpoint: nil,
+ registration_endpoint: "https://auth.example.com/register",
+ )
+ DiscourseAi::Mcp::OAuthDiscovery.stubs(:discover!).returns(discovery)
+
+ url = described_class.start!(server: ai_mcp_server, user: user)
+
+ expect(url).to include("client_id=existing-client-id")
+ expect(a_request(:post, "https://auth.example.com/register")).not_to have_been_made
+ end
+
+ it "skips dynamic registration for manual registration mode" do
+ Discourse.stubs(:base_url).returns("https://discourse.example.com")
+ ai_mcp_server.update!(oauth_client_registration: "manual", oauth_client_id: "manual-id")
+
+ discovery =
+ DiscourseAi::Mcp::OAuthDiscovery::Result.new(
+ resource: ai_mcp_server.url,
+ resource_metadata_url: "#{ai_mcp_server.url}/.well-known/oauth-protected-resource",
+ issuer: "https://auth.example.com",
+ authorization_endpoint: "https://auth.example.com/authorize",
+ token_endpoint: "https://auth.example.com/token",
+ revocation_endpoint: nil,
+ registration_endpoint: "https://auth.example.com/register",
+ )
+ DiscourseAi::Mcp::OAuthDiscovery.stubs(:discover!).returns(discovery)
+
+ url = described_class.start!(server: ai_mcp_server, user: user)
+
+ expect(url).to include("client_id=manual-id")
+ expect(a_request(:post, "https://auth.example.com/register")).not_to have_been_made
+ end
+ end
+
+ describe ".complete!" do
+ it "wraps token exchange errors in OAuthError with the server attached" do
+ ai_mcp_server.update_columns(
+ oauth_authorization_endpoint: "https://auth.example.com/authorize",
+ oauth_token_endpoint: "https://auth.example.com/token",
+ oauth_issuer: "https://auth.example.com",
+ )
+
+ state = SecureRandom.hex(32)
+ Rails.cache.write(
+ "discourse-ai:mcp-oauth-state:#{state}",
+ {
+ "ai_mcp_server_id" => ai_mcp_server.id,
+ "user_id" => user.id,
+ "code_verifier" => "test-verifier",
+ },
+ expires_in: 10.minutes,
+ )
+
+ stub_request(:post, "https://auth.example.com/token").to_return(
+ status: 400,
+ body: { error: "invalid_client", error_description: "Client not found" }.to_json,
+ headers: {
+ "Content-Type" => "application/json",
+ },
+ )
+
+ expect {
+ described_class.complete!(params: { state: state, code: "auth-code" }, current_user: user)
+ }.to raise_error(described_class::OAuthError, "Client not found") { |error|
+ expect(error.server).to eq(ai_mcp_server)
+ expect(error.cause).to be_a(DiscourseAi::Mcp::Client::Error)
+ }
+
+ expect(ai_mcp_server.reload.oauth_status).to eq("error")
+ expect(ai_mcp_server.oauth_last_error).to eq("Client not found")
+ end
end
describe ".refresh!" do
diff --git a/plugins/discourse-ai/spec/models/ai_mcp_server_spec.rb b/plugins/discourse-ai/spec/models/ai_mcp_server_spec.rb
index 577f700f6bc..d92ba138af1 100644
--- a/plugins/discourse-ai/spec/models/ai_mcp_server_spec.rb
+++ b/plugins/discourse-ai/spec/models/ai_mcp_server_spec.rb
@@ -80,6 +80,19 @@ RSpec.describe AiMcpServer do
expect(server.oauth_token.refresh_token).to eq("refresh")
end
+ it "capitalizes a lowercase OAuth token type in the Authorization header" do
+ server =
+ Fabricate(
+ :ai_mcp_server,
+ auth_type: "oauth",
+ oauth_status: "connected",
+ oauth_token_type: "bearer",
+ )
+ server.oauth_token_store.write!(access_token: "oauth-access-token", refresh_token: "refresh")
+
+ expect(server.auth_header_value).to eq("Bearer oauth-access-token")
+ end
+
it "uses the client metadata URL unless manual registration is selected" do
server = Fabricate(:ai_mcp_server, auth_type: "oauth")
@@ -91,6 +104,33 @@ RSpec.describe AiMcpServer do
expect(server.effective_oauth_client_id).to eq("manual-client-id")
end
+ it "prefers a dynamically registered client_id over the metadata URL" do
+ server = Fabricate(:ai_mcp_server, auth_type: "oauth")
+ server.store_dynamic_registration!(client_id: "dynamic-client-id")
+
+ expect(server.reload.effective_oauth_client_id).to eq("dynamic-client-id")
+ end
+
+ it "clears dynamically registered client_id when OAuth credentials are cleared" do
+ server = Fabricate(:ai_mcp_server, auth_type: "oauth")
+ server.store_dynamic_registration!(client_id: "dynamic-client-id")
+
+ server.clear_oauth_credentials!
+
+ expect(server.reload.oauth_client_id).to be_nil
+ expect(server.effective_oauth_client_id).to eq(server.oauth_client_metadata_url)
+ end
+
+ it "preserves dynamically registered client_id across normal saves" do
+ server = Fabricate(:ai_mcp_server, auth_type: "oauth")
+ server.store_dynamic_registration!(client_id: "dynamic-client-id")
+
+ server.reload
+ server.update!(description: "Updated description")
+
+ expect(server.reload.oauth_client_id).to eq("dynamic-client-id")
+ end
+
it "clears stored OAuth credentials when the OAuth configuration changes" do
server =
Fabricate(
diff --git a/plugins/discourse-ai/spec/requests/admin/ai_mcp_servers_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_mcp_servers_controller_spec.rb
index 3386f549581..ca85e200042 100644
--- a/plugins/discourse-ai/spec/requests/admin/ai_mcp_servers_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/admin/ai_mcp_servers_controller_spec.rb
@@ -181,13 +181,11 @@ RSpec.describe DiscourseAi::Admin::AiMcpServersController do
it "does not reuse stored OAuth tokens when the OAuth configuration changes" do
ai_mcp_server =
- Fabricate(
- :ai_mcp_server,
- auth_type: "oauth",
- oauth_status: "connected",
- url: "https://docs.example.com/mcp",
- oauth_access_token_expires_at: 10.minutes.from_now,
- )
+ Fabricate(:ai_mcp_server, auth_type: "oauth", url: "https://docs.example.com/mcp")
+ ai_mcp_server.update_columns(
+ oauth_status: "connected",
+ oauth_access_token_expires_at: 10.minutes.from_now,
+ )
ai_mcp_server.oauth_token_store.write!(
access_token: "stale-access-token",
refresh_token: "refresh-token",
@@ -278,6 +276,29 @@ RSpec.describe DiscourseAi::Admin::AiMcpServersController do
expect(response).to redirect_to(ai_mcp_server.admin_edit_url)
end
+
+ it "redirects to the server edit page on failure so the admin can see the error" do
+ DiscourseAi::Mcp::OAuthFlow.expects(:complete!).raises(
+ DiscourseAi::Mcp::OAuthFlow::OAuthError.new("Client not found", server: ai_mcp_server),
+ )
+
+ get "/admin/plugins/discourse-ai/ai-mcp-servers/oauth/callback", params: { state: "abc" }
+
+ expect(response).to redirect_to(ai_mcp_server.admin_edit_url)
+ end
+
+ it "falls back to the tools page with a flash error when the server is unknown" do
+ DiscourseAi::Mcp::OAuthFlow.expects(:complete!).raises(
+ DiscourseAi::Mcp::OAuthFlow::OAuthError.new("invalid state"),
+ )
+
+ get "/admin/plugins/discourse-ai/ai-mcp-servers/oauth/callback", params: { state: "bad" }
+
+ expect(response).to redirect_to("/admin/plugins/discourse-ai/ai-tools")
+ expect(flash[:error]).to eq(
+ I18n.t("discourse_ai.mcp_servers.errors.oauth_callback_failed", message: "invalid state"),
+ )
+ end
end
describe "DELETE #oauth_disconnect" do
diff --git a/plugins/discourse-ai/spec/requests/mcp_oauth_controller_spec.rb b/plugins/discourse-ai/spec/requests/mcp_oauth_controller_spec.rb
index e1f6f860ef8..3559da6158e 100644
--- a/plugins/discourse-ai/spec/requests/mcp_oauth_controller_spec.rb
+++ b/plugins/discourse-ai/spec/requests/mcp_oauth_controller_spec.rb
@@ -15,5 +15,14 @@ RSpec.describe DiscourseAi::McpOauthController do
expect(response.parsed_body["grant_types"]).to eq(%w[authorization_code refresh_token])
expect(response.parsed_body["token_endpoint_auth_method"]).to eq("none")
end
+
+ it "is accessible when login is required" do
+ SiteSetting.login_required = true
+
+ get "/discourse-ai/mcp/oauth/client-metadata.json"
+
+ expect(response).to be_successful
+ expect(response.parsed_body["client_name"]).to eq("Discourse AI MCP Client")
+ end
end
end