A platform for community discussion. Free, open, simple.
FEATURE: Add MCP server integration to AI agents (#38706)
Samb2d73b346d25
diff --git a/config/initializers/000-zeitwerk.rb b/config/initializers/000-zeitwerk.rbindex a4855a1743b..5dcdb8eaf74 100644--- a/config/initializers/000-zeitwerk.rb+++ b/config/initializers/000-zeitwerk.rb@@ -43,6 +43,9 @@ Rails.autoloaders.each do |autoloader|"json" => "JSON","ssrf_detector" => "SSRFDetector","http" => "HTTP",+ "oauth_discovery" => "OAuthDiscovery",+ "oauth_flow" => "OAuthFlow",+ "oauth_token_store" => "OAuthTokenStore","gc_stat_instrumenter" => "GCStatInstrumenter","chat_sdk" => "ChatSDK","ip" => "IP",diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjsindex 0ab61338b1a..dee6884a368 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-agent-editor.gjs@@ -10,6 +10,7 @@ import { service } from "@ember/service";import { trustHTML } from "@ember/template";import AdminUser from "discourse/admin/models/admin-user";import BackButton from "discourse/components/back-button";+import DButton from "discourse/components/d-button";import Form from "discourse/components/form";import Avatar from "discourse/helpers/bound-avatar-template";import icon from "discourse/helpers/d-icon";@@ -24,6 +25,7 @@ import Group from "discourse/models/group";import GroupChooser from "discourse/select-kit/components/group-chooser";import { and, eq, gt, not, or } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";+import AiAgentMcpToolSelectorModal from "../components/modal/ai-agent-mcp-tool-selector-modal";import AiAgentResponseFormatEditor from "../components/modal/ai-agent-response-format-editor";import { toPlainObject } from "../lib/utilities";import AiAgentCollapsableExample from "./ai-agent-example";@@ -43,6 +45,7 @@ export default class AgentEditor extends Component {@service router;@service site;@service dialog;+ @service modal;@service toasts;@service siteSettings;@@ -78,6 +81,10 @@ export default class AgentEditor extends Component {return this.args.agents.resultSetMeta.tools;}+ get allMcpServers() {+ return this.args.agents.resultSetMeta.mcp_servers || [];+ }+get maxPixelValues() {const l = (key) =>i18n(`discourse_ai.ai_agent.vision_max_pixel_sizes.${key}`);@@ -274,9 +281,34 @@ export default class AgentEditor extends Component {return this.allTools.filter((tool) => tools.includes(tool.id));}+ mcpServerById(serverId) {+ return this.allMcpServers.find((item) => item.id === serverId);+ }++ selectedMcpToolNames(serverId, mcpServerToolNames = {}) {+ // Draft form state may use numeric keys, while persisted JSON keys are strings.+ return mcpServerToolNames[serverId] || mcpServerToolNames[`${serverId}`];+ }++ selectedMcpTools(serverId, mcpServerToolNames = {}) {+ const server = this.mcpServerById(serverId);+ const tools = server?.tools || [];+ const selectedToolNames = this.selectedMcpToolNames(+ serverId,+ mcpServerToolNames+ );++ if (!selectedToolNames?.length) {+ return tools;+ }++ const selectedToolSet = new Set(selectedToolNames);+ return tools.filter((tool) => selectedToolSet.has(tool.name));+ }+@actionselectedToolsWithTokens(tools) {- return tools.map((toolId) => {+ return (tools || []).map((toolId) => {const tool = this.allTools.find((t) => t.id === toolId);return {id: toolId,@@ -287,38 +319,82 @@ export default class AgentEditor extends Component {}@action- totalToolTokens(tools) {- if (!tools) {- return 0;- }- return tools.reduce((sum, toolId) => {- const tool = this.allTools.find((t) => t.id === toolId);- return sum + (tool?.token_count || 0);+ selectedMcpServers(serverIds, mcpServerToolNames = {}) {+ return (serverIds || []).map((serverId) => {+ const server = this.mcpServerById(serverId);+ const tools = server?.tools || [];+ const selectedTools = this.selectedMcpTools(serverId, mcpServerToolNames);++ return {+ id: serverId,+ name: server?.name || serverId,+ toolCount: server?.tool_count || 0,+ tokenCount: server?.token_count || 0,+ selectedToolCount: selectedTools.length,+ selectedTokenCount: selectedTools.reduce(+ (sum, tool) => sum + (tool.token_count || 0),+ 0+ ),+ allToolsEnabled: !this.selectedMcpToolNames(+ serverId,+ mcpServerToolNames+ )?.length,+ tools,+ lastHealthStatus: server?.last_health_status,+ };+ });+ }++ @action+ totalToolTokens(selectedTools = []) {+ return selectedTools.reduce((sum, tool) => {+ return sum + (tool?.tokenCount || 0);}, 0);}@action- toolTokenIndicatorStyle(tools) {- const total = this.totalToolTokens(tools);+ totalMcpToolTokens(selectedMcpServers = []) {+ return selectedMcpServers.reduce(+ (sum, server) => sum + server.selectedTokenCount,+ 0+ );+ }++ @action+ totalSelectedToolTokens(selectedTools = [], selectedMcpServers = []) {+ return (+ this.totalToolTokens(selectedTools) ++ this.totalMcpToolTokens(selectedMcpServers)+ );+ }++ @action+ totalSelectedToolCount(selectedTools = [], selectedMcpServers = []) {+ const mcpToolCount = selectedMcpServers.reduce(+ (sum, server) => sum + server.selectedToolCount,+ 0+ );++ return selectedTools.length + mcpToolCount;+ }++ @action+ toolTokenIndicatorStyle(total) {const percent = Math.min(100, (total / TOOL_TOKEN_BAR_MAX) * 100);return trustHTML(`left: ${percent}%`);}@action- toolCountIndicatorStyle(tools) {- const percent = Math.min(100, (tools.length / TOOL_COUNT_BAR_MAX) * 100);+ toolCountIndicatorStyle(count) {+ const percent = Math.min(100, (count / TOOL_COUNT_BAR_MAX) * 100);return trustHTML(`left: ${percent}%`);}@action- toolTokenSeverity(tools) {- if (!tools) {- return "low";- }- const total = this.totalToolTokens(tools);+ toolTokenSeverity(total, count) {if (total >= TOOL_TOKEN_HIGH_THRESHOLD ||- tools.length >= TOOL_COUNT_WARNING_THRESHOLD+ count >= TOOL_COUNT_WARNING_THRESHOLD) {return "high";} else if (total >= TOOL_TOKEN_LOW_THRESHOLD) {@@ -328,11 +404,7 @@ export default class AgentEditor extends Component {}@action- toolTokenOnlySeverity(tools) {- if (!tools) {- return "low";- }- const total = this.totalToolTokens(tools);+ toolTokenOnlySeverity(total) {if (total >= TOOL_TOKEN_HIGH_THRESHOLD) {return "high";} else if (total >= TOOL_TOKEN_LOW_THRESHOLD) {@@ -342,11 +414,8 @@ export default class AgentEditor extends Component {}@action- toolCountOnlySeverity(tools) {- if (!tools) {- return "low";- }- return tools.length >= TOOL_COUNT_WARNING_THRESHOLD ? "high" : "low";+ toolCountOnlySeverity(count) {+ return count >= TOOL_COUNT_WARNING_THRESHOLD ? "high" : "low";}@action@@ -355,13 +424,13 @@ export default class AgentEditor extends Component {}@action- tooManyTools(tools) {- return tools.length >= TOOL_COUNT_WARNING_THRESHOLD;+ tooManyTools(count) {+ return count >= TOOL_COUNT_WARNING_THRESHOLD;}@action- highTokenUsage(tools) {- return this.totalToolTokens(tools) >= TOOL_TOKEN_HIGH_THRESHOLD;+ highTokenUsage(total) {+ return total >= TOOL_TOKEN_HIGH_THRESHOLD;}@action@@ -370,6 +439,64 @@ export default class AgentEditor extends Component {form.set("examples", newExamples);}+ @action+ updateMcpServerIds(form, currentData, updatedServerIds) {+ const normalizedToolNames = {};++ Object.entries(currentData.mcp_server_tool_names || {}).forEach(+ ([serverId, toolNames]) => {+ const normalizedServerId = Number(serverId);+ if (updatedServerIds.includes(normalizedServerId)) {+ normalizedToolNames[normalizedServerId] = toolNames;+ }+ }+ );++ form.setProperties({+ mcp_server_ids: updatedServerIds,+ mcp_server_tool_names: normalizedToolNames,+ });+ }++ @action+ openMcpToolSelector(form, currentData, server) {+ this.modal.show(AiAgentMcpToolSelectorModal, {+ model: {+ serverName: server.name,+ tools: server.tools || [],+ selectedToolNames: this.selectedMcpToolNames(+ server.id,+ currentData.mcp_server_tool_names || {}+ ),+ onSave: (selectedToolNames) => {+ const updatedToolNames = {+ ...(currentData.mcp_server_tool_names || {}),+ };+ let updatedServerIds = [...(currentData.mcp_server_ids || [])];++ if (selectedToolNames?.length) {+ updatedToolNames[server.id] = selectedToolNames;+ } else {+ delete updatedToolNames[server.id];+ }++ if (selectedToolNames?.length === 0) {+ updatedServerIds = updatedServerIds.filter(+ (id) => id !== server.id+ );+ } else if (!updatedServerIds.includes(server.id)) {+ updatedServerIds = [...updatedServerIds, server.id];+ }++ form.setProperties({+ mcp_server_ids: updatedServerIds,+ mcp_server_tool_names: updatedToolNames,+ });+ },+ },+ });+ }+mapToolOptions(currentOptions, toolNames) {const updatedOptions = Object.assign({}, currentOptions);@@ -620,106 +747,231 @@ export default class AgentEditor extends Component {</field.Control></form.Field>- {{#if (gt data.tools.length 0)}}- <div- class="ai-agent-editor__tool-context-cost- {{if- (eq (this.toolTokenSeverity data.tools) 'high')- '--high'- (if- (eq (this.toolTokenSeverity data.tools) 'medium')- '--medium'- '--low'- )- }}"+ {{#if this.allMcpServers.length}}+ <form.Field+ @name="mcp_server_ids"+ @title={{i18n "discourse_ai.ai_agent.mcp_servers"}}+ @format="large"+ @type="custom"+ as |field|>- <ul class="ai-agent-editor__tool-token-list">- {{#each (this.selectedToolsWithTokens data.tools) as |tool|}}- <li class="ai-agent-editor__tool-token-item">- <span>{{tool.name}}</span>- <span class="ai-agent-editor__tool-token-count">- {{tool.tokenCount}}- {{i18n "discourse_ai.ai_agent.tokens"}}- </span>- </li>+ <field.Control>+ <AiToolSelector+ @value={{field.value}}+ @disabled={{data.system}}+ @onChange={{fn this.updateMcpServerIds form data}}+ @content={{this.allMcpServers}}+ />+ </field.Control>+ </form.Field>++ <p class="ai-agent-editor__mcp-server-help">+ {{i18n "discourse_ai.ai_agent.mcp_server_tools_help"}}+ </p>+ {{/if}}++ {{#let+ (this.selectedMcpServers+ data.mcp_server_ids data.mcp_server_tool_names+ )+ (this.selectedToolsWithTokens data.tools)+ as |selectedMcpServers selectedTools|+ }}+ {{#if data.mcp_server_ids.length}}+ <div class="ai-agent-editor__mcp-server-summary">+ {{#each selectedMcpServers as |server|}}+ <div class="ai-agent-editor__mcp-server-item">+ <div class="ai-agent-editor__mcp-server-item-main">+ <span class="ai-agent-editor__mcp-server-name">+ {{server.name}}+ </span>+ <div class="ai-agent-editor__mcp-server-meta">+ <span>+ {{#if server.allToolsEnabled}}+ {{i18n+ "discourse_ai.ai_agent.mcp_server_enabled_tool_count"+ count=server.selectedToolCount+ }}+ {{else}}+ {{i18n+ "discourse_ai.ai_agent.mcp_server_enabled_tools"+ count=server.selectedToolCount+ total=server.toolCount+ }}+ {{/if}}+ </span>+ <span>+ {{i18n+ "discourse_ai.ai_agent.mcp_server_tokens_only"+ tokens=server.selectedTokenCount+ }}+ </span>+ <span+ class="ai-agent-editor__mcp-server-health+ {{if+ (eq server.lastHealthStatus 'healthy')+ '--healthy'+ '--unhealthy'+ }}"+ >+ {{if+ (eq server.lastHealthStatus "healthy")+ (i18n "discourse_ai.mcp_servers.healthy")+ (i18n "discourse_ai.mcp_servers.unhealthy")+ }}+ </span>+ </div>+ </div>+ <DButton+ @action={{fn this.openMcpToolSelector form data server}}+ @label={{if+ server.allToolsEnabled+ "discourse_ai.ai_agent.mcp_server_choose_tools"+ "discourse_ai.ai_agent.mcp_server_edit_tools"+ }}+ class="btn-default btn-small ai-agent-editor__mcp-server-action"+ />+ </div>{{/each}}- </ul>- <div class="ai-agent-editor__tool-context-cost-header">- <span class="ai-agent-editor__tool-context-cost-label">- {{i18n "discourse_ai.ai_agent.context_cost"}}- </span>- </div>- <div class="ai-agent-editor__tool-context-cost-bar">- <span- class="ai-agent-editor__tool-context-cost-bar-indicator --token"- style={{this.toolTokenIndicatorStyle data.tools}}- >- {{icon "caret-down"}}- </span>- <span- class="ai-agent-editor__tool-context-cost-bar-indicator --count"- style={{this.toolCountIndicatorStyle data.tools}}- >- {{icon "caret-up"}}- </span></div>- <span class="ai-agent-editor__tool-context-cost-legend">- <span- class="ai-agent-editor__tool-context-cost-legend-item --token"- >- {{icon "caret-down"}}- {{i18n "discourse_ai.ai_agent.token_usage"}}:- <span- class="ai-agent-editor__tool-context-cost-value- {{this.toolTokenOnlySeverity data.tools}}"- >- {{i18n- "discourse_ai.ai_agent.tool_tokens_total"- tokens=(this.totalToolTokens data.tools)- }}- </span>- </span>- <span- class="ai-agent-editor__tool-context-cost-legend-item --count"- >- {{icon "caret-up"}}- {{i18n "discourse_ai.ai_agent.tool_count"}}:- <span- class="ai-agent-editor__tool-context-cost-value- {{this.toolCountOnlySeverity data.tools}}"+ {{/if}}++ {{#let+ (this.totalSelectedToolTokens selectedTools selectedMcpServers)+ (this.totalSelectedToolCount selectedTools selectedMcpServers)+ as |totalSelectedToolTokens totalSelectedToolCount|+ }}+ {{#let+ (this.toolTokenSeverity+ totalSelectedToolTokens totalSelectedToolCount+ )+ (this.toolTokenOnlySeverity totalSelectedToolTokens)+ (this.toolCountOnlySeverity totalSelectedToolCount)+ (this.tooManyTools totalSelectedToolCount)+ as |toolTokenSeverity toolTokenOnlySeverity toolCountOnlySeverity tooManyTools|+ }}+ {{#if (gt totalSelectedToolCount 0)}}+ <div+ class="ai-agent-editor__tool-context-cost+ {{if+ (eq toolTokenSeverity 'high')+ '--high'+ (if (eq toolTokenSeverity 'medium') '--medium' '--low')+ }}">- {{i18n- "discourse_ai.ai_agent.tool_count_value"- count=data.tools.length- }}- </span>- </span>- </span>- {{#if (eq (this.toolTokenSeverity data.tools) "medium")}}- <div class="ai-agent-editor__tool-context-cost-warning">- <span>- {{i18n "discourse_ai.ai_agent.tool_severity_medium"}}:- </span>- {{i18n "discourse_ai.ai_agent.tool_tokens_warning"}}- </div>- {{/if}}- {{#if (eq (this.toolTokenSeverity data.tools) "high")}}- <div class="ai-agent-editor__tool-context-cost-warning">- {{#if (this.tooManyTools data.tools)}}- <span>- {{i18n "discourse_ai.ai_agent.tool_severity_too_many"}}:- </span>- {{i18n "discourse_ai.ai_agent.tool_count_warning"}}- {{else}}- <span>- {{i18n "discourse_ai.ai_agent.tool_severity_high"}}:+ <ul class="ai-agent-editor__tool-token-list">+ {{#each selectedTools as |tool|}}+ <li class="ai-agent-editor__tool-token-item">+ <span>{{tool.name}}</span>+ <span class="ai-agent-editor__tool-token-count">+ {{tool.tokenCount}}+ {{i18n "discourse_ai.ai_agent.tokens"}}+ </span>+ </li>+ {{/each}}+ {{#each selectedMcpServers as |server|}}+ <li class="ai-agent-editor__tool-token-item">+ <span>+ {{i18n+ "discourse_ai.ai_agent.mcp_server_cost_name"+ name=server.name+ }}+ </span>+ <span class="ai-agent-editor__tool-token-count">+ {{i18n+ "discourse_ai.ai_agent.mcp_server_cost_value"+ tokens=server.selectedTokenCount+ count=server.selectedToolCount+ }}+ </span>+ </li>+ {{/each}}+ </ul>+ <div class="ai-agent-editor__tool-context-cost-header">+ <span class="ai-agent-editor__tool-context-cost-label">+ {{i18n "discourse_ai.ai_agent.context_cost"}}+ </span>+ </div>+ <div class="ai-agent-editor__tool-context-cost-bar">+ <span+ class="ai-agent-editor__tool-context-cost-bar-indicator --token"+ style={{this.toolTokenIndicatorStyle+ totalSelectedToolTokens+ }}+ >+ {{icon "caret-down"}}+ </span>+ <span+ class="ai-agent-editor__tool-context-cost-bar-indicator --count"+ style={{this.toolCountIndicatorStyle+ totalSelectedToolCount+ }}+ >+ {{icon "caret-up"}}+ </span>+ </div>+ <span class="ai-agent-editor__tool-context-cost-legend">+ <span+ class="ai-agent-editor__tool-context-cost-legend-item --token"+ >+ {{icon "caret-down"}}+ {{i18n "discourse_ai.ai_agent.token_usage"}}:+ <span+ class="ai-agent-editor__tool-context-cost-value+ {{toolTokenOnlySeverity}}"+ >+ {{i18n+ "discourse_ai.ai_agent.tool_tokens_total"+ tokens=totalSelectedToolTokens+ }}+ </span>+ </span>+ <span+ class="ai-agent-editor__tool-context-cost-legend-item --count"+ >+ {{icon "caret-up"}}+ {{i18n "discourse_ai.ai_agent.tool_count"}}:+ <span+ class="ai-agent-editor__tool-context-cost-value+ {{toolCountOnlySeverity}}"+ >+ {{i18n+ "discourse_ai.ai_agent.tool_count_value"+ count=totalSelectedToolCount+ }}+ </span>+ </span></span>- {{i18n "discourse_ai.ai_agent.tool_tokens_warning"}}- {{/if}}- </div>- {{/if}}- </div>- {{/if}}+ {{#if (eq toolTokenSeverity "medium")}}+ <div class="ai-agent-editor__tool-context-cost-warning">+ <span>+ {{i18n "discourse_ai.ai_agent.tool_severity_medium"}}:+ </span>+ {{i18n "discourse_ai.ai_agent.tool_tokens_warning"}}+ </div>+ {{/if}}+ {{#if (eq toolTokenSeverity "high")}}+ <div class="ai-agent-editor__tool-context-cost-warning">+ {{#if tooManyTools}}+ <span>+ {{i18n+ "discourse_ai.ai_agent.tool_severity_too_many"+ }}:+ </span>+ {{i18n "discourse_ai.ai_agent.tool_count_warning"}}+ {{else}}+ <span>+ {{i18n "discourse_ai.ai_agent.tool_severity_high"}}:+ </span>+ {{i18n "discourse_ai.ai_agent.tool_tokens_warning"}}+ {{/if}}+ </div>+ {{/if}}+ </div>+ {{/if}}+ {{/let}}+ {{/let}}+ {{/let}}{{#if (gt data.tools.length 0)}}<form.Fielddiff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-secrets-list-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-secrets-list-editor.gjsindex 8c804b711d3..d72551f74f0 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-secrets-list-editor.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-secrets-list-editor.gjs@@ -73,6 +73,26 @@ export default class AiSecretsListEditor extends Component {{{usage.name}}</LinkTo>({{i18n "discourse_ai.secrets.embedding"}})+ {{else if (eq usage.type "mcp_server")}}+ <LinkTo+ @route="adminPlugins.show.discourse-ai-tools.mcp-server-edit"+ @model={{usage.id}}+ >+ {{usage.name}}+ </LinkTo>+ ({{i18n "discourse_ai.secrets.mcp_server"}})+ {{else if+ (eq usage.type "mcp_server_oauth_client_secret")+ }}+ <LinkTo+ @route="adminPlugins.show.discourse-ai-tools.mcp-server-edit"+ @model={{usage.id}}+ >+ {{usage.name}}+ </LinkTo>+ ({{i18n+ "discourse_ai.secrets.mcp_server_oauth_client_secret"+ }}){{else if (eq usage.type "tool")}}<LinkTo@route="adminPlugins.show.discourse-ai-tools.edit"diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-tool-list-editor.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-tool-list-editor.gjsindex 57407172674..cb9b06a01bc 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-tool-list-editor.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/components/ai-tool-list-editor.gjs@@ -18,11 +18,13 @@ import { removeValueFromArray } from "discourse/lib/array-tools";import { eq } from "discourse/truth-helpers";import { i18n } from "discourse-i18n";import AiTool from "../admin/models/ai-tool";+import AiMcpServerToolsModal from "./modal/ai-mcp-server-tools-modal";export default class AiToolListEditor extends Component {@service adminPluginNavManager;@service router;@service dialog;+ @service modal;@tracked expandedCategory = null;@@ -32,6 +34,24 @@ export default class AiToolListEditor extends Component {);}+ get sortedMcpServers() {+ return [...(this.args.mcpServers?.content || [])].sort((a, b) =>+ (a.name || "").localeCompare(b.name || "")+ );+ }++ get hasScriptTools() {+ return this.sortedTools.length > 0;+ }++ get hasMcpServers() {+ return this.sortedMcpServers.length > 0;+ }++ get hasAnyItems() {+ return this.hasScriptTools || this.hasMcpServers;+ }+get dropdownPresets() {return this.args.tools.resultSetMeta.presets.filter((preset) => {// Filter out individual image generation presets, keep only the category@@ -91,6 +111,23 @@ export default class AiToolListEditor extends Component {);}+ @action+ routeToNewMcpServer() {+ return this.router.transitionTo(+ "adminPlugins.show.discourse-ai-tools.mcp-server-new"+ );+ }++ @action+ showMcpServerTools(server) {+ this.modal.show(AiMcpServerToolsModal, {+ model: {+ serverName: server.name,+ tools: server.tools || [],+ },+ });+ }+credentialStatus(tool) {const contracts = tool.secret_contracts || [];if (contracts.length === 0) {@@ -190,230 +227,326 @@ export default class AiToolListEditor extends Component {@learnMoreUrl="https://meta.discourse.org/t/ai-bot-custom-tools/314103"@descriptionLabel={{i18n "discourse_ai.tools.subheader_description"}}>- <:actions>- <DButton- @translatedLabel={{i18n "discourse_ai.tools.import"}}- @icon="upload"- class="btn btn-default btn-small ai-tool-list-editor__import-button"+ <:actions as |actions|>+ <actions.Default+ @label="discourse_ai.tools.import"@action={{this.importTool}}+ @icon="upload"+ class="ai-tool-list-editor__import-button"/>- <DMenu- @triggerClass="btn-primary btn-small ai-tool-list-editor__new-button"- @label={{i18n "discourse_ai.tools.new"}}+ <actions.Default+ @label="discourse_ai.mcp_servers.new"+ @action={{this.routeToNewMcpServer}}@icon="plus"- @placement="bottom-end"- @onClose={{this.resetMenuState}}- >- <:content>- <DropdownMenu as |dropdown|>- {{#if this.expandedCategory}}- <dropdown.item>- <DButton- @label="back_button"- @icon="chevron-left"- @action={{this.collapseCategory}}- class="btn-transparent"- />- </dropdown.item>- <dropdown.divider />- {{#each this.categoryPresets.otherPresets as |preset|}}- <dropdown.item>- <div- role="button"- class="ai-tool-preset-item"- data-option={{preset.preset_id}}- {{on "click" (fn this.routeToNewTool preset)}}- >- <span- class="ai-tool-preset-provider"- >{{preset.provider}}</span>- <span- class="ai-tool-preset-model"- >{{preset.model_name}}</span>- </div>- </dropdown.item>- {{/each}}-- {{#if this.categoryPresets.customPreset}}- <dropdown.divider />+ class="ai-tool-list-editor__new-mcp-button"+ />+ <actions.Wrapped>+ <DMenu+ @triggerClass="btn-default btn-small ai-tool-list-editor__new-button"+ @label={{i18n "discourse_ai.tools.new"}}+ @icon="plus"+ @placement="bottom-end"+ @onClose={{this.resetMenuState}}+ >+ <:content>+ <DropdownMenu as |dropdown|>+ {{#if this.expandedCategory}}<dropdown.item><DButton- @translatedLabel={{this.categoryPresets.customPreset.preset_name}}- @action={{fn- this.routeToNewTool- this.categoryPresets.customPreset- }}+ @label="back_button"+ @icon="chevron-left"+ @action={{this.collapseCategory}}class="btn-transparent"- data-option={{this.categoryPresets.customPreset.preset_id}}/></dropdown.item>- {{/if}}- {{else}}- {{#each this.dropdownPresets as |preset index|}}- {{#if (eq index this.lastIndexOfPresets)}}+ <dropdown.divider />+ {{#each this.categoryPresets.otherPresets as |preset|}}+ <dropdown.item>+ <div+ role="button"+ class="ai-tool-preset-item"+ data-option={{preset.preset_id}}+ {{on "click" (fn this.routeToNewTool preset)}}+ >+ <span+ class="ai-tool-preset-provider"+ >{{preset.provider}}</span>+ <span+ class="ai-tool-preset-model"+ >{{preset.model_name}}</span>+ </div>+ </dropdown.item>+ {{/each}}++ {{#if this.categoryPresets.customPreset}}<dropdown.divider />+ <dropdown.item>+ <DButton+ @translatedLabel={{this.categoryPresets.customPreset.preset_name}}+ @action={{fn+ this.routeToNewTool+ this.categoryPresets.customPreset+ }}+ class="btn-transparent"+ data-option={{this.categoryPresets.customPreset.preset_id}}+ />+ </dropdown.item>{{/if}}+ {{else}}+ {{#each this.dropdownPresets as |preset index|}}+ {{#if (eq index this.lastIndexOfPresets)}}+ <dropdown.divider />+ {{/if}}- <dropdown.item>- <DButton- @translatedLabel={{preset.preset_name}}- @action={{if- preset.is_category- (fn this.expandCategory preset)- (fn this.routeToNewTool preset)- }}- class="btn-transparent"- data-option={{preset.preset_id}}- />- </dropdown.item>- {{/each}}- {{/if}}- </DropdownMenu>+ <dropdown.item>+ <DButton+ @translatedLabel={{preset.preset_name}}+ @action={{if+ preset.is_category+ (fn this.expandCategory preset)+ (fn this.routeToNewTool preset)+ }}+ class="btn-transparent"+ data-option={{preset.preset_id}}+ />+ </dropdown.item>+ {{/each}}+ {{/if}}+ </DropdownMenu>- </:content>- </DMenu>+ </:content>+ </DMenu>+ </actions.Wrapped></:actions></DPageSubheader>- {{#if @tools.content}}- <table class="d-table ai-tool-list-editor">- <thead class="d-table__header">- <th>{{i18n "discourse_ai.tools.name"}}</th>- <th></th>- </thead>- <tbody>- {{#each this.sortedTools as |tool|}}- <tr- data-tool-id={{tool.id}}- class="ai-tool-list__row d-table__row"- >- <td class="d-table__cell --overview">- <div class="ai-tool-list__name-with-description">- <div class="ai-tool-list__name">- <strong>- {{tool.name}}- </strong>- </div>- <div class="ai-tool-list__description">- {{tool.description}}+ {{#if this.hasAnyItems}}+ {{#if this.hasScriptTools}}+ <h3 class="ai-tool-list-editor__section-title">+ {{i18n "discourse_ai.tools.script_tools"}}+ </h3>+ <table class="d-table ai-tool-list-editor">+ <thead class="d-table__header">+ <th>{{i18n "discourse_ai.tools.name"}}</th>+ <th></th>+ </thead>+ <tbody>+ {{#each this.sortedTools as |tool|}}+ <tr+ data-tool-id={{tool.id}}+ class="ai-tool-list__row d-table__row"+ >+ <td class="d-table__cell --overview">+ <div class="ai-tool-list__name-with-description">+ <div class="ai-tool-list__name">+ <strong>+ {{tool.name}}+ </strong>+ </div>+ <div class="ai-tool-list__description">+ {{tool.description}}+ </div>+ {{#if tool.secret_contracts.length}}+ <div class="ai-tool-list__credentials">+ {{#each (this.credentialStatus tool) as |cred|}}+ <span+ class="ai-tool-list__credential-badge+ {{if+ cred.bound+ 'ai-tool-list__credential-badge--bound'+ 'ai-tool-list__credential-badge--missing'+ }}"+ >+ {{#if cred.bound}}+ {{icon "check"}}+ {{else}}+ {{icon "triangle-exclamation"}}+ {{/if}}+ {{cred.alias}}+ {{#unless cred.bound}}+ <span class="ai-tool-list__credential-not-set">+ {{i18n+ "discourse_ai.tools.credential_not_set"+ }}+ </span>+ {{/unless}}+ </span>+ {{/each}}+ </div>+ {{/if}}</div>- {{#if tool.secret_contracts.length}}- <div class="ai-tool-list__credentials">- {{#each (this.credentialStatus tool) as |cred|}}- <span- class="ai-tool-list__credential-badge- {{if- cred.bound- 'ai-tool-list__credential-badge--bound'- 'ai-tool-list__credential-badge--missing'- }}"+ </td>+ <td class="d-table__cell --controls">+ <LinkTo+ @route="adminPlugins.show.discourse-ai-tools.edit"+ @model={{tool}}+ class="btn btn-default btn-text btn-small"+ >{{i18n "discourse_ai.tools.edit"}}</LinkTo>+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ {{/if}}++ {{#if this.hasMcpServers}}+ <h3 class="ai-tool-list-editor__section-title">+ {{i18n "discourse_ai.mcp_servers.short_title"}}+ </h3>+ <table class="d-table ai-tool-list-editor">+ <thead class="d-table__header">+ <th>{{i18n "discourse_ai.mcp_servers.name"}}</th>+ <th>{{i18n "discourse_ai.mcp_servers.health"}}</th>+ <th></th>+ </thead>+ <tbody>+ {{#each this.sortedMcpServers as |server|}}+ <tr+ data-mcp-server-id={{server.id}}+ class="ai-tool-list__row d-table__row"+ >+ <td class="d-table__cell --overview">+ <div class="ai-tool-list__name-with-description">+ <div class="ai-tool-list__name">+ <strong>{{server.name}}</strong>+ </div>+ <div class="ai-tool-list__description">+ {{server.description}}+ </div>+ <div class="ai-tool-list__mcp-meta">+ {{#if server.tools.length}}+ <button+ type="button"+ class="ai-tool-list__mcp-tools-button"+ {{on "click" (fn this.showMcpServerTools server)}}>- {{#if cred.bound}}- {{icon "check"}}- {{else}}- {{icon "triangle-exclamation"}}- {{/if}}- {{cred.alias}}- {{#unless cred.bound}}- <span class="ai-tool-list__credential-not-set">- {{i18n "discourse_ai.tools.credential_not_set"}}- </span>- {{/unless}}- </span>- {{/each}}+ {{i18n+ "discourse_ai.mcp_servers.tool_count"+ count=server.tool_count+ }}+ </button>+ {{else}}+ {{i18n+ "discourse_ai.mcp_servers.tool_count"+ count=server.tool_count+ }}+ {{/if}}</div>- {{/if}}- </div>- </td>- <td class="d-table__cell --controls">- <LinkTo- @route="adminPlugins.show.discourse-ai-tools.edit"- @model={{tool}}- class="btn btn-default btn-text btn-small"- >{{i18n "discourse_ai.tools.edit"}}</LinkTo>- </td>- </tr>- {{/each}}- </tbody>- </table>+ </div>+ </td>+ <td class="d-table__cell --detail">+ <span+ class="ai-tool-list__credential-badge+ {{if+ (eq server.last_health_status 'healthy')+ 'ai-tool-list__credential-badge--bound'+ 'ai-tool-list__credential-badge--missing'+ }}"+ >+ {{if+ (eq server.last_health_status "healthy")+ (i18n "discourse_ai.mcp_servers.healthy")+ (i18n "discourse_ai.mcp_servers.unhealthy")+ }}+ </span>+ </td>+ <td class="d-table__cell --controls">+ <LinkTo+ @route="adminPlugins.show.discourse-ai-tools.mcp-server-edit"+ @model={{server}}+ class="btn btn-default btn-text btn-small"+ >{{i18n "discourse_ai.mcp_servers.edit"}}</LinkTo>+ </td>+ </tr>+ {{/each}}+ </tbody>+ </table>+ {{/if}}{{else}}<AdminConfigAreaEmptyList @emptyLabel="discourse_ai.tools.no_tools">- <DMenu- @triggerClass="btn-default btn-small admin-config-area-empty-list__cta-button ai-tool-list-editor__empty-new-button"- @label={{i18n "discourse_ai.tools.new"}}- @icon="plus"- @placement="bottom-end"- @onClose={{this.resetMenuState}}- >- <:content>- <DropdownMenu as |dropdown|>- {{#if this.expandedCategory}}- <dropdown.item>- <DButton- @label="back_button"- @icon="chevron-left"- @action={{this.collapseCategory}}- class="btn-transparent"- />- </dropdown.item>- <dropdown.divider />- {{#each this.categoryPresets.otherPresets as |preset|}}- <dropdown.item>- <div- role="button"- class="ai-tool-preset-item"- data-option={{preset.preset_id}}- {{on "click" (fn this.routeToNewTool preset)}}- >- <span- class="ai-tool-preset-provider"- >{{preset.provider}}</span>- <span- class="ai-tool-preset-model"- >{{preset.model_name}}</span>- </div>- </dropdown.item>- {{/each}}-- {{#if this.categoryPresets.customPreset}}- <dropdown.divider />+ <div class="ai-tool-list-editor__empty-list-buttons">+ <DMenu+ @triggerClass="btn-default btn-small ai-tool-list-editor__empty-new-button"+ @label={{i18n "discourse_ai.tools.new"}}+ @icon="plus"+ @placement="bottom-end"+ @onClose={{this.resetMenuState}}+ >+ <:content>+ <DropdownMenu as |dropdown|>+ {{#if this.expandedCategory}}<dropdown.item><DButton- @translatedLabel={{this.categoryPresets.customPreset.preset_name}}- @action={{fn- this.routeToNewTool- this.categoryPresets.customPreset- }}+ @label="back_button"+ @icon="chevron-left"+ @action={{this.collapseCategory}}class="btn-transparent"- data-option={{this.categoryPresets.customPreset.preset_id}}/></dropdown.item>- {{/if}}- {{else}}- {{#each this.dropdownPresets as |preset index|}}- {{#if (eq index this.lastIndexOfPresets)}}+ <dropdown.divider />+ {{#each this.categoryPresets.otherPresets as |preset|}}+ <dropdown.item>+ <div+ role="button"+ class="ai-tool-preset-item"+ data-option={{preset.preset_id}}+ {{on "click" (fn this.routeToNewTool preset)}}+ >+ <span+ class="ai-tool-preset-provider"+ >{{preset.provider}}</span>+ <span+ class="ai-tool-preset-model"+ >{{preset.model_name}}</span>+ </div>+ </dropdown.item>+ {{/each}}++ {{#if this.categoryPresets.customPreset}}<dropdown.divider />+ <dropdown.item>+ <DButton+ @translatedLabel={{this.categoryPresets.customPreset.preset_name}}+ @action={{fn+ this.routeToNewTool+ this.categoryPresets.customPreset+ }}+ class="btn-transparent"+ data-option={{this.categoryPresets.customPreset.preset_id}}+ />+ </dropdown.item>{{/if}}+ {{else}}+ {{#each this.dropdownPresets as |preset index|}}+ {{#if (eq index this.lastIndexOfPresets)}}+ <dropdown.divider />+ {{/if}}- <dropdown.item>- <DButton- @translatedLabel={{preset.preset_name}}- @action={{if- preset.is_category- (fn this.expandCategory preset)- (fn this.routeToNewTool preset)- }}- class="btn-transparent"- data-option={{preset.preset_id}}- />- </dropdown.item>- {{/each}}- {{/if}}- </DropdownMenu>+ <dropdown.item>+ <DButton+ @translatedLabel={{preset.preset_name}}+ @action={{if+ preset.is_category+ (fn this.expandCategory preset)+ (fn this.routeToNewTool preset)+ }}+ class="btn-transparent"+ data-option={{preset.preset_id}}+ />+ </dropdown.item>+ {{/each}}+ {{/if}}+ </DropdownMenu>- </:content>- </DMenu>- </AdminConfigAreaEmptyList>+ </:content>+ </DMenu>+ <DButton+ @label="discourse_ai.mcp_servers.new"+ @icon="plus"+ @action={{this.routeToNewMcpServer}}+ class="btn-default btn-small ai-tool-list-editor__empty-new-mcp-button"+ />+ </div></AdminConfigAreaEmptyList>{{/if}}</section></template>diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.jsindex f3b1d22309a..96a635a4683 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-agents/new.js@@ -5,6 +5,7 @@ export default class AdminPluginsShowDiscourseAiAgentsNew extends DiscourseRouteasync model() {const record = this.store.createRecord("ai-agent");record.set("allowed_group_ids", [AUTO_GROUPS.trust_level_0.id]);+ record.set("tools", []);record.set("rag_uploads", []);// these match the defaults on the tablerecord.set("rag_chunk_tokens", 374);diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools.jsindex b8d1117fbb7..3deb84a4359 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools.js+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools.js@@ -4,7 +4,12 @@ import DiscourseRoute from "discourse/routes/discourse";export default class DiscourseAiToolsRoute extends DiscourseRoute {@service store;- model() {- return this.store.findAll("ai-tool");+ async model() {+ const [tools, mcpServers] = await Promise.all([+ this.store.findAll("ai-tool"),+ this.store.findAll("ai-mcp-server"),+ ]);++ return { tools, mcpServers };}}diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/edit.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/edit.jsindex e5ad4b29a93..cbaa054f0bc 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/edit.js+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/edit.js@@ -5,17 +5,17 @@ export default class DiscourseAiToolsEditRoute extends DiscourseRoute {const allTools = this.modelFor("adminPlugins.show.discourse-ai-tools");const id = parseInt(params.id, 10);- return allTools.content.find((tool) => tool.id === id);+ return allTools.tools.content.find((tool) => tool.id === id);}setupController(controller) {super.setupController(...arguments);const toolsModel = this.modelFor("adminPlugins.show.discourse-ai-tools");- controller.set("allTools", toolsModel);- controller.set("presets", toolsModel.resultSetMeta.presets);- controller.set("llms", toolsModel.resultSetMeta.llms);- controller.set("secrets", toolsModel.resultSetMeta.ai_secrets);- controller.set("settings", toolsModel.resultSetMeta.settings);+ controller.set("allTools", toolsModel.tools);+ controller.set("presets", toolsModel.tools.resultSetMeta.presets);+ controller.set("llms", toolsModel.tools.resultSetMeta.llms);+ controller.set("secrets", toolsModel.tools.resultSetMeta.ai_secrets);+ controller.set("settings", toolsModel.tools.resultSetMeta.settings);}}diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/mcp-server-edit.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/mcp-server-edit.jsnew file mode 100644index 00000000000..d86cbac967e--- /dev/null+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/mcp-server-edit.js@@ -0,0 +1,17 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class DiscourseAiToolsMcpServerEditRoute extends DiscourseRoute {+ model(params) {+ const toolsModel = this.modelFor("adminPlugins.show.discourse-ai-tools");+ const id = parseInt(params.id, 10);++ return toolsModel.mcpServers.content.find((server) => server.id === id);+ }++ setupController(controller) {+ super.setupController(...arguments);+ const toolsModel = this.modelFor("adminPlugins.show.discourse-ai-tools");+ controller.set("allMcpServers", toolsModel.mcpServers);+ controller.set("secrets", toolsModel.mcpServers.resultSetMeta.ai_secrets);+ }+}diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/mcp-server-new.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/mcp-server-new.jsnew file mode 100644index 00000000000..03bcae7342a--- /dev/null+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/mcp-server-new.js@@ -0,0 +1,14 @@+import DiscourseRoute from "discourse/routes/discourse";++export default class DiscourseAiToolsMcpServerNewRoute extends DiscourseRoute {+ async model() {+ return this.store.createRecord("ai-mcp-server");+ }++ setupController(controller) {+ super.setupController(...arguments);+ const toolsModel = this.modelFor("adminPlugins.show.discourse-ai-tools");+ controller.set("allMcpServers", toolsModel.mcpServers);+ controller.set("secrets", toolsModel.mcpServers.resultSetMeta.ai_secrets);+ }+}diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.jsindex 2cb5177f9bc..1cbcba04596 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/routes/admin-plugins/show/discourse-ai-tools/new.js@@ -16,11 +16,11 @@ export default class DiscourseAiToolsNewRoute extends DiscourseRoute {setupController(controller) {super.setupController(...arguments);const toolsModel = this.modelFor("adminPlugins.show.discourse-ai-tools");- controller.set("allTools", toolsModel);- controller.set("presets", toolsModel.resultSetMeta.presets);- controller.set("llms", toolsModel.resultSetMeta.llms);- controller.set("secrets", toolsModel.resultSetMeta.ai_secrets);- controller.set("settings", toolsModel.resultSetMeta.settings);+ controller.set("allTools", toolsModel.tools);+ controller.set("presets", toolsModel.tools.resultSetMeta.presets);+ controller.set("llms", toolsModel.tools.resultSetMeta.llms);+ controller.set("secrets", toolsModel.tools.resultSetMeta.ai_secrets);+ controller.set("settings", toolsModel.tools.resultSetMeta.settings);controller.set("selectedPreset", this.preset);}}diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/index.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/index.gjsindex 5da6735084f..635ca65a5fc 100644--- a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/index.gjs+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/index.gjs@@ -1,5 +1,8 @@import AiToolListEditor from "../../../../components/ai-tool-list-editor";export default <template>- <AiToolListEditor @tools={{@controller.model}} />+ <AiToolListEditor+ @tools={{@controller.model.tools}}+ @mcpServers={{@controller.model.mcpServers}}+ /></template>diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/mcp-server-edit.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/mcp-server-edit.gjsnew file mode 100644index 00000000000..88eb5151c0d--- /dev/null+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/mcp-server-edit.gjs@@ -0,0 +1,11 @@+import AiMcpServerEditor from "../../../../../discourse/components/ai-mcp-server-editor";++export default <template>+ <section class="ai-agent-tool-editor__current admin-detail pull-left">+ <AiMcpServerEditor+ @mcpServers={{@controller.allMcpServers}}+ @model={{@controller.model}}+ @secrets={{@controller.secrets}}+ />+ </section>+</template>diff --git a/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/mcp-server-new.gjs b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/mcp-server-new.gjsnew file mode 100644index 00000000000..88eb5151c0d--- /dev/null+++ b/plugins/discourse-ai/admin/assets/javascripts/discourse/templates/admin-plugins/show/discourse-ai-tools/mcp-server-new.gjs@@ -0,0 +1,11 @@+import AiMcpServerEditor from "../../../../../discourse/components/ai-mcp-server-editor";++export default <template>+ <section class="ai-agent-tool-editor__current admin-detail pull-left">+ <AiMcpServerEditor+ @mcpServers={{@controller.allMcpServers}}+ @model={{@controller.model}}+ @secrets={{@controller.secrets}}+ />+ </section>+</template>diff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rbindex e2ab6e7e2ed..ba12986c9e0 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_agents_controller.rb@@ -11,7 +11,7 @@ module DiscourseAiai_agents =AiAgent.ordered- .includes(:user, :uploads)+ .includes(:user, :uploads, ai_agent_mcp_servers: :ai_mcp_server).map { |agent| LocalizedAiAgentSerializer.new(agent, root: false) }tools =@@ -36,6 +36,11 @@ module DiscourseAiendllms = DiscourseAi::Configuration::LlmEnumerator.values_for_serialization+ mcp_servers =+ AiMcpServer+ .where(enabled: true)+ .order(:name)+ .map { |server| serialize_mcp_server(server) }sorted_tools = tools.sort_by { |t| t.try(:name) || t[:name] || "" }@@ -44,6 +49,7 @@ module DiscourseAimeta: {tools: sorted_tools,llms: llms,+ mcp_servers: mcp_servers,settings: {rag_images_enabled: SiteSetting.ai_rag_images_enabled,},@@ -59,8 +65,15 @@ module DiscourseAienddef create- ai_agent = AiAgent.new(ai_agent_params.except(:rag_uploads))+ params = ai_agent_params+ mcp_server_ids = params.delete(:ai_mcp_server_ids)+ mcp_server_tool_names = params.delete(:mcp_server_tool_names) || {}+ ai_agent = AiAgent.new(params.except(:rag_uploads))+if ai_agent.save+ if mcp_server_ids+ sync_mcp_server_assignments(ai_agent, mcp_server_ids, mcp_server_tool_names)+ endRagDocumentFragment.link_target_and_uploads(ai_agent, attached_upload_ids)log_ai_agent_creation(ai_agent)@@ -76,9 +89,15 @@ module DiscourseAienddef update+ params = ai_agent_params+ mcp_server_ids = params.delete(:ai_mcp_server_ids)+ mcp_server_tool_names = params.delete(:mcp_server_tool_names) || {}initial_attributes = @ai_agent.attributes.dup- if @ai_agent.update(ai_agent_params.except(:rag_uploads))+ if @ai_agent.update(params.except(:rag_uploads))+ if mcp_server_ids+ sync_mcp_server_assignments(@ai_agent, mcp_server_ids, mcp_server_tool_names)+ endRagDocumentFragment.update_target_uploads(@ai_agent, attached_upload_ids)log_ai_agent_update(@ai_agent, initial_attributes)@@ -439,9 +458,22 @@ module DiscourseAi:compression_threshold,:require_approval,allowed_group_ids: [],+ mcp_server_ids: [],rag_uploads: [:id],)+ if payload[:mcp_server_ids].is_a?(Array)+ permitted[:ai_mcp_server_ids] = payload[:mcp_server_ids].filter_map(&:presence).map(+ &:to_i+ )+ permitted.delete(:mcp_server_ids)+ end++ permitted[:mcp_server_tool_names] = normalize_mcp_server_tool_names(+ payload[:mcp_server_tool_names],+ permitted[:ai_mcp_server_ids],+ )+if tools = payload[:tools]permitted[:tools] = permit_tools(tools)end@@ -503,6 +535,68 @@ module DiscourseAiexamples.map { |example_arr| example_arr.take(2).map(&:to_s) }end+ def normalize_mcp_server_tool_names(raw_tool_names, allowed_server_ids)+ return {} if !raw_tool_names.respond_to?(:to_unsafe_h) && !raw_tool_names.is_a?(Hash)++ allowed_ids = Array(allowed_server_ids).map(&:to_i).to_set+ raw_hash =+ if raw_tool_names.respond_to?(:to_unsafe_h)+ raw_tool_names.to_unsafe_h+ else+ raw_tool_names+ end++ raw_hash.each_with_object({}) do |(server_id, tool_names), hash|+ normalized_server_id = server_id.to_i+ next if !allowed_ids.include?(normalized_server_id)+ next if !tool_names.is_a?(Array)++ normalized_tool_names = tool_names.filter_map { |name| name.to_s.presence }.uniq+ next if normalized_tool_names.blank?++ hash[normalized_server_id.to_s] = normalized_tool_names+ end+ end++ def sync_mcp_server_assignments(ai_agent, submitted_server_ids, mcp_server_tool_names)+ submitted_server_ids = Array(submitted_server_ids).map(&:to_i)+ preserved_disabled_server_ids =+ hidden_disabled_mcp_server_ids(ai_agent, submitted_server_ids)+ ai_agent.ai_mcp_server_ids = (submitted_server_ids + preserved_disabled_server_ids).uniq++ ai_agent.ai_agent_mcp_servers.each do |assignment|+ next if preserved_disabled_server_ids.include?(assignment.ai_mcp_server_id)++ assignment.update!(+ selected_tool_names: mcp_server_tool_names[assignment.ai_mcp_server_id.to_s],+ )+ end+ end++ def hidden_disabled_mcp_server_ids(ai_agent, submitted_server_ids)+ ai_agent+ .ai_agent_mcp_servers+ .includes(:ai_mcp_server)+ .filter_map do |assignment|+ next if submitted_server_ids.include?(assignment.ai_mcp_server_id)+ next if assignment.ai_mcp_server&.enabled?++ assignment.ai_mcp_server_id+ end+ end++ def serialize_mcp_server(server)+ {+ id: server.id,+ name: server.name,+ tool_count: server.tool_count,+ token_count: server.token_count,+ last_health_status: server.last_health_status,+ last_checked_at: server.last_checked_at,+ tools: server.tools_for_serialization,+ }+ end+def ai_agent_logger_fields{name: {@@ -562,7 +656,7 @@ module DiscourseAirequire_approval: {},# JSON fields- json_fields: %i[tools response_format examples allowed_group_ids],+ json_fields: %i[tools response_format examples allowed_group_ids ai_mcp_server_ids],}enddiff --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.rbnew file mode 100644index 00000000000..dab696f2d3a--- /dev/null+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_mcp_servers_controller.rb@@ -0,0 +1,271 @@+# frozen_string_literal: true++module DiscourseAi+ module Admin+ class AiMcpServersController < ::Admin::AdminController+ requires_plugin PLUGIN_NAME++ before_action :find_ai_mcp_server, only: %i[edit update destroy oauth_start oauth_disconnect]+ skip_before_action :check_xhr, :preload_json, only: %i[oauth_start oauth_callback]++ def index+ render json: {+ ai_mcp_servers:+ ActiveModel::ArraySerializer.new(+ AiMcpServer.order(:name),+ each_serializer: AiMcpServerSerializer,+ root: false,+ ).as_json,+ meta: {+ ai_secrets:+ ActiveModel::ArraySerializer.new(+ AiSecret.order(:name),+ each_serializer: AiSecretSerializer,+ root: false,+ ).as_json,+ },+ }+ end++ def new+ end++ def edit+ render json: AiMcpServerSerializer.new(@ai_mcp_server)+ end++ def create+ ai_mcp_server = AiMcpServer.new(ai_mcp_server_params)+ ai_mcp_server.created_by_id = current_user.id++ if ai_mcp_server.save+ log_ai_mcp_server_creation(ai_mcp_server)+ render json: AiMcpServerSerializer.new(ai_mcp_server), status: :created+ else+ render_json_error ai_mcp_server+ end+ end++ def update+ initial_attributes = @ai_mcp_server.attributes.dup++ if @ai_mcp_server.update(ai_mcp_server_params)+ log_ai_mcp_server_update(@ai_mcp_server, initial_attributes)+ render json: AiMcpServerSerializer.new(@ai_mcp_server)+ else+ render_json_error @ai_mcp_server+ end+ end++ def destroy+ details = {+ mcp_server_id: @ai_mcp_server.id,+ name: @ai_mcp_server.name,+ subject: @ai_mcp_server.name,+ }++ @ai_mcp_server.destroy!+ log_ai_mcp_server_deletion(details)+ head :no_content+ end++ def oauth_start+ if @ai_mcp_server.new_record? || !@ai_mcp_server.oauth?+ return render_json_error(I18n.t("discourse_ai.mcp_servers.errors.oauth_not_configured"))+ end++ redirect_to(+ DiscourseAi::Mcp::OAuthFlow.start!(server: @ai_mcp_server, user: current_user),+ allow_other_host: true,+ )+ rescue StandardError => e+ @ai_mcp_server.mark_oauth_error!(e.message)+ redirect_to @ai_mcp_server.admin_edit_url+ end++ def oauth_callback+ 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"+ end++ def oauth_disconnect+ DiscourseAi::Mcp::OAuthFlow.disconnect!(@ai_mcp_server)+ render json: AiMcpServerSerializer.new(@ai_mcp_server.reload)+ rescue StandardError => e+ render_json_error e.message, status: 400+ end++ def test+ 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)++ 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(+ render_json_error(+ I18n.t("discourse_ai.mcp_servers.errors.oauth_save_before_connect"),+ status: 400,+ )+ )+ end++ client = DiscourseAi::Mcp::Client.new(ai_mcp_server)+ initialized = client.initialize_session+ tools = client.list_tools(session_id: initialized[:session_id])++ render json: {+ protocol_version: initialized[:result]["protocolVersion"],+ server_capabilities: initialized[:result]["capabilities"] || {},+ tool_count: tools.length,+ tool_names: tools.map { |tool| tool["name"] },+ }+ rescue StandardError => e+ render_json_error e.message, status: 400+ end++ private++ def find_ai_mcp_server+ @ai_mcp_server = AiMcpServer.find(params[:id])+ end++ def ai_mcp_server_params+ params.require(:ai_mcp_server).permit(+ :name,+ :description,+ :url,+ :auth_type,+ :ai_secret_id,+ :auth_header,+ :auth_scheme,+ :oauth_client_registration,+ :oauth_client_id,+ :oauth_client_secret_ai_secret_id,+ :oauth_scopes,+ :enabled,+ :timeout_seconds,+ )+ end++ def ai_mcp_server_logger_fields+ {+ name: {+ },+ description: {+ },+ url: {+ },+ auth_type: {+ },+ ai_secret_id: {+ type: :sensitive,+ extract: false,+ },+ auth_header: {+ },+ auth_scheme: {+ },+ oauth_client_registration: {+ },+ oauth_client_id: {+ },+ oauth_client_secret_ai_secret_id: {+ type: :sensitive,+ extract: false,+ },+ oauth_scopes: {+ },+ oauth_token_type: {+ },+ oauth_access_token_expires_at: {+ },+ oauth_authorization_endpoint: {+ },+ oauth_token_endpoint: {+ },+ oauth_revocation_endpoint: {+ },+ oauth_issuer: {+ },+ oauth_resource_metadata_url: {+ },+ oauth_status: {+ },+ oauth_last_error: {+ type: :large_text,+ },+ oauth_last_authorized_at: {+ },+ oauth_last_refreshed_at: {+ },+ enabled: {+ },+ timeout_seconds: {+ },+ server_capabilities: {+ type: :large_text,+ },+ protocol_version: {+ },+ last_health_error: {+ type: :large_text,+ },+ }+ end++ def log_ai_mcp_server_creation(ai_mcp_server)+ logger = DiscourseAi::Utils::AiStaffActionLogger.new(current_user)+ entity_details = { mcp_server_id: ai_mcp_server.id, subject: ai_mcp_server.name }+ logger.log_creation(+ "mcp_server",+ ai_mcp_server,+ ai_mcp_server_logger_fields,+ entity_details,+ )+ end++ def log_ai_mcp_server_update(ai_mcp_server, initial_attributes)+ logger = DiscourseAi::Utils::AiStaffActionLogger.new(current_user)+ entity_details = { mcp_server_id: ai_mcp_server.id, subject: ai_mcp_server.name }+ logger.log_update(+ "mcp_server",+ ai_mcp_server,+ initial_attributes,+ ai_mcp_server_logger_fields,+ entity_details,+ )+ end++ def log_ai_mcp_server_deletion(details)+ logger = DiscourseAi::Utils::AiStaffActionLogger.new(current_user)+ 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?++ (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+ end+ end+ end+enddiff --git a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_secrets_controller.rb b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_secrets_controller.rbindex 874ce3dd7c3..91b13c3444b 100644--- a/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_secrets_controller.rb+++ b/plugins/discourse-ai/app/controllers/discourse_ai/admin/ai_secrets_controller.rb@@ -9,7 +9,12 @@ module DiscourseAisecrets =AiSecret.all- .includes(:llm_models, :embedding_definitions, ai_tool_secret_bindings: :ai_tool)+ .includes(+ :llm_models,+ :embedding_definitions,+ :ai_mcp_servers,+ ai_tool_secret_bindings: :ai_tool,+ ).order(:name)render json: {@@ -27,6 +32,7 @@ module DiscourseAiAiSecret.includes(:llm_models,:embedding_definitions,+ :ai_mcp_servers,ai_tool_secret_bindings: :ai_tool,).find(params[:id])render json: AiSecretSerializer.new(secret, scope: { unmask: true })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.rbnew file mode 100644index 00000000000..6f412a3ef6b--- /dev/null+++ b/plugins/discourse-ai/app/controllers/discourse_ai/mcp_oauth_controller.rb@@ -0,0 +1,22 @@+# frozen_string_literal: true++module DiscourseAi+ class McpOauthController < ::ApplicationController+ requires_plugin PLUGIN_NAME+ skip_before_action :check_xhr, only: :client_metadata+ skip_before_action :preload_json, only: :client_metadata++ def client_metadata+ render json: {+ client_name: "Discourse AI MCP Client",+ redirect_uris: [+ "#{Discourse.base_url}/admin/plugins/discourse-ai/ai-mcp-servers/oauth/callback",+ ],+ grant_types: %w[authorization_code refresh_token],+ response_types: ["code"],+ application_type: "web",+ token_endpoint_auth_method: "none",+ }+ end+ end+enddiff --git a/plugins/discourse-ai/app/jobs/regular/refresh_ai_mcp_server_tools.rb b/plugins/discourse-ai/app/jobs/regular/refresh_ai_mcp_server_tools.rbnew file mode 100644index 00000000000..fdb8b31b5b8--- /dev/null+++ b/plugins/discourse-ai/app/jobs/regular/refresh_ai_mcp_server_tools.rb@@ -0,0 +1,12 @@+# frozen_string_literal: true++module Jobs+ class RefreshAiMcpServerTools < ::Jobs::Base+ def execute(args)+ server = AiMcpServer.find_by(id: args[:ai_mcp_server_id])+ return if server.blank? || !server.enabled?++ DiscourseAi::Mcp::ToolRegistry.refresh!(server, raise_on_error: false)+ end+ end+enddiff --git a/plugins/discourse-ai/app/jobs/scheduled/refresh_ai_mcp_server_tools_cache.rb b/plugins/discourse-ai/app/jobs/scheduled/refresh_ai_mcp_server_tools_cache.rbnew file mode 100644index 00000000000..6cdd5d550b9--- /dev/null+++ b/plugins/discourse-ai/app/jobs/scheduled/refresh_ai_mcp_server_tools_cache.rb@@ -0,0 +1,15 @@+# frozen_string_literal: true++module Jobs+ class RefreshAiMcpServerToolsCache < ::Jobs::Scheduled+ every 1.hour++ def execute(args)+ AiMcpServer+ .where(enabled: true)+ .find_each do |server|+ DiscourseAi::Mcp::ToolRegistry.refresh!(server, raise_on_error: false)+ end+ end+ end+enddiff --git a/plugins/discourse-ai/app/models/ai_agent.rb b/plugins/discourse-ai/app/models/ai_agent.rbindex bbecf3b9289..6db7bfc23cd 100644--- a/plugins/discourse-ai/app/models/ai_agent.rb+++ b/plugins/discourse-ai/app/models/ai_agent.rb@@ -48,6 +48,8 @@ class AiAgent < ActiveRecord::Basevalidate :tools_can_not_be_duplicatedhas_many :rag_document_fragments, dependent: :destroy, as: :target+ has_many :ai_agent_mcp_servers, dependent: :destroy+ has_many :ai_mcp_servers, through: :ai_agent_mcp_serversbelongs_to :created_by, class_name: "User"belongs_to :user@@ -78,7 +80,12 @@ class AiAgent < ActiveRecord::Baseenddef self.all_agent_records(enabled_only: true)- agent_cache[:records] ||= AiAgent.ordered.includes(:user).all.limit(MAX_AGENTS_PER_SITE).to_a+ agent_cache[:records] ||= AiAgent+ .ordered+ .includes(:user, ai_agent_mcp_servers: :ai_mcp_server)+ .all+ .limit(MAX_AGENTS_PER_SITE)+ .to_aif enabled_onlyagent_cache[:records].select(&:enabled)@@ -265,6 +272,28 @@ class AiAgent < ActiveRecord::Baseklassend+ reserved_names = tools.filter_map { |tool| tool.signature[:name].to_s.downcase.presence }+ enabled_mcp_server_assignments =+ ai_agent_mcp_servers+ .includes(:ai_mcp_server)+ .select { |assignment| assignment.ai_mcp_server&.enabled? }+ enabled_mcp_servers = enabled_mcp_server_assignments.map(&:ai_mcp_server)+ selected_tool_names_by_server =+ enabled_mcp_server_assignments.each_with_object({}) do |assignment, hash|+ next if assignment.all_tools_enabled?++ hash[assignment.ai_mcp_server_id] = assignment.selected_tool_names+ end++ tools.concat(+ DiscourseAi::Mcp::ToolRegistry.tool_classes_for_servers(+ enabled_mcp_servers,+ reserved_names: reserved_names,+ selected_tool_names_by_server: selected_tool_names_by_server,+ ),+ )+ instance_attributes[:mcp_server_ids] = enabled_mcp_servers.map(&:id)+agent_class = DiscourseAi::Agents::Agent.system_agents_by_id[self.id]if agent_classreturn(diff --git a/plugins/discourse-ai/app/models/ai_agent_mcp_server.rb b/plugins/discourse-ai/app/models/ai_agent_mcp_server.rbnew file mode 100644index 00000000000..88faec8900f--- /dev/null+++ b/plugins/discourse-ai/app/models/ai_agent_mcp_server.rb@@ -0,0 +1,67 @@+# frozen_string_literal: true++class AiAgentMcpServer < ActiveRecord::Base+ belongs_to :ai_agent+ belongs_to :ai_mcp_server++ before_validation :normalize_selected_tool_names++ validates :ai_agent_id, presence: true+ validates :ai_mcp_server_id, presence: true+ validates :ai_mcp_server_id, uniqueness: { scope: :ai_agent_id }++ def selected_tool_names+ Array(self[:selected_tool_names]).filter_map(&:presence).uniq+ end++ def all_tools_enabled?+ self[:selected_tool_names].blank?+ end++ def tools_for_serialization+ return @tools_for_serialization if instance_variable_defined?(:@tools_for_serialization)++ tools = ai_mcp_server&.tools_for_serialization || []+ @tools_for_serialization =+ if all_tools_enabled?+ tools+ else+ selected_names = selected_tool_names.to_set+ tools.select { |tool| selected_names.include?(tool[:name]) }+ end+ end++ def tool_count+ tools_for_serialization.length+ end++ def token_count+ tools_for_serialization.sum { |tool| tool[:token_count].to_i }+ end++ private++ def normalize_selected_tool_names+ if instance_variable_defined?(:@tools_for_serialization)+ remove_instance_variable(:@tools_for_serialization)+ end+ self[:selected_tool_names] = selected_tool_names.presence+ end+end++# == Schema Information+#+# Table name: ai_agent_mcp_servers+#+# id :bigint not null, primary key+# selected_tool_names :jsonb+# created_at :datetime not null+# updated_at :datetime not null+# ai_agent_id :bigint not null+# ai_mcp_server_id :bigint not null+#+# Indexes+#+# index_ai_agent_mcp_servers_on_ai_agent_id_and_ai_mcp_server_id (ai_agent_id,ai_mcp_server_id) UNIQUE+# index_ai_agent_mcp_servers_on_ai_mcp_server_id (ai_mcp_server_id)+#diff --git a/plugins/discourse-ai/app/models/ai_mcp_oauth_token.rb b/plugins/discourse-ai/app/models/ai_mcp_oauth_token.rbnew file mode 100644index 00000000000..1145b9b02a1--- /dev/null+++ b/plugins/discourse-ai/app/models/ai_mcp_oauth_token.rb@@ -0,0 +1,25 @@+# frozen_string_literal: true++class AiMcpOauthToken < ActiveRecord::Base+ belongs_to :ai_mcp_server, inverse_of: :oauth_token++ validates :ai_mcp_server_id, uniqueness: true+ validates :access_token, length: { maximum: 10_000 }, allow_blank: true+ validates :refresh_token, length: { maximum: 10_000 }, allow_blank: true+end++# == Schema Information+#+# Table name: ai_mcp_oauth_tokens+#+# id :bigint not null, primary key+# access_token :text+# refresh_token :text+# created_at :datetime not null+# updated_at :datetime not null+# ai_mcp_server_id :bigint not null+#+# Indexes+#+# index_ai_mcp_oauth_tokens_on_ai_mcp_server_id (ai_mcp_server_id) UNIQUE+#diff --git a/plugins/discourse-ai/app/models/ai_mcp_server.rb b/plugins/discourse-ai/app/models/ai_mcp_server.rbnew file mode 100644index 00000000000..4275e988fb6--- /dev/null+++ b/plugins/discourse-ai/app/models/ai_mcp_server.rb@@ -0,0 +1,437 @@+# frozen_string_literal: true++class AiMcpServer < ActiveRecord::Base+ MAX_TIMEOUT_SECONDS = 300+ AUTH_TYPES = %w[none header_secret oauth].freeze+ HEALTH_STATUSES = %w[unknown healthy error].freeze+ OAUTH_CLIENT_REGISTRATIONS = %w[client_metadata_document manual].freeze+ OAUTH_STATUSES = %w[disconnected connected refresh_failed error].freeze+ OAUTH_REAUTH_TRIGGER_FIELDS = %w[+ url+ oauth_client_registration+ oauth_client_id+ oauth_client_secret_ai_secret_id+ oauth_scopes+ ].freeze++ belongs_to :ai_secret, optional: true+ belongs_to :created_by, class_name: "User", optional: true+ belongs_to :oauth_client_secret,+ class_name: "AiSecret",+ foreign_key: :oauth_client_secret_ai_secret_id,+ optional: true++ has_many :ai_agent_mcp_servers, dependent: :destroy+ has_many :ai_agents, through: :ai_agent_mcp_servers+ has_one :oauth_token,+ class_name: "AiMcpOauthToken",+ dependent: :destroy,+ inverse_of: :ai_mcp_server++ before_validation :normalize_auth_configuration++ validates :name, presence: true, uniqueness: true, length: { maximum: 100 }+ validates :description, presence: true, length: { maximum: 1000 }+ validates :url, presence: true, length: { maximum: 1000 }+ validates :auth_header, presence: true, length: { maximum: 100 }, if: :header_secret?+ validates :auth_scheme, length: { maximum: 100 }+ validates :auth_type, inclusion: { in: AUTH_TYPES }+ validates :oauth_client_registration, inclusion: { in: OAUTH_CLIENT_REGISTRATIONS }, if: :oauth?+ validates :oauth_status, inclusion: { in: OAUTH_STATUSES }, allow_blank: true+ validates :timeout_seconds,+ numericality: {+ only_integer: true,+ greater_than: 0,+ less_than_or_equal_to: MAX_TIMEOUT_SECONDS,+ }+ validates :last_health_status, inclusion: { in: HEALTH_STATUSES }, allow_blank: true++ validate :validate_ai_secret_id_exists+ validate :validate_oauth_client_secret_id_exists+ validate :validate_oauth_configuration+ validate :validate_public_https_url++ after_commit :flush_tool_cache+ after_commit :clear_oauth_tokens_if_auth_type_changed+ after_commit :clear_oauth_credentials_if_configuration_changed+ after_destroy_commit :clear_oauth_tokens++ def auth_header_value+ if oauth?+ token = oauth_token_store.access_token+ return nil if token.blank?++ token_type = oauth_token_type.presence || "Bearer"+ return "#{token_type} #{token}"+ end++ return nil if ai_secret.blank?++ secret = ai_secret.secret+ return secret if auth_scheme.blank?++ "#{auth_scheme} #{secret}"+ end++ def healthy?+ last_health_status == "healthy"+ end++ def tool_definitions+ DiscourseAi::Mcp::ToolRegistry.tool_definitions_for(self)+ end++ def tools_for_serialization+ return @tools_for_serialization if instance_variable_defined?(:@tools_for_serialization)++ @tools_for_serialization =+ tool_definitions.filter_map do |definition|+ tool_name = definition["name"].to_s+ next if tool_name.blank?++ signature =+ DiscourseAi::Agents::Tools::Mcp.class_instance(id, tool_name, definition).signature+ json_schema = signature[:json_schema]++ {+ name: tool_name,+ title:+ definition["title"].presence || definition.dig("annotations", "title").presence ||+ tool_name.humanize,+ description: definition["description"].presence || signature[:description],+ parameters:+ (+ if json_schema.present?+ self.class.parameters_for_serialization(json_schema)+ else+ signature[:parameters]+ end+ ),+ json_schema: json_schema,+ token_count: DiscourseAi::Tokenizer::OpenAiCl100kTokenizer.size(signature.to_json),+ }+ end+ rescue StandardError+ @tools_for_serialization = []+ end++ def tool_count+ tools_for_serialization.length+ end++ def token_count+ tools_for_serialization.sum { |tool| tool[:token_count].to_i }+ end++ def refresh_tools!(raise_on_error: true)+ if instance_variable_defined?(:@tools_for_serialization)+ remove_instance_variable(:@tools_for_serialization)+ end+ DiscourseAi::Mcp::ToolRegistry.refresh!(self, raise_on_error: raise_on_error)+ end++ def none_auth?+ auth_type == "none"+ end++ def header_secret?+ auth_type == "header_secret"+ end++ def oauth?+ auth_type == "oauth"+ end++ def oauth_connected?+ oauth? && oauth_status == "connected" && oauth_token_store.access_token.present?+ end++ def oauth_needs_refresh?+ oauth_access_token_expires_at.present? && oauth_access_token_expires_at <= 1.minute.from_now+ end++ def oauth_callback_url+ "#{Discourse.base_url}/admin/plugins/discourse-ai/ai-mcp-servers/oauth/callback"+ end++ def oauth_client_metadata_url+ "#{Discourse.base_url}/discourse-ai/mcp/oauth/client-metadata"+ end++ def admin_edit_url+ "#{Discourse.base_url}/admin/plugins/discourse-ai/ai-tools/mcp-servers/#{id}/edit"+ end++ def effective_oauth_client_id+ if oauth_client_registration == "manual"+ oauth_client_id.presence+ else+ oauth_client_metadata_url+ end+ end++ def oauth_client_secret_value+ oauth_client_secret&.secret+ end++ def oauth_discovery_result+ return if oauth_authorization_endpoint.blank? || oauth_token_endpoint.blank?++ DiscourseAi::Mcp::OAuthDiscovery::Result.new(+ resource: url,+ resource_metadata_url: oauth_resource_metadata_url,+ issuer: oauth_issuer,+ authorization_endpoint: oauth_authorization_endpoint,+ token_endpoint: oauth_token_endpoint,+ revocation_endpoint: oauth_revocation_endpoint,+ )+ end++ def store_oauth_discovery!(discovery)+ update_columns(+ oauth_authorization_endpoint: discovery.authorization_endpoint,+ oauth_token_endpoint: discovery.token_endpoint,+ oauth_revocation_endpoint: discovery.revocation_endpoint,+ oauth_issuer: discovery.issuer,+ oauth_resource_metadata_url: discovery.resource_metadata_url,+ oauth_last_error: nil,+ )+ end++ def update_oauth_tokens!(access_token:, refresh_token:, token_type:, expires_in:, granted_scopes:)+ oauth_token_store.write!(access_token: access_token, refresh_token: refresh_token)++ update_columns(+ oauth_status: "connected",+ oauth_token_type: token_type.presence || "Bearer",+ oauth_access_token_expires_at:+ expires_in.present? ? Time.zone.now + expires_in.to_i.seconds : nil,+ oauth_granted_scopes: granted_scopes.presence || oauth_granted_scopes,+ oauth_last_authorized_at: oauth_last_authorized_at || Time.zone.now,+ oauth_last_refreshed_at: Time.zone.now,+ oauth_last_error: nil,+ )+ end++ def mark_oauth_authorized!+ update_columns(+ oauth_status: "connected",+ oauth_last_authorized_at: Time.zone.now,+ oauth_last_refreshed_at: Time.zone.now,+ oauth_last_error: nil,+ )+ end++ def mark_oauth_refresh_failed!(message)+ update_columns(oauth_status: "refresh_failed", oauth_last_error: message.to_s.truncate(1000))+ end++ def mark_oauth_error!(message)+ update_columns(oauth_status: "error", oauth_last_error: message.to_s.truncate(1000))+ end++ def clear_oauth_credentials!+ oauth_token_store.clear!+ update_columns(+ oauth_status: "disconnected",+ oauth_token_type: nil,+ oauth_access_token_expires_at: nil,+ oauth_granted_scopes: nil,+ oauth_authorization_endpoint: nil,+ oauth_token_endpoint: nil,+ oauth_revocation_endpoint: nil,+ oauth_issuer: nil,+ oauth_resource_metadata_url: nil,+ oauth_last_error: nil,+ oauth_last_authorized_at: nil,+ oauth_last_refreshed_at: nil,+ )+ end++ def oauth_token_store+ @oauth_token_store ||= DiscourseAi::Mcp::OAuthTokenStore.new(self)+ end++ def self.public_https_url?(raw_url)+ uri = parse_public_uri(raw_url)+ return false if uri.nil?++ validate_hostname_public!(uri.hostname)+ true+ rescue FinalDestination::SSRFError, SocketError, URI::InvalidURIError+ false+ end++ def self.parse_public_uri(raw_url)+ uri = URI.parse(raw_url.to_s.strip)+ return nil if uri.scheme != "https"+ return nil if uri.host.blank?+ return nil if uri.user.present? || uri.password.present?++ uri+ rescue URI::InvalidURIError+ nil+ end++ def self.validate_hostname_public!(hostname)+ normalized = hostname.to_s.downcase+ raise FinalDestination::SSRFError, "hostname missing" if normalized.blank?+ raise FinalDestination::SSRFError, "localhost is not allowed" if normalized == "localhost"++ ip = IPAddr.new(normalized)+ if !FinalDestination::SSRFDetector.ip_allowed?(ip)+ raise FinalDestination::SSRFError, "private IP is not allowed"+ end+ rescue IPAddr::InvalidAddressError+ FinalDestination::SSRFDetector.lookup_and_filter_ips(normalized)+ end++ def self.parameters_for_serialization(schema)+ properties = schema&.dig(:properties) || schema&.dig("properties")+ required_names = Array(schema&.dig(:required) || schema&.dig("required")).map(&:to_s)+ return [] if !properties.is_a?(Hash)++ properties.map do |name, definition|+ definition = definition.is_a?(Hash) ? definition : {}+ items = definition[:items] || definition["items"]++ {+ name: name.to_s,+ type: definition[:type] || definition["type"] || "object",+ description: definition[:description] || definition["description"],+ required: required_names.include?(name.to_s),+ enum: definition[:enum] || definition["enum"],+ item_type: items.is_a?(Hash) ? (items[:type] || items["type"]) : nil,+ }.compact+ end+ end++ private++ def normalize_auth_configuration+ self.auth_type = auth_type.presence || (ai_secret_id.present? ? "header_secret" : "none")+ self.auth_header = auth_header.presence || "Authorization"+ self.oauth_client_registration ||= "client_metadata_document" if oauth?++ 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?+ end++ def validate_ai_secret_id_exists+ return if ai_secret_id.blank? || AiSecret.exists?(ai_secret_id)++ errors.add(:ai_secret_id, I18n.t("discourse_ai.mcp_servers.secret_not_found"))+ end++ def validate_oauth_client_secret_id_exists+ if oauth_client_secret_ai_secret_id.blank? || AiSecret.exists?(oauth_client_secret_ai_secret_id)+ return+ end++ errors.add(+ :oauth_client_secret_ai_secret_id,+ I18n.t("discourse_ai.mcp_servers.secret_not_found"),+ )+ end++ def validate_oauth_configuration+ return unless oauth?++ if oauth_client_registration == "manual" && oauth_client_id.blank?+ errors.add(:oauth_client_id, I18n.t("discourse_ai.mcp_servers.oauth_client_id_required"))+ end+ end++ def validate_public_https_url+ uri = self.class.parse_public_uri(url)++ if uri.nil?+ errors.add(:url, I18n.t("discourse_ai.mcp_servers.invalid_url_not_https"))+ return+ end++ self.class.validate_hostname_public!(uri.hostname)+ rescue FinalDestination::SSRFError, SocketError, URI::InvalidURIError+ errors.add(:url, I18n.t("discourse_ai.mcp_servers.invalid_url_not_reachable"))+ end++ def flush_tool_cache+ if instance_variable_defined?(:@tools_for_serialization)+ remove_instance_variable(:@tools_for_serialization)+ end+ DiscourseAi::Mcp::ToolRegistry.invalidate!(self.id)+ AiAgent.agent_cache.flush!+ end++ def clear_oauth_tokens_if_auth_type_changed+ previous_auth_type = previous_changes["auth_type"]&.first+ return if previous_auth_type != "oauth" || oauth?++ clear_oauth_credentials!+ end++ def clear_oauth_credentials_if_configuration_changed+ return unless oauth?+ return if (previous_changes.keys & OAUTH_REAUTH_TRIGGER_FIELDS).blank?++ clear_oauth_credentials!+ end++ def clear_oauth_tokens+ oauth_token_store.clear!+ end+end++# == Schema Information+#+# Table name: ai_mcp_servers+#+# id :bigint not null, primary key+# auth_header :string(100) default("Authorization"), not null+# auth_scheme :string(100) default("Bearer"), not null+# auth_type :string(50) default("header_secret"), not null+# description :string(1000) not null+# enabled :boolean default(TRUE), not null+# last_checked_at :datetime+# last_health_error :string(1000)+# last_health_status :string(50)+# last_tools_synced_at :datetime+# name :string(100) not null+# oauth_access_token_expires_at :datetime+# oauth_authorization_endpoint :string(1000)+# oauth_client_registration :string(50) default("client_metadata_document")+# oauth_granted_scopes :string(2000)+# oauth_issuer :string(1000)+# oauth_last_authorized_at :datetime+# oauth_last_error :string(1000)+# oauth_last_refreshed_at :datetime+# oauth_resource_metadata_url :string(1000)+# oauth_revocation_endpoint :string(1000)+# oauth_scopes :string(2000)+# oauth_status :string(50) default("disconnected"), not null+# oauth_token_endpoint :string(1000)+# oauth_token_type :string(100)+# protocol_version :string(100)+# server_capabilities :jsonb not null+# timeout_seconds :integer default(30), not null+# url :string(1000) not null+# created_at :datetime not null+# updated_at :datetime not null+# ai_secret_id :bigint+# created_by_id :integer+# oauth_client_id :string(1000)+# oauth_client_secret_ai_secret_id :bigint+#+# Indexes+#+# index_ai_mcp_servers_on_ai_secret_id (ai_secret_id)+# index_ai_mcp_servers_on_name (name) UNIQUE+# index_ai_mcp_servers_on_oauth_client_secret_ai_secret_id (oauth_client_secret_ai_secret_id)+#diff --git a/plugins/discourse-ai/app/models/ai_secret.rb b/plugins/discourse-ai/app/models/ai_secret.rbindex 0776352935a..0db1c709c2a 100644--- a/plugins/discourse-ai/app/models/ai_secret.rb+++ b/plugins/discourse-ai/app/models/ai_secret.rb@@ -9,10 +9,16 @@ class AiSecret < ActiveRecord::Basehas_many :llm_models, dependent: :nullifyhas_many :embedding_definitions, dependent: :nullifyhas_many :ai_tool_secret_bindings, dependent: :destroy+ has_many :ai_mcp_servers, dependent: :nullify+ has_many :oauth_client_secret_mcp_servers,+ class_name: "AiMcpServer",+ foreign_key: :oauth_client_secret_ai_secret_id,+ dependent: :nullifydef in_use?llm_models.exists? || embedding_definitions.exists? || used_by_provider_params? ||- ai_tool_secret_bindings.exists?+ ai_tool_secret_bindings.exists? || ai_mcp_servers.exists? ||+ oauth_client_secret_mcp_servers.exists?enddef used_by@@ -35,6 +41,12 @@ class AiSecret < ActiveRecord::Baseid: binding.ai_tool.id,}end+ ai_mcp_servers.each do |server|+ usage << { type: "mcp_server", name: server.name, id: server.id }+ end+ oauth_client_secret_mcp_servers.each do |server|+ usage << { type: "mcp_server_oauth_client_secret", name: server.name, id: server.id }+ endusageenddiff --git a/plugins/discourse-ai/app/serializers/ai_mcp_server_serializer.rb b/plugins/discourse-ai/app/serializers/ai_mcp_server_serializer.rbnew file mode 100644index 00000000000..45c4f023837--- /dev/null+++ b/plugins/discourse-ai/app/serializers/ai_mcp_server_serializer.rb@@ -0,0 +1,63 @@+# frozen_string_literal: true++class AiMcpServerSerializer < ApplicationSerializer+ attributes :id,+ :name,+ :description,+ :url,+ :auth_type,+ :ai_secret_id,+ :auth_header,+ :auth_scheme,+ :oauth_client_registration,+ :oauth_client_id,+ :oauth_client_secret_ai_secret_id,+ :oauth_scopes,+ :oauth_granted_scopes,+ :oauth_token_type,+ :oauth_access_token_expires_at,+ :oauth_authorization_endpoint,+ :oauth_token_endpoint,+ :oauth_revocation_endpoint,+ :oauth_issuer,+ :oauth_resource_metadata_url,+ :oauth_status,+ :oauth_last_error,+ :oauth_last_authorized_at,+ :oauth_last_refreshed_at,+ :oauth_client_metadata_url,+ :enabled,+ :timeout_seconds,+ :last_health_status,+ :last_health_error,+ :last_checked_at,+ :last_tools_synced_at,+ :protocol_version,+ :server_capabilities,+ :tool_count,+ :token_count,+ :tool_names,+ :tools++ root "ai_mcp_server"++ def tool_count+ object.tool_count+ end++ def tool_names+ object.tools_for_serialization.map { |tool| tool[:name] }+ end++ def tools+ object.tools_for_serialization+ end++ def token_count+ object.token_count+ end++ def oauth_client_metadata_url+ object.oauth_client_metadata_url+ end+enddiff --git a/plugins/discourse-ai/app/serializers/localized_ai_agent_serializer.rb b/plugins/discourse-ai/app/serializers/localized_ai_agent_serializer.rbindex 075cdd903ba..0059e58fa8e 100644--- a/plugins/discourse-ai/app/serializers/localized_ai_agent_serializer.rb+++ b/plugins/discourse-ai/app/serializers/localized_ai_agent_serializer.rb@@ -34,6 +34,9 @@ class LocalizedAiAgentSerializer < ApplicationSerializer:max_turn_tokens,:compression_threshold,:require_approval,+ :mcp_server_ids,+ :mcp_server_tool_names,+ :mcp_servers,:response_format,:examples,:features@@ -63,4 +66,46 @@ class LocalizedAiAgentSerializer < ApplicationSerializer{ id: feature.module_id, module_name: feature.module_name, name: feature.name }endend++ def mcp_server_ids+ enabled_mcp_server_assignments.filter_map(&:ai_mcp_server_id)+ end++ def mcp_server_tool_names+ enabled_mcp_server_assignments.each_with_object({}) do |assignment, hash|+ next if assignment.all_tools_enabled?++ hash[assignment.ai_mcp_server_id.to_s] = assignment.selected_tool_names+ end+ end++ def mcp_servers+ sorted_enabled_mcp_server_assignments.map do |assignment|+ server = assignment.ai_mcp_server+ {+ id: server.id,+ name: server.name,+ tool_count: server.tool_count,+ token_count: server.token_count,+ selected_tool_names: assignment.selected_tool_names,+ selected_tool_count: assignment.tool_count,+ selected_token_count: assignment.token_count,+ all_tools_enabled: assignment.all_tools_enabled?,+ last_health_status: server.last_health_status,+ last_checked_at: server.last_checked_at,+ }+ end+ end++ private++ def enabled_mcp_server_assignments+ @enabled_mcp_server_assignments ||=+ object.ai_agent_mcp_servers.select { |assignment| assignment.ai_mcp_server&.enabled? }+ end++ def sorted_enabled_mcp_server_assignments+ @sorted_enabled_mcp_server_assignments ||=+ enabled_mcp_server_assignments.sort_by { |assignment| assignment.ai_mcp_server.name.downcase }+ endenddiff --git a/plugins/discourse-ai/app/services/discourse_ai/agent_exporter.rb b/plugins/discourse-ai/app/services/discourse_ai/agent_exporter.rbindex 439ab4d9661..c795fa0e3f0 100644--- a/plugins/discourse-ai/app/services/discourse_ai/agent_exporter.rb+++ b/plugins/discourse-ai/app/services/discourse_ai/agent_exporter.rb@@ -55,6 +55,7 @@ module DiscourseAitop_p: ai_agent.top_p,response_format: ai_agent.response_format,tools: transform_tools_for_export(ai_agent.tools, serialized_custom_tools),+ mcp_servers: serialize_mcp_servers(ai_agent),},custom_tools: serialized_custom_tools,}@@ -77,5 +78,19 @@ module DiscourseAi["custom-#{tool.tool_name}", tool_config[1], tool_config[2]]endend++ def serialize_mcp_servers(ai_agent)+ ai_agent+ .ai_agent_mcp_servers+ .includes(:ai_mcp_server)+ .sort_by { |assignment| assignment.ai_mcp_server.name.downcase }+ .map do |assignment|+ server_data = { name: assignment.ai_mcp_server.name }+ if !assignment.all_tools_enabled?+ server_data[:selected_tool_names] = assignment.selected_tool_names+ end+ server_data+ end+ endendenddiff --git a/plugins/discourse-ai/app/services/discourse_ai/agent_importer.rb b/plugins/discourse-ai/app/services/discourse_ai/agent_importer.rbindex 0a35e65788e..fe5bdc20e92 100644--- a/plugins/discourse-ai/app/services/discourse_ai/agent_importer.rb+++ b/plugins/discourse-ai/app/services/discourse_ai/agent_importer.rb@@ -44,13 +44,17 @@ module DiscourseAiresponse_format: agent_data["response_format"],tools: transform_tools_for_import(agent_data["tools"], tool_name_to_id),}+ mcp_server_assignments = resolve_mcp_server_assignments(agent_data["mcp_servers"])if existing_agent && overwriteexisting_agent.update!(**attrs)+ sync_mcp_server_assignments(existing_agent, mcp_server_assignments)existing_agentelseattrs[:name] = agent_data["name"]- AiAgent.create!(**attrs)+ AiAgent+ .create!(**attrs)+ .tap { |agent| sync_mcp_server_assignments(agent, mcp_server_assignments) }endendend@@ -84,6 +88,15 @@ module DiscourseAiconflicts[:custom_tools] = existing_tools if existing_tools.any?end+ if @data["agent"]["mcp_servers"].present?+ missing_mcp_servers =+ Array(@data["agent"]["mcp_servers"]).filter_map do |server|+ server_name = extract_mcp_server_name(server)+ server_name if server_name.present? && !AiMcpServer.exists?(name: server_name)+ end+ conflicts[:mcp_servers] = missing_mcp_servers if missing_mcp_servers.any?+ end+if conflicts.any?message = build_conflict_message(conflicts)raise ImportError.new(message, conflicts)@@ -108,6 +121,13 @@ module DiscourseAimessages << errorend+ if conflicts[:mcp_servers] && conflicts[:mcp_servers].any?+ messages << I18n.t(+ "discourse_ai.errors.mcp_server_missing",+ names: conflicts[:mcp_servers].join(", "),+ )+ end+messages.join("\n")end@@ -154,5 +174,71 @@ module DiscourseAiendendend++ def resolve_mcp_server_assignments(raw_servers)+ return [] if raw_servers.blank?++ server_entries =+ Array(raw_servers).map do |server|+ if server.is_a?(Hash)+ {+ name: server["name"].to_s,+ selected_tool_names:+ Array(server["selected_tool_names"]).filter_map { |name| name.to_s.presence }.uniq,+ }+ else+ { name: server.to_s, selected_tool_names: [] }+ end+ end++ names = server_entries.map { |entry| entry[:name] }+ found = AiMcpServer.where(name: names).index_by(&:name)+ missing = names.reject { |name| found.key?(name) }++ if missing.any?+ raise ImportError.new(+ I18n.t("discourse_ai.errors.mcp_server_missing", names: missing.join(", ")),+ mcp_servers: missing,+ )+ end++ server_entries.map do |entry|+ server = found.fetch(entry[:name])+ selected_tool_names = entry[:selected_tool_names]++ if selected_tool_names.present?+ available_tool_names = server.tools_for_serialization.map { |tool| tool[:name] }+ selected_tool_names &= available_tool_names++ if selected_tool_names.blank?+ raise ImportError.new(+ I18n.t("discourse_ai.errors.mcp_server_tools_not_found", name: entry[:name]),+ mcp_servers: [entry[:name]],+ )+ end+ end++ { id: server.id, selected_tool_names: selected_tool_names.presence }+ end+ end++ def sync_mcp_server_assignments(agent, assignments)+ agent.ai_mcp_server_ids = assignments.map { |assignment| assignment[:id] }++ assignments.each do |assignment|+ agent+ .ai_agent_mcp_servers+ .find_by!(ai_mcp_server_id: assignment[:id])+ .update!(selected_tool_names: assignment[:selected_tool_names])+ end+ end++ def extract_mcp_server_name(server)+ if server.is_a?(Hash)+ server["name"].presence+ else+ server.to_s.presence+ end+ endendenddiff --git a/plugins/discourse-ai/assets/javascripts/discourse/admin-discourse-ai-plugin-route-map.js b/plugins/discourse-ai/assets/javascripts/discourse/admin-discourse-ai-plugin-route-map.jsindex 41ffbd4d3a8..a9dc5d31b77 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/admin-discourse-ai-plugin-route-map.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/admin-discourse-ai-plugin-route-map.js@@ -23,6 +23,8 @@ export default {this.route("discourse-ai-tools", { path: "ai-tools" }, function () {this.route("new");this.route("edit", { path: "/:id/edit" });+ this.route("mcp-server-new", { path: "/mcp-servers/new" });+ this.route("mcp-server-edit", { path: "/mcp-servers/:id/edit" });});this.route("discourse-ai-spam", { path: "ai-spam" });this.route("discourse-ai-translations", { path: "ai-translations" });diff --git a/plugins/discourse-ai/assets/javascripts/discourse/admin/adapters/ai-mcp-server.js b/plugins/discourse-ai/assets/javascripts/discourse/admin/adapters/ai-mcp-server.jsnew file mode 100644index 00000000000..c16225436f4--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/admin/adapters/ai-mcp-server.js@@ -0,0 +1,20 @@+import RestAdapter from "discourse/adapters/rest";++export default class AiMcpServerAdapter extends RestAdapter {+ jsonMode = true;++ basePath() {+ return "/admin/plugins/discourse-ai/";+ }++ pathFor(store, type, findArgs) {+ let path =+ this.basePath(store, type, findArgs) ++ store.pluralize(this.apiNameFor(type));+ return this.appendQueryParams(path, findArgs);+ }++ apiNameFor() {+ return "ai-mcp-server";+ }+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-agent.js b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-agent.jsindex 3193d3f4c89..2b9e091200f 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-agent.js+++ b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-agent.js@@ -32,6 +32,8 @@ const CREATE_ATTRIBUTES = ["allow_topic_mentions","allow_chat_channel_mentions","allow_chat_direct_messages",+ "mcp_server_ids",+ "mcp_server_tool_names","execution_mode","max_turn_tokens",@@ -65,6 +67,8 @@ const SYSTEM_ATTRIBUTES = ["allow_topic_mentions","allow_chat_channel_mentions","allow_chat_direct_messages",+ "mcp_server_ids",+ "mcp_server_tool_names","execution_mode","max_turn_tokens",@@ -160,6 +164,8 @@ export default class AiAgent extends RestModel {toPOJO() {const attrs = this.getProperties(CREATE_ATTRIBUTES);this.populateTools(attrs);+ attrs.mcp_server_ids = attrs.mcp_server_ids || [];+ attrs.mcp_server_tool_names = attrs.mcp_server_tool_names || {};attrs.forced_tool_count = this.forced_tool_count || -1;attrs.response_format = attrs.response_format || [];attrs.examples = attrs.examples || [];diff --git a/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-mcp-server.js b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-mcp-server.jsnew file mode 100644index 00000000000..09bb0c149f8--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/admin/models/ai-mcp-server.js@@ -0,0 +1,81 @@+import { ajax } from "discourse/lib/ajax";+import RestModel from "discourse/models/rest";++const CREATE_ATTRIBUTES = [+ "id",+ "name",+ "description",+ "url",+ "auth_type",+ "ai_secret_id",+ "auth_header",+ "auth_scheme",+ "oauth_client_registration",+ "oauth_client_id",+ "oauth_client_secret_ai_secret_id",+ "oauth_scopes",+ "oauth_granted_scopes",+ "oauth_token_type",+ "oauth_access_token_expires_at",+ "oauth_authorization_endpoint",+ "oauth_token_endpoint",+ "oauth_revocation_endpoint",+ "oauth_issuer",+ "oauth_resource_metadata_url",+ "oauth_status",+ "oauth_last_error",+ "oauth_last_authorized_at",+ "oauth_last_refreshed_at",+ "oauth_client_metadata_url",+ "enabled",+ "timeout_seconds",+ "last_health_status",+ "last_health_error",+ "last_checked_at",+ "last_tools_synced_at",+ "protocol_version",+ "server_capabilities",+ "tool_count",+ "tool_names",+ "tools",+];++export default class AiMcpServer extends RestModel {+ createProperties() {+ return this.getProperties(CREATE_ATTRIBUTES);+ }++ updateProperties() {+ const attrs = this.createProperties();+ attrs.id = this.id;+ return attrs;+ }++ async testConnection(data) {+ const path = this.isNew+ ? "/admin/plugins/discourse-ai/ai-mcp-servers/test.json"+ : `/admin/plugins/discourse-ai/ai-mcp-servers/${this.id}/test.json`;++ return await ajax(path, {+ type: "POST",+ data: JSON.stringify({ ai_mcp_server: data }),+ contentType: "application/json",+ });+ }++ get oauthStartPath() {+ return `/admin/plugins/discourse-ai/ai-mcp-servers/${this.id}/oauth/start`;+ }++ async disconnectOAuth() {+ const response = await ajax(+ `/admin/plugins/discourse-ai/ai-mcp-servers/${this.id}/oauth/disconnect.json`,+ {+ type: "DELETE",+ }+ );++ this.setProperties(response.ai_mcp_server);+ return response.ai_mcp_server;+ }+}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.gjsnew file mode 100644index 00000000000..7363ab515cb--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-mcp-server-editor-form.gjs@@ -0,0 +1,598 @@+import Component from "@glimmer/component";+import { tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { action } from "@ember/object";+import { later } from "@ember/runloop";+import { service } from "@ember/service";+import Form from "discourse/components/form";+import { popupAjaxError } from "discourse/lib/ajax-error";+import { removeValueFromArray } from "discourse/lib/array-tools";+import { and, eq, not } from "discourse/truth-helpers";+import { i18n } from "discourse-i18n";+import AiSecretSelector from "./ai-secret-selector";++export default class AiMcpServerEditorForm extends Component {+ @service dialog;+ @service router;+ @service toasts;++ @tracked isSaving = false;+ @tracked isTesting = false;+ @tracked isConnecting = false;+ @tracked isDisconnecting = false;+ @tracked testResult = null;+ @tracked formData = {};++ constructor() {+ super(...arguments);+ this.formData = this.buildFormData();+ }++ buildFormData() {+ const { model } = this.args;++ return {+ name: model.name || "",+ description: model.description || "",+ url: model.url || "",+ auth_type:+ model.auth_type || (model.ai_secret_id ? "header_secret" : "none"),+ ai_secret_id: model.ai_secret_id || null,+ auth_header: model.auth_header || "Authorization",+ auth_scheme: model.auth_scheme ?? "Bearer",+ oauth_client_registration:+ model.oauth_client_registration || "client_metadata_document",+ oauth_client_id: model.oauth_client_id || "",+ oauth_client_secret_ai_secret_id:+ model.oauth_client_secret_ai_secret_id || null,+ oauth_scopes: model.oauth_scopes || "",+ enabled: model.enabled ?? true,+ timeout_seconds: model.timeout_seconds || 30,+ };+ }++ get authTypes() {+ return [+ {+ id: "none",+ name: i18n("discourse_ai.mcp_servers.auth_types.none"),+ },+ {+ id: "header_secret",+ name: i18n("discourse_ai.mcp_servers.auth_types.header_secret"),+ },+ {+ id: "oauth",+ name: i18n("discourse_ai.mcp_servers.auth_types.oauth"),+ },+ ];+ }++ get oauthClientRegistrations() {+ return [+ {+ id: "client_metadata_document",+ name: i18n(+ "discourse_ai.mcp_servers.oauth_client_registration_types.client_metadata_document"+ ),+ },+ {+ id: "manual",+ name: i18n(+ "discourse_ai.mcp_servers.oauth_client_registration_types.manual"+ ),+ },+ ];+ }++ get oauthStatusLabelKey() {+ return `discourse_ai.mcp_servers.oauth_statuses.${+ this.args.model.oauth_status || "disconnected"+ }`;+ }++ get oauthConnectLabelKey() {+ return this.canDisconnectOAuth+ ? "discourse_ai.mcp_servers.oauth_reconnect"+ : "discourse_ai.mcp_servers.oauth_connect";+ }++ get canDisconnectOAuth() {+ const status = this.args.model.oauth_status;+ return status === "connected" || status === "refresh_failed";+ }++ get canTestOAuthConnection() {+ return this.args.model.oauth_status === "connected";+ }++ @action+ resetTestResult(value, { name, set }) {+ set(name, value);+ this.testResult = null;+ }++ @action+ normalizeData(data) {+ const payload = { ...data };++ payload.auth_type ||= payload.ai_secret_id ? "header_secret" : "none";+ payload.ai_secret_id ||= null;+ payload.oauth_client_secret_ai_secret_id ||= null;+ payload.oauth_client_id = payload.oauth_client_id?.trim() || null;+ payload.oauth_scopes = payload.oauth_scopes?.trim() || null;+ payload.auth_header = payload.auth_header?.trim() || "Authorization";+ payload.auth_scheme = payload.auth_scheme?.trim() ?? "Bearer";++ if (payload.auth_type !== "header_secret") {+ payload.ai_secret_id = null;+ }++ if (payload.auth_type !== "oauth") {+ payload.oauth_client_registration = "client_metadata_document";+ payload.oauth_client_id = null;+ payload.oauth_client_secret_ai_secret_id = null;+ payload.oauth_scopes = null;+ } else {+ payload.oauth_client_registration ||= "client_metadata_document";++ if (payload.oauth_client_registration !== "manual") {+ payload.oauth_client_id = null;+ payload.oauth_client_secret_ai_secret_id = null;+ }+ }++ return payload;+ }++ async persist(data, { transition = true, toast = true } = {}) {+ const isNew = this.args.model.isNew;++ await this.args.model.save(this.normalizeData(data));++ if (isNew) {+ this.args.mcpServers.content.push(this.args.model);+ }++ if (transition) {+ await this.router.replaceWith(+ "adminPlugins.show.discourse-ai-tools.mcp-server-edit",+ this.args.model+ );+ }++ if (toast) {+ this.toasts.success({+ data: { message: i18n("discourse_ai.mcp_servers.saved") },+ duration: "short",+ });+ }+ }++ @action+ async save(data) {+ this.isSaving = true;++ try {+ await this.persist(data);+ } catch (e) {+ popupAjaxError(e);+ } finally {+ later(() => {+ this.isSaving = false;+ }, 1000);+ }+ }++ @action+ async testConnection(data) {+ this.isTesting = true;+ this.testResult = null;++ try {+ this.testResult = await this.args.model.testConnection(+ this.normalizeData(data)+ );+ } catch (e) {+ popupAjaxError(e);+ } finally {+ this.isTesting = false;+ }+ }++ @action+ async startOAuth(data) {+ this.isConnecting = true;++ try {+ await this.persist(data, { transition: false, toast: false });+ window.location.assign(this.args.model.oauthStartPath);+ } catch (e) {+ popupAjaxError(e);+ this.isConnecting = false;+ }+ }++ @action+ async disconnectOAuth() {+ this.isDisconnecting = true;++ try {+ await this.args.model.disconnectOAuth();+ this.testResult = null;+ } catch (e) {+ popupAjaxError(e);+ } finally {+ this.isDisconnecting = false;+ }+ }++ @action+ delete() {+ return this.dialog.confirm({+ message: i18n("discourse_ai.mcp_servers.confirm_delete"),+ didConfirm: async () => {+ await this.args.model.destroyRecord();+ removeValueFromArray(this.args.mcpServers.content, this.args.model);+ this.router.transitionTo("adminPlugins.show.discourse-ai-tools.index");+ },+ });+ }++ <template>+ <Form+ @onSubmit={{this.save}}+ @data={{this.formData}}+ class="ai-tool-editor ai-mcp-server-editor"+ as |form data|+ >+ <form.Field+ @name="name"+ @title={{i18n "discourse_ai.mcp_servers.name"}}+ @validation="required|length:1,100"+ @format="large"+ @type="input"+ as |field|+ >+ <field.Control />+ </form.Field>++ <form.Field+ @name="description"+ @title={{i18n "discourse_ai.mcp_servers.description"}}+ @validation="required|length:1,1000"+ @format="large"+ @type="textarea"+ as |field|+ >+ <field.Control />+ </form.Field>++ <form.Field+ @name="url"+ @title={{i18n "discourse_ai.mcp_servers.url"}}+ @validation="required|length:1,1000"+ @onSet={{this.resetTestResult}}+ @format="large"+ @type="input"+ as |field|+ >+ <field.Control />+ </form.Field>++ <form.Field+ @name="auth_type"+ @title={{i18n "discourse_ai.mcp_servers.auth_type"}}+ @onSet={{this.resetTestResult}}+ @format="large"+ @type="select"+ as |field|+ >+ <field.Control @includeNone={{false}} as |select|>+ {{#each this.authTypes as |authType|}}+ <select.Option @value={{authType.id}}>+ {{authType.name}}+ </select.Option>+ {{/each}}+ </field.Control>+ </form.Field>++ {{#if (eq data.auth_type "header_secret")}}+ <form.Field+ @name="ai_secret_id"+ @title={{i18n "discourse_ai.mcp_servers.secret"}}+ @format="large"+ @type="custom"+ as |field|+ >+ <field.Control>+ <AiSecretSelector+ @value={{field.value}}+ @secrets={{@secrets}}+ @onChange={{field.set}}+ />+ </field.Control>+ </form.Field>++ <form.Field+ @name="auth_header"+ @title={{i18n "discourse_ai.mcp_servers.auth_header"}}+ @validation="required|length:1,100"+ @format="large"+ @type="input"+ as |field|+ >+ <field.Control />+ </form.Field>++ <form.Field+ @name="auth_scheme"+ @title={{i18n "discourse_ai.mcp_servers.auth_scheme"}}+ @format="large"+ @type="input"+ as |field|+ >+ <field.Control />+ </form.Field>+ {{/if}}++ {{#if (eq data.auth_type "oauth")}}+ <form.Field+ @name="oauth_client_registration"+ @title={{i18n "discourse_ai.mcp_servers.oauth_client_registration"}}+ @onSet={{this.resetTestResult}}+ @format="large"+ @type="select"+ as |field|+ >+ <field.Control @includeNone={{false}} as |select|>+ {{#each this.oauthClientRegistrations as |registration|}}+ <select.Option @value={{registration.id}}>+ {{registration.name}}+ </select.Option>+ {{/each}}+ </field.Control>+ </form.Field>++ {{#if (eq data.oauth_client_registration "manual")}}+ <form.Field+ @name="oauth_client_id"+ @title={{i18n "discourse_ai.mcp_servers.oauth_client_id"}}+ @validation="required|length:1,1000"+ @format="large"+ @type="input"+ as |field|+ >+ <field.Control />+ </form.Field>++ <form.Field+ @name="oauth_client_secret_ai_secret_id"+ @title={{i18n "discourse_ai.mcp_servers.oauth_client_secret"}}+ @format="large"+ @type="custom"+ as |field|+ >+ <field.Control>+ <AiSecretSelector+ @value={{field.value}}+ @secrets={{@secrets}}+ @onChange={{field.set}}+ />+ </field.Control>+ </form.Field>+ {{/if}}++ <form.Field+ @name="oauth_scopes"+ @title={{i18n "discourse_ai.mcp_servers.oauth_scopes"}}+ @format="large"+ @type="input"+ as |field|+ >+ <field.Control />+ </form.Field>++ {{#unless @model.isNew}}+ <div class="ai-mcp-server-editor__oauth-state">+ <h3>{{i18n "discourse_ai.mcp_servers.oauth_connection"}}</h3>++ <div class="ai-mcp-server-editor__oauth-row">+ <span class="ai-mcp-server-editor__oauth-label">+ {{i18n "discourse_ai.mcp_servers.oauth_status"}}+ </span>+ <span+ class="ai-tool-list__credential-badge+ {{if+ (eq @model.oauth_status 'connected')+ 'ai-tool-list__credential-badge--bound'+ 'ai-tool-list__credential-badge--missing'+ }}"+ >+ {{i18n this.oauthStatusLabelKey}}+ </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">+ {{i18n "discourse_ai.mcp_servers.oauth_last_error"}}+ </span>+ <span class="ai-mcp-server-editor__oauth-value">+ {{@model.oauth_last_error}}+ </span>+ </div>+ {{/if}}+ </div>+ {{/unless}}+ {{/if}}++ <form.Field+ @name="timeout_seconds"+ @title={{i18n "discourse_ai.mcp_servers.timeout_seconds"}}+ @tooltip={{i18n "discourse_ai.mcp_servers.timeout_seconds_tooltip"}}+ @validation="required|number"+ @format="large"+ @type="input-number"+ as |field|+ >+ <field.Control @min={{1}} @max={{300}} lang="en" />+ </form.Field>++ <form.Field+ @name="enabled"+ @title={{i18n "discourse_ai.mcp_servers.enabled"}}+ @showTitle={{false}}+ @format="large"+ @type="checkbox"+ as |field|+ >+ <field.Control />+ </form.Field>++ {{#if this.testResult}}+ <div class="ai-mcp-server-editor__test-result">+ <h3>{{i18n "discourse_ai.mcp_servers.test_result"}}</h3>+ <p>+ {{i18n+ "discourse_ai.mcp_servers.test_summary"+ count=this.testResult.tool_count+ version=this.testResult.protocol_version+ }}+ </p>+ {{#if this.testResult.tool_names.length}}+ <ul>+ {{#each this.testResult.tool_names as |toolName|}}+ <li>{{toolName}}</li>+ {{/each}}+ </ul>+ {{/if}}+ </div>+ {{/if}}++ <form.Actions>+ <form.Submit />++ {{#unless @model.isNew}}+ {{#if (eq data.auth_type "oauth")}}+ <form.Button+ @action={{fn this.startOAuth data}}+ @label={{this.oauthConnectLabelKey}}+ @isLoading={{this.isConnecting}}+ @disabled={{this.isDisconnecting}}+ class="btn-default"+ />++ {{#if this.canDisconnectOAuth}}+ <form.Button+ @action={{this.disconnectOAuth}}+ @label="discourse_ai.mcp_servers.oauth_disconnect"+ @isLoading={{this.isDisconnecting}}+ @disabled={{this.isConnecting}}+ class="btn-default"+ />+ {{/if}}+ {{/if}}++ <form.Button+ @action={{fn this.testConnection data}}+ @label="discourse_ai.mcp_servers.test"+ @isLoading={{this.isTesting}}+ @disabled={{and+ (eq data.auth_type "oauth")+ (not this.canTestOAuthConnection)+ }}+ class="btn-default"+ />++ <form.Button+ @action={{this.delete}}+ @label="discourse_ai.mcp_servers.delete"+ class="btn-danger"+ />+ {{/unless}}+ </form.Actions>+ </Form>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-mcp-server-editor.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-mcp-server-editor.gjsnew file mode 100644index 00000000000..b3064f25683--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-mcp-server-editor.gjs@@ -0,0 +1,17 @@+import BackButton from "discourse/components/back-button";+import AiMcpServerEditorForm from "./ai-mcp-server-editor-form";++const AiMcpServerEditor = <template>+ <BackButton+ @route="adminPlugins.show.discourse-ai-tools"+ @label="discourse_ai.mcp_servers.back"+ />++ <AiMcpServerEditorForm+ @model={{@model}}+ @mcpServers={{@mcpServers}}+ @secrets={{@secrets}}+ />+</template>;++export default AiMcpServerEditor;diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-secret-editor-form.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-secret-editor-form.gjsindex b4f4827691e..c0a7bb6209c 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-secret-editor-form.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-secret-editor-form.gjs@@ -136,6 +136,16 @@ export default class AiSecretEditorForm extends Component {@route="adminPlugins.show.discourse-ai-embeddings.edit"@model={{usage.id}}>{{usage.name}}</LinkTo>+ {{~else if (eq usage.type "tool")~}}+ <LinkTo+ @route="adminPlugins.show.discourse-ai-tools.edit"+ @model={{usage.id}}+ >{{usage.name}}</LinkTo>+ {{~else if (eq usage.type "mcp_server")~}}+ <LinkTo+ @route="adminPlugins.show.discourse-ai-tools.mcp-server-edit"+ @model={{usage.id}}+ >{{usage.name}}</LinkTo>{{~else~}}<LinkTo@route="adminPlugins.show.discourse-ai-llms.edit"diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-secret-selector.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-secret-selector.gjsindex 8bf41661ca9..19bbb61a50a 100644--- a/plugins/discourse-ai/assets/javascripts/discourse/components/ai-secret-selector.gjs+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/ai-secret-selector.gjs@@ -13,10 +13,15 @@ export default class AiSecretSelector extends Component {@tracked addedSecrets = [];get secretOptions() {- return [...(this.args.secrets || []), ...this.addedSecrets].map((s) => ({- id: s.id,- name: s.name,- }));+ const seen = new Set();+ const options = [];+ for (const s of [...(this.args.secrets || []), ...this.addedSecrets]) {+ if (!seen.has(s.id)) {+ seen.add(s.id);+ options.push({ id: s.id, name: s.name });+ }+ }+ return options;}get hasSecrets() {@@ -34,6 +39,7 @@ export default class AiSecretSelector extends Component {model: {onSave: (newSecret) => {this.addedSecrets = [...this.addedSecrets, newSecret];+ this.args.secrets?.push(newSecret);this.args.onChange?.(newSecret.id);},},diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-agent-mcp-tool-selector-modal.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-agent-mcp-tool-selector-modal.gjsnew file mode 100644index 00000000000..202e49c1b41--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-agent-mcp-tool-selector-modal.gjs@@ -0,0 +1,213 @@+import Component from "@glimmer/component";+import { cached, tracked } from "@glimmer/tracking";+import { fn } from "@ember/helper";+import { on } from "@ember/modifier";+import { action } from "@ember/object";+import DButton from "discourse/components/d-button";+import DModal from "discourse/components/d-modal";+import DModalCancel from "discourse/components/d-modal-cancel";+import { i18n } from "discourse-i18n";++export default class AiAgentMcpToolSelectorModal extends Component {+ @tracked filter = "";+ @tracked selectedToolNames = null;++ @cached+ get tools() {+ return [...(this.args.model?.tools || [])].sort((firstTool, secondTool) =>+ (firstTool.title || firstTool.name || "").localeCompare(+ secondTool.title || secondTool.name || ""+ )+ );+ }++ get allToolNames() {+ return this.tools.map((tool) => tool.name);+ }++ get defaultSelectedToolNames() {+ const initialSelection = this.args.model?.selectedToolNames;++ if (initialSelection?.length) {+ const availableToolNames = new Set(this.allToolNames);+ return initialSelection.filter((name) => availableToolNames.has(name));+ }++ return this.allToolNames;+ }++ get effectiveSelectedToolNames() {+ return this.selectedToolNames ?? this.defaultSelectedToolNames;+ }++ @cached+ get effectiveSelectedToolNameSet() {+ return new Set(this.effectiveSelectedToolNames);+ }++ get filteredTools() {+ const filter = this.filter.trim().toLowerCase();+ if (!filter) {+ return this.tools;+ }++ return this.tools.filter((tool) => {+ return [tool.title, tool.name, tool.description]+ .filter(Boolean)+ .some((value) => value.toLowerCase().includes(filter));+ });+ }++ get selectedCount() {+ return this.tools.filter((tool) =>+ this.effectiveSelectedToolNameSet.has(tool.name)+ ).length;+ }++ @action+ isSelected(toolName) {+ return this.effectiveSelectedToolNameSet.has(toolName);+ }++ @action+ updateFilter(event) {+ this.filter = event.target.value;+ }++ @action+ toggleTool(toolName, event) {+ if (event.target.checked) {+ this.selectedToolNames = [+ ...new Set([...this.effectiveSelectedToolNames, toolName]),+ ];+ } else {+ this.selectedToolNames = this.effectiveSelectedToolNames.filter(+ (selectedToolName) => selectedToolName !== toolName+ );+ }+ }++ @action+ selectAllVisible() {+ const selectedToolNames = new Set(this.effectiveSelectedToolNames);+ this.filteredTools.forEach((tool) => selectedToolNames.add(tool.name));+ this.selectedToolNames = this.tools+ .map((tool) => tool.name)+ .filter((toolName) => selectedToolNames.has(toolName));+ }++ @action+ clearAll() {+ this.selectedToolNames = [];+ }++ @action+ save() {+ const selectedToolNameSet = this.effectiveSelectedToolNameSet;+ const selectedToolNames = this.tools+ .map((tool) => tool.name)+ .filter((toolName) => selectedToolNameSet.has(toolName));++ if (selectedToolNames.length === 0) {+ this.args.model.onSave?.([]);+ } else if (selectedToolNames.length === this.tools.length) {+ this.args.model.onSave?.(null);+ } else {+ this.args.model.onSave?.(selectedToolNames);+ }++ this.args.closeModal();+ }++ <template>+ <DModal+ @title={{i18n+ "discourse_ai.ai_agent.mcp_tools_modal.title"+ }}+ @closeModal={{@closeModal}}+ @bodyClass="ai-agent-mcp-tools-modal__body"+ class="ai-agent-mcp-tools-modal"+ >+ <:body>+ <p class="ai-agent-mcp-tools-modal__summary">+ {{i18n "discourse_ai.ai_agent.mcp_tools_modal.summary"}}+ </p>++ <div class="ai-agent-mcp-tools-modal__controls">+ <input+ class="ai-agent-mcp-tools-modal__filter"+ type="search"+ value={{this.filter}}+ placeholder={{i18n+ "discourse_ai.ai_agent.mcp_tools_modal.filter_placeholder"+ }}+ {{on "input" this.updateFilter}}+ />++ <DButton+ @action={{this.selectAllVisible}}+ @label="discourse_ai.ai_agent.mcp_tools_modal.select_all"+ class="btn-default btn-small ai-agent-mcp-tools-modal__select-all"+ />++ <DButton+ @action={{this.clearAll}}+ @label="discourse_ai.ai_agent.mcp_tools_modal.clear_all"+ class="btn-default btn-small ai-agent-mcp-tools-modal__clear-all"+ />+ </div>++ <p class="ai-agent-mcp-tools-modal__selection-summary">+ {{i18n+ "discourse_ai.ai_agent.mcp_tools_modal.selection_summary"+ count=this.selectedCount+ total=this.tools.length+ }}+ </p>++ {{#if this.filteredTools.length}}+ {{#each this.filteredTools as |tool|}}+ <section+ class="ai-agent-mcp-tools-modal__tool"+ data-tool-name={{tool.name}}+ >+ <label class="ai-agent-mcp-tools-modal__tool-header">+ <span class="ai-agent-mcp-tools-modal__tool-checkbox">+ <input+ type="checkbox"+ checked={{this.isSelected tool.name}}+ {{on "change" (fn this.toggleTool tool.name)}}+ />+ </span>+ <span class="ai-agent-mcp-tools-modal__tool-header-content">+ <span class="ai-agent-mcp-tools-modal__tool-title">+ {{if tool.title tool.title tool.name}}+ </span>+ <code class="ai-agent-mcp-tools-modal__tool-name">+ {{tool.name}}+ </code>+ </span>+ <span class="ai-agent-mcp-tools-modal__tool-token-count">+ {{i18n+ "discourse_ai.ai_agent.mcp_server_tokens_only"+ tokens=tool.token_count+ }}+ </span>+ </label>+ </section>+ {{/each}}+ {{else}}+ <p class="ai-agent-mcp-tools-modal__empty">+ {{i18n "discourse_ai.ai_agent.mcp_tools_modal.empty"}}+ </p>+ {{/if}}+ </:body>++ <:footer>+ <DButton @action={{this.save}} @label="save" class="btn-primary" />+ <DModalCancel @close={{@closeModal}} />+ </:footer>+ </DModal>+ </template>+}diff --git a/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-mcp-server-tools-modal.gjs b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-mcp-server-tools-modal.gjsnew file mode 100644index 00000000000..184d296dfc2--- /dev/null+++ b/plugins/discourse-ai/assets/javascripts/discourse/components/modal/ai-mcp-server-tools-modal.gjs@@ -0,0 +1,80 @@+import DModal from "discourse/components/d-modal";+import { i18n } from "discourse-i18n";++<template>+ <DModal+ @title={{i18n+ "discourse_ai.mcp_servers.tools_modal.title"+ }}+ @closeModal={{@closeModal}}+ @bodyClass="ai-mcp-server-tools-modal__body"+ class="ai-mcp-server-tools-modal"+ >+ <:body>+ <p class="ai-mcp-server-tools-modal__summary">+ {{i18n+ "discourse_ai.mcp_servers.tools_modal.summary"+ }}+ </p>++ {{#each @model.tools as |tool|}}+ <section class="ai-mcp-server-tools-modal__tool">+ <div class="ai-mcp-server-tools-modal__header">+ <div class="ai-mcp-server-tools-modal__title">+ {{if tool.title tool.title tool.name}}+ </div>+ <code class="ai-mcp-server-tools-modal__name">{{tool.name}}</code>+ </div>++ {{#if tool.description}}+ <p class="ai-mcp-server-tools-modal__description">+ {{tool.description}}+ </p>+ {{/if}}++ {{#if tool.parameters.length}}+ <h3 class="ai-mcp-server-tools-modal__parameters-title">+ {{i18n "discourse_ai.mcp_servers.tools_modal.parameters"}}+ </h3>++ <ul class="ai-mcp-server-tools-modal__parameters">+ {{#each tool.parameters as |parameter|}}+ <li class="ai-mcp-server-tools-modal__parameter">+ <div class="ai-mcp-server-tools-modal__parameter-meta">+ <code class="ai-mcp-server-tools-modal__parameter-name">+ {{parameter.name}}+ </code>+ <span class="ai-mcp-server-tools-modal__parameter-type">+ {{parameter.type}}+ </span>+ {{#if parameter.required}}+ <span+ class="ai-mcp-server-tools-modal__parameter-required"+ >+ {{i18n "discourse_ai.mcp_servers.tools_modal.required"}}+ </span>+ {{/if}}+ </div>++ {{#if parameter.description}}+ <div+ class="ai-mcp-server-tools-modal__parameter-description"+ >+ {{parameter.description}}+ </div>+ {{/if}}+ </li>+ {{/each}}+ </ul>+ {{else}}+ <p class="ai-mcp-server-tools-modal__no-parameters">+ {{i18n "discourse_ai.mcp_servers.tools_modal.no_parameters"}}+ </p>+ {{/if}}+ </section>+ {{/each}}+ </:body>+ </DModal>+</template>diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-agent.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-agent.scssindex 59ee85f77e9..96a57b839ce 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-agent.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-agent.scss@@ -402,6 +402,145 @@margin-bottom: 1em;margin-top: 0.5em;}++ &__mcp-server-summary {+ margin-bottom: var(--space-4);+ padding: var(--space-3);+ border: 1px solid var(--content-border-color);+ max-width: 480px;+ }++ &__mcp-server-help {+ margin: 0 0 var(--space-3);+ max-width: 480px;+ color: var(--primary-medium);+ font-size: var(--font-down-1);+ }++ &__mcp-server-item {+ display: flex;+ justify-content: space-between;+ gap: var(--space-2);+ align-items: flex-start;+ font-size: var(--font-down-1);+ color: var(--primary-high);++ & + & {+ margin-top: var(--space-2);+ }+ }++ &__mcp-server-item-main {+ display: grid;+ gap: 0.35rem;+ }++ &__mcp-server-name {+ font-weight: 700;+ color: var(--primary);+ }++ &__mcp-server-meta {+ display: flex;+ flex-wrap: wrap;+ gap: 0.35rem 0.9rem;+ align-items: center;+ color: var(--primary-high);+ }++ &__mcp-server-action {+ flex-shrink: 0;+ }++ &__mcp-server-health {+ &.--healthy {+ color: var(--success);+ }++ &.--unhealthy {+ color: var(--danger);+ }+ }+}++.ai-agent-mcp-tools-modal {+ &__body {+ display: grid;+ gap: 1rem;+ max-height: 70vh;+ overflow-y: auto;+ }++ &__summary,+ &__selection-summary,+ &__empty {+ margin: 0;+ color: var(--primary-medium);+ }++ &__controls {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ align-items: stretch;+ }++ &__filter {+ flex: 1 1 14rem;+ min-width: 0;+ margin: 0;+ height: 2.5rem;+ box-sizing: border-box;+ }++ &__select-all,+ &__clear-all {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ height: 2.5rem;+ box-sizing: border-box;+ }++ &__tool {+ padding: 0.85rem 1rem;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);+ }++ &__tool-header {+ display: grid;+ grid-template-columns: auto 1fr auto;+ gap: 0.75rem;+ align-items: start;+ cursor: pointer;+ }++ &__tool-checkbox {+ padding-top: 0.15rem;+ }++ &__tool-header-content {+ display: grid;+ gap: 0.1rem;+ }++ &__tool-title {+ font-weight: 700;+ color: var(--primary);+ }++ &__tool-name,+ &__tool-token-count {+ color: var(--primary-medium);+ font-size: var(--font-down-1);+ }++ &__tool-name {+ background: transparent;+ padding: 0;+ border: 0;+ }}.rag-options {diff --git a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scssindex e3c5f713d03..16250c223fe 100644--- a/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss+++ b/plugins/discourse-ai/assets/stylesheets/modules/ai-bot/common/ai-tools.scss@@ -83,6 +83,17 @@margin: 0;}}++ &__section-title {+ margin: 1.25rem 0 0.5rem;+ }++ &__empty-list-buttons {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5em;+ margin-top: 1em;+ }}.ai-tool-list__credentials {@@ -117,6 +128,165 @@margin-left: 0.15em;}+.ai-tool-list__mcp-meta {+ margin-top: 0.35em;+ color: var(--primary-medium);+ font-size: var(--font-down-1);+}++.ai-tool-list__mcp-tools-button {+ padding: 0;+ border: 0;+ background: transparent;+ color: var(--tertiary);+ font: inherit;+ text-decoration: underline;+ cursor: pointer;++ &:hover,+ &:focus-visible {+ color: var(--tertiary-hover);+ text-decoration-thickness: 2px;+ }+}++.ai-mcp-server-tools-modal {+ &__body {+ display: grid;+ gap: 1rem;+ max-height: 70vh;+ overflow-y: auto;+ }++ &__summary {+ margin: 0;+ color: var(--primary-medium);+ }++ &__tool {+ padding: 1rem;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);+ }++ &__header {+ display: flex;+ flex-wrap: wrap;+ justify-content: space-between;+ gap: 0.5rem;+ align-items: baseline;+ }++ &__title {+ font-weight: 700;+ font-size: var(--font-up-1);+ }++ &__name {+ color: var(--primary-medium);+ font-size: var(--font-down-1);+ }++ &__description {+ margin: 0.5rem 0 0;+ color: var(--primary-high);+ }++ &__parameters-title {+ margin: 1rem 0 0.5rem;+ font-size: var(--font-0);+ }++ &__parameters {+ list-style: none;+ margin: 0;+ padding: 0;+ display: grid;+ gap: 0.75rem;+ }++ &__parameter {+ padding-top: 0.75rem;+ border-top: 1px solid var(--primary-low);++ &:first-child {+ padding-top: 0;+ border-top: 0;+ }+ }++ &__parameter-meta {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem;+ align-items: center;+ }++ &__parameter-type,+ &__parameter-required {+ padding: 0.1rem 0.45rem;+ border-radius: 999px;+ font-size: var(--font-down-2);+ }++ &__parameter-type {+ background: var(--primary-low);+ color: var(--primary-high);+ }++ &__parameter-required {+ background: var(--danger-low);+ color: var(--danger);+ }++ &__parameter-description,+ &__no-parameters {+ margin-top: 0.35rem;+ color: var(--primary-medium);+ }+}++.ai-mcp-server-editor {+ &__oauth-state,+ &__test-result {+ margin-bottom: 1rem;+ padding: 1rem;+ border: 1px solid var(--primary-low);+ border-radius: var(--d-border-radius);++ h3 {+ margin-top: 0;+ }++ ul {+ margin-bottom: 0;+ }+ }++ &__oauth-row {+ display: grid;+ grid-template-columns: minmax(10rem, 14rem) minmax(0, 1fr);+ gap: 0.75rem;+ align-items: start;+ margin-top: 0.75rem;++ @include viewport.until(md) {+ grid-template-columns: 1fr;+ gap: 0.25rem;+ }+ }++ &__oauth-label {+ color: var(--primary-medium);+ font-weight: 600;+ }++ &__oauth-value {+ min-width: 0;+ overflow-wrap: anywhere;+ }+}+.ai-tool-editor__templates {&-list {display: grid;diff --git a/plugins/discourse-ai/config/locales/client.en.yml b/plugins/discourse-ai/config/locales/client.en.ymlindex a2a6811b9db..fad93df189d 100644--- a/plugins/discourse-ai/config/locales/client.en.yml+++ b/plugins/discourse-ai/config/locales/client.en.yml@@ -508,6 +508,20 @@ en:ai_agent:ai_tools: "Tools"+ mcp_servers: "MCP servers"+ mcp_server_tools_help: "Selected MCP servers expose all of their tools by default. Narrow them per agent to reduce token usage and keep tool choice focused."+ mcp_server_tool_count:+ one: "%{count} tool"+ other: "%{count} tools"+ mcp_server_enabled_tool_count:+ one: "%{count} tool enabled"+ other: "%{count} tools enabled"+ mcp_server_all_tools_enabled: "All tools enabled"+ mcp_server_enabled_tools:+ one: "%{count} of %{total} tool enabled"+ other: "%{count} of %{total} tools enabled"+ mcp_server_choose_tools: "Choose tools"+ mcp_server_edit_tools: "Edit tools"tool_strategies:all: "Apply to all replies"replies:@@ -575,6 +589,21 @@ en:one: "%{count} tool"other: "%{count} tools"tool_tokens_total: "~%{tokens} Tokens"+ mcp_server_cost_name: "%{name} (MCP server)"+ mcp_server_cost_value:+ one: "~%{tokens} tokens, %{count} tool"+ other: "~%{tokens} tokens, %{count} tools"+ mcp_server_tokens_only: "~%{tokens} tokens"+ mcp_tools_modal:+ title: "%{name} tools"+ summary: "By default this agent can use every tool from this server. Select a smaller set to limit access and reduce prompt cost."+ filter_placeholder: "Filter tools"+ select_all: "Select all"+ clear_all: "Clear all"+ selection_summary:+ one: "%{count} of %{total} tool selected"+ other: "%{count} of %{total} tools selected"+ empty: "No tools match this filter."tool_severity_medium: "Moderate capacity"tool_severity_high: "High capacity"tool_severity_too_many: "Too many tools"@@ -659,6 +688,7 @@ en:tools:back: "Back to tools"short_title: "Tools"+ script_tools: "Script tools"export: "Export"import: "Import"import_error_conflict: "Tool already exists, would you like to update it?"@@ -671,7 +701,7 @@ en:tool_name_help: "Tool Name is presented to the large language model. It is not distinct, but it is distinct per agent. (agent validates on save)"description: "Description"description_help: "A clear description of the tool's purpose for the language model"- subheader_description: "Tools extend the capabilities of AI bots with user-defined JavaScript functions."+ subheader_description: "Tools and MCP servers extend the capabilities of AI agents."summary: "Summary"summary_help: "Summary of tools purpose to be displayed to end users"script: "Script"@@ -726,9 +756,80 @@ en:embedding: "Embedding"cannot_delete_in_use: "This credential cannot be deleted because it is in use by:"tool: "Tool"+ mcp_server: "MCP server"+ mcp_server_oauth_client_secret: "MCP server OAuth client secret"modal:title: "Create new credential"+ mcp_servers:+ short_title: "MCP servers"+ new: "New MCP server"+ name: "Name"+ description: "Description"+ url: "URL"+ auth_type: "Authentication"+ auth_types:+ none: "No authentication"+ header_secret: "Header credential"+ oauth: "OAuth"+ secret: "Credential"+ auth_header: "Auth header"+ auth_scheme: "Auth scheme"+ oauth_client_registration: "OAuth client registration"+ oauth_client_registration_types:+ client_metadata_document: "Client metadata document"+ manual: "Manual client credentials"+ oauth_client_id: "OAuth client ID"+ oauth_client_secret: "OAuth client secret"+ oauth_scopes: "OAuth scopes"+ oauth_connection: "OAuth connection"+ oauth_status: "OAuth status"+ oauth_statuses:+ disconnected: "Disconnected"+ connected: "Connected"+ refresh_failed: "Refresh failed"+ error: "Needs attention"+ oauth_connect: "Connect"+ oauth_reconnect: "Reconnect"+ oauth_disconnect: "Disconnect"+ oauth_connect_help: "Use Connect to save the server and authorize it."+ oauth_client_metadata_url: "Client metadata URL"+ oauth_granted_scopes: "Granted scopes"+ oauth_access_token_expires_at: "Access token expires at"+ oauth_authorization_endpoint: "Authorization endpoint"+ oauth_token_endpoint: "Token endpoint"+ oauth_revocation_endpoint: "Revocation endpoint"+ oauth_issuer: "Issuer"+ oauth_last_error: "Last OAuth error"+ 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"+ save: "Save"+ edit: "Edit"+ delete: "Delete"+ test: "Test connection"+ saved: "MCP server saved"+ confirm_delete: "Are you sure you want to delete this MCP server?"+ back: "Back to tools"+ health: "Health"+ healthy: "Healthy"+ unhealthy: "Needs attention"+ tool_count:+ one: "%{count} tool"+ other: "%{count} tools"+ tools_modal:+ title: "%{name} tools"+ summary:+ one: "This server currently exposes %{count} tool."+ other: "This server currently exposes %{count} tools."+ parameters: "Parameters"+ required: "Required"+ no_parameters: "This tool does not require any parameters."+ test_result: "Connection result"+ test_summary:+ one: "Discovered %{count} tool using protocol %{version}."+ other: "Discovered %{count} tools using protocol %{version}."+llms:short_title: "LLMs"no_llms: "No LLMs yet"diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex dd34db6646c..fadb1fe33d2 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -306,6 +306,27 @@ en:secret_not_found: "Credential alias `%{alias}` is bound to a missing credential."unknown_error: "Unable to resolve the requested credential."+ mcp_servers:+ secret_not_found: "The selected credential does not exist."+ invalid_url_not_https: "must be a valid HTTPS URL"+ invalid_url_not_reachable: "must resolve to a publicly accessible address"+ oauth_client_id_required: "OAuth client ID is required for manual client registration."+ errors:+ invalid_response: "The MCP server returned an invalid response."+ request_failed: "The MCP server request failed with status %{status}."+ session_expired: "The MCP session expired."+ timeout: "The MCP server request timed out."+ oauth_authorization_required: "OAuth authorization is required before this MCP server can be used. Connect it to %{issuer} from the admin UI."+ oauth_discovery_failed: "Unable to discover OAuth authorization details for this MCP server."+ oauth_discovery_failed_with_status: "OAuth discovery failed with status %{status}."+ oauth_not_configured: "OAuth is not configured for this MCP server."+ oauth_refresh_token_missing: "The OAuth refresh token is missing. Reconnect this MCP server."+ oauth_save_before_connect: "Save the MCP server before testing the OAuth connection."+ 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_client_metadata_public_https_required: "Client metadata document registration requires a public HTTPS site URL. Current client metadata URL: %{url}"+ai_helper:errors:completion_request_failed: "Something went wrong while trying to provide suggestions. Please, try again."@@ -913,3 +934,5 @@ en:custom_tool_exists:one: "Custom tool with the name %{names} already exists."other: "Custom tools with the names %{names} already exist."+ mcp_server_missing: "The following MCP servers are not configured on this site: %{names}."+ mcp_server_tools_not_found: "No matching tools from MCP server %{name} are available on this site."diff --git a/plugins/discourse-ai/config/routes.rb b/plugins/discourse-ai/config/routes.rbindex 30b9ff52c02..75eb021d3db 100644--- a/plugins/discourse-ai/config/routes.rb+++ b/plugins/discourse-ai/config/routes.rb@@ -75,6 +75,10 @@ DiscourseAi::Engine.routes.draw dopost "/posts/:post_id" => "translation#translate"post "/topics/:topic_id" => "translation#schedule_topic"end++ scope path: "/mcp/oauth", defaults: { format: :json } do+ get "client-metadata" => "mcp_oauth#client_metadata"+ endendDiscourse::Application.routes.draw do@@ -118,6 +122,19 @@ Discourse::Application.routes.draw dopost "/ai-tools/:id/test", to: "discourse_ai/admin/ai_tools#test"get "/ai-tools/:id/export", to: "discourse_ai/admin/ai_tools#export", format: :jsonpost "/ai-tools/import", to: "discourse_ai/admin/ai_tools#import"+ get "/ai-tools/mcp-servers/new", to: "discourse_ai/admin/ai_mcp_servers#new"+ get "/ai-tools/mcp-servers/:id/edit", to: "discourse_ai/admin/ai_mcp_servers#edit"++ resources :ai_mcp_servers,+ only: %i[index new create edit update destroy],+ path: "ai-mcp-servers",+ controller: "discourse_ai/admin/ai_mcp_servers"+ post "/ai-mcp-servers/test", to: "discourse_ai/admin/ai_mcp_servers#test"+ post "/ai-mcp-servers/:id/test", to: "discourse_ai/admin/ai_mcp_servers#test"+ get "/ai-mcp-servers/:id/oauth/start", to: "discourse_ai/admin/ai_mcp_servers#oauth_start"+ get "/ai-mcp-servers/oauth/callback", to: "discourse_ai/admin/ai_mcp_servers#oauth_callback"+ delete "/ai-mcp-servers/:id/oauth/disconnect",+ to: "discourse_ai/admin/ai_mcp_servers#oauth_disconnect"post "/rag-document-fragments/files/upload",to: "discourse_ai/admin/rag_document_fragments#upload_file"diff --git a/plugins/discourse-ai/db/migrate/20260319000000_create_ai_mcp_servers.rb b/plugins/discourse-ai/db/migrate/20260319000000_create_ai_mcp_servers.rbnew file mode 100644index 00000000000..0452cfd3bd5--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20260319000000_create_ai_mcp_servers.rb@@ -0,0 +1,27 @@+# frozen_string_literal: true++class CreateAiMcpServers < ActiveRecord::Migration[7.2]+ def change+ create_table :ai_mcp_servers do |t|+ t.string :name, null: false, limit: 100+ t.string :description, null: false, limit: 1000+ t.string :url, null: false, limit: 1000+ t.bigint :ai_secret_id+ t.string :auth_header, null: false, limit: 100, default: "Authorization"+ t.string :auth_scheme, null: false, limit: 100, default: "Bearer"+ t.boolean :enabled, null: false, default: true+ t.integer :timeout_seconds, null: false, default: 30+ t.string :last_health_status, limit: 50+ t.string :last_health_error, limit: 1000+ t.datetime :last_checked_at+ t.datetime :last_tools_synced_at+ t.jsonb :server_capabilities, null: false, default: {}+ t.string :protocol_version, limit: 100+ t.integer :created_by_id+ t.timestamps+ end++ add_index :ai_mcp_servers, :name, unique: true+ add_index :ai_mcp_servers, :ai_secret_id+ end+enddiff --git a/plugins/discourse-ai/db/migrate/20260319000001_create_ai_agent_mcp_servers.rb b/plugins/discourse-ai/db/migrate/20260319000001_create_ai_agent_mcp_servers.rbnew file mode 100644index 00000000000..b5d224ffab1--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20260319000001_create_ai_agent_mcp_servers.rb@@ -0,0 +1,14 @@+# frozen_string_literal: true++class CreateAiAgentMcpServers < ActiveRecord::Migration[7.2]+ def change+ create_table :ai_agent_mcp_servers do |t|+ t.bigint :ai_agent_id, null: false+ t.bigint :ai_mcp_server_id, null: false+ t.timestamps+ end++ add_index :ai_agent_mcp_servers, %i[ai_agent_id ai_mcp_server_id], unique: true+ add_index :ai_agent_mcp_servers, :ai_mcp_server_id+ end+enddiff --git a/plugins/discourse-ai/db/migrate/20260319033623_add_oauth_fields_to_ai_mcp_servers.rb b/plugins/discourse-ai/db/migrate/20260319033623_add_oauth_fields_to_ai_mcp_servers.rbnew file mode 100644index 00000000000..8c283b3ee47--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20260319033623_add_oauth_fields_to_ai_mcp_servers.rb@@ -0,0 +1,56 @@+# frozen_string_literal: true++class AddOauthFieldsToAiMcpServers < ActiveRecord::Migration[7.2]+ def up+ change_table :ai_mcp_servers do |t|+ t.string :auth_type, null: false, limit: 50, default: "header_secret"+ t.string :oauth_client_registration, limit: 50, default: "client_metadata_document"+ t.string :oauth_client_id, limit: 1000+ t.bigint :oauth_client_secret_ai_secret_id+ t.string :oauth_scopes, limit: 2000+ t.string :oauth_granted_scopes, limit: 2000+ t.string :oauth_token_type, limit: 100+ t.datetime :oauth_access_token_expires_at+ t.string :oauth_authorization_endpoint, limit: 1000+ t.string :oauth_token_endpoint, limit: 1000+ t.string :oauth_revocation_endpoint, limit: 1000+ t.string :oauth_issuer, limit: 1000+ t.string :oauth_resource_metadata_url, limit: 1000+ t.string :oauth_status, null: false, limit: 50, default: "disconnected"+ t.string :oauth_last_error, limit: 1000+ t.datetime :oauth_last_authorized_at+ t.datetime :oauth_last_refreshed_at+ end++ add_index :ai_mcp_servers, :oauth_client_secret_ai_secret_id++ execute <<~SQL+ UPDATE ai_mcp_servers+ SET auth_type = CASE WHEN ai_secret_id IS NULL THEN 'none' ELSE 'header_secret' END+ SQL+ end++ def down+ remove_index :ai_mcp_servers, :oauth_client_secret_ai_secret_id++ change_table :ai_mcp_servers do |t|+ t.remove :auth_type+ t.remove :oauth_client_registration+ t.remove :oauth_client_id+ t.remove :oauth_client_secret_ai_secret_id+ t.remove :oauth_scopes+ t.remove :oauth_granted_scopes+ t.remove :oauth_token_type+ t.remove :oauth_access_token_expires_at+ t.remove :oauth_authorization_endpoint+ t.remove :oauth_token_endpoint+ t.remove :oauth_revocation_endpoint+ t.remove :oauth_issuer+ t.remove :oauth_resource_metadata_url+ t.remove :oauth_status+ t.remove :oauth_last_error+ t.remove :oauth_last_authorized_at+ t.remove :oauth_last_refreshed_at+ end+ end+enddiff --git a/plugins/discourse-ai/db/migrate/20260319055039_create_ai_mcp_oauth_tokens.rb b/plugins/discourse-ai/db/migrate/20260319055039_create_ai_mcp_oauth_tokens.rbnew file mode 100644index 00000000000..75137cdad8e--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20260319055039_create_ai_mcp_oauth_tokens.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++class CreateAiMcpOauthTokens < ActiveRecord::Migration[8.0]+ def up+ create_table :ai_mcp_oauth_tokens do |t|+ t.bigint :ai_mcp_server_id, null: false+ t.text :access_token+ t.text :refresh_token++ t.timestamps+ end++ add_index :ai_mcp_oauth_tokens, :ai_mcp_server_id, unique: true+ end++ def down+ drop_table :ai_mcp_oauth_tokens+ end+enddiff --git a/plugins/discourse-ai/db/migrate/20260319070000_add_selected_tool_names_to_ai_agent_mcp_servers.rb b/plugins/discourse-ai/db/migrate/20260319070000_add_selected_tool_names_to_ai_agent_mcp_servers.rbnew file mode 100644index 00000000000..dd0bb2fd457--- /dev/null+++ b/plugins/discourse-ai/db/migrate/20260319070000_add_selected_tool_names_to_ai_agent_mcp_servers.rb@@ -0,0 +1,7 @@+# frozen_string_literal: true++class AddSelectedToolNamesToAiAgentMcpServers < ActiveRecord::Migration[7.2]+ def change+ add_column :ai_agent_mcp_servers, :selected_tool_names, :jsonb+ end+enddiff --git a/plugins/discourse-ai/lib/agents/agent.rb b/plugins/discourse-ai/lib/agents/agent.rbindex 07e549fc551..3ebabe70ba9 100644--- a/plugins/discourse-ai/lib/agents/agent.rb+++ b/plugins/discourse-ai/lib/agents/agent.rb@@ -316,32 +316,13 @@ module DiscourseAitool_klass = available_tools.find { |c| c.signature.dig(:name) == function_name }return nil if tool_klass.nil?- arguments = {}- tool_klass.signature[:parameters].to_a.each do |param|- name = param[:name]- value = tool_call.parameters[name.to_sym]-- if param[:type] == "array" && value- value =- begin- JSON.parse(value)- rescue JSON::ParserError- [value.to_s]- end- elsif param[:type] == "string" && value- value = strip_quotes(value).to_s- elsif param[:type] == "integer" && value- value = strip_quotes(value).to_i- end-- if param[:enum] && value && !param[:enum].include?(value)- # invalid enum value- value = nil+ arguments =+ if tool_klass.signature[:json_schema]+ tool_call.parameters+ else+ coerce_tool_arguments(tool_klass.signature[:parameters].to_a, tool_call)end- arguments[name.to_sym] = value if value- end-tool_instance =existing_tools.find { |t| t.name == function_name && t.tool_call_id == function_id }@@ -372,6 +353,32 @@ module DiscourseAiUploadReference.where(target_id: id, target_type: "AiAgent").exists?end+ def coerce_tool_arguments(param_defs, tool_call)+ arguments = {}+ param_defs.each do |param|+ name = param[:name]+ value = tool_call.parameters[name.to_sym]++ if param[:type] == "array" && value+ value =+ begin+ JSON.parse(value)+ rescue JSON::ParserError+ [value.to_s]+ end+ elsif param[:type] == "string" && value+ value = strip_quotes(value).to_s+ elsif param[:type] == "integer" && value+ value = strip_quotes(value).to_i+ end++ value = nil if param[:enum] && value && !param[:enum].include?(value)++ arguments[name.to_sym] = value if value+ end+ arguments+ end+def strip_quotes(value)if value.is_a?(String)if value.start_with?('"') && value.end_with?('"')diff --git a/plugins/discourse-ai/lib/agents/bot_context.rb b/plugins/discourse-ai/lib/agents/bot_context.rbindex 10c61e6cbaa..cf663ee1bb7 100644--- a/plugins/discourse-ai/lib/agents/bot_context.rb+++ b/plugins/discourse-ai/lib/agents/bot_context.rb@@ -23,7 +23,8 @@ module DiscourseAi:format_dates,:temporal_context,:user_language,- :bypass_response_format+ :bypass_response_format,+ :mcp_statedef initialize(post: nil,@@ -72,6 +73,7 @@ module DiscourseAi@cancel_manager = cancel_manager@bypass_response_format = bypass_response_format+ @mcp_state = {}if post@post_id = post.id@@ -170,6 +172,16 @@ module DiscourseAibypass_response_format: @bypass_response_format,}end++ def mcp_session_for(server_id)+ @mcp_state&.dig(server_id.to_i, :session_id)+ end++ def store_mcp_session(server_id, session_id)+ @mcp_state ||= {}+ state = (@mcp_state[server_id.to_i] ||= { session_id: nil })+ state[:session_id] = session_id+ endendendenddiff --git a/plugins/discourse-ai/lib/agents/tools/mcp.rb b/plugins/discourse-ai/lib/agents/tools/mcp.rbnew file mode 100644index 00000000000..1a3312b0970--- /dev/null+++ b/plugins/discourse-ai/lib/agents/tools/mcp.rb@@ -0,0 +1,242 @@+# frozen_string_literal: true++module DiscourseAi+ module Agents+ module Tools+ class Mcp < Tool+ class << self+ attr_accessor :server_id_value, :tool_name_value, :schema_value, :function_name_value++ def class_instance(server_id, tool_name, schema, function_name: tool_name)+ klass = Class.new(self)+ klass.server_id_value = server_id+ klass.tool_name_value = tool_name+ klass.schema_value = schema.deep_dup+ klass.function_name_value = function_name+ klass+ end++ def custom?+ true+ end++ def name+ function_name_value+ end++ def tool_name+ tool_name_value+ end++ def server_id+ server_id_value+ end++ def signature+ {+ name: function_name_value,+ description: schema_value["description"].presence || tool_name_value.humanize,+ json_schema: resolve_schema(schema_value["inputSchema"]),+ }+ end++ def placeholder_summary+ schema_value["title"].presence || schema_value.dig("annotations", "title").presence ||+ tool_name_value.humanize+ end++ def placeholder_details+ schema_value["description"].presence || placeholder_summary+ end++ private++ def resolve_schema(schema)+ return { type: "object", properties: {} } if !schema.is_a?(Hash)++ resolved = resolve_node(schema, schema)+ resolved.deep_symbolize_keys+ end++ def resolve_node(node, root)+ return node if !node.is_a?(Hash)++ node = resolve_ref(node, root) if node["$ref"]+ node = resolve_all_of(node, root) if node["allOf"]+ node = resolve_any_of(node) if node["anyOf"] || node["oneOf"]++ result = {}+ node.each do |key, value|+ next if key == "$defs" || key == "definitions"++ case value+ when Hash+ if key == "properties"+ result[key] = value.transform_values { |v| resolve_node(v, root) }+ elsif key == "items"+ result[key] = resolve_node(value, root)+ else+ result[key] = value+ end+ else+ result[key] = value+ end+ end++ result+ end++ def resolve_ref(node, root)+ ref_path = node["$ref"]+ return node if !ref_path.is_a?(String) || !ref_path.start_with?("#/")++ segments = ref_path.delete_prefix("#/").split("/")+ target = root.dig(*segments)+ return node if !target.is_a?(Hash)++ node.except("$ref").merge(target)+ end++ def resolve_all_of(node, root)+ variants = node["allOf"]+ return node if !variants.is_a?(Array)++ merged = node.except("allOf")+ variants.each do |variant|+ resolved = resolve_node(variant, root)+ next if !resolved.is_a?(Hash)++ if resolved["properties"] && merged["properties"]+ merged["properties"] = merged["properties"].merge(resolved["properties"])+ elsif resolved["properties"]+ merged["properties"] = resolved["properties"]+ end++ if resolved["required"]+ merged["required"] = Array(merged["required"]) | Array(resolved["required"])+ end++ resolved.each { |k, v| merged[k] = v if !merged.key?(k) }+ end++ merged+ end++ def resolve_any_of(node)+ variants = node["anyOf"] || node["oneOf"]+ return node if !variants.is_a?(Array)++ non_null = variants.find { |v| v.is_a?(Hash) && v["type"] != "null" } || variants.first+ non_null.is_a?(Hash) ? node.except("anyOf", "oneOf").merge(non_null) : node+ end+ end++ def summary+ self.class.placeholder_summary+ end++ def details+ return "" if parameters.blank?++ formatted_parameters+ end++ def invoke+ current_server = server+ current_context = context || DiscourseAi::Agents::BotContext.new(messages: [])++ client = DiscourseAi::Mcp::Client.new(current_server)+ result = invoke_with_session(client, current_context)++ return error_response(normalize_content(result)) if result["isError"]++ { result: normalize_content(result) }+ end++ private++ def invoke_with_session(client, current_context)+ session_id = current_context.mcp_session_for(self.class.server_id)++ if session_id.blank?+ initialized = client.initialize_session+ current_context.store_mcp_session(self.class.server_id, initialized[:session_id])+ session_id = initialized[:session_id]+ end++ client.call_tool(self.class.tool_name, parameters, session_id: session_id)+ rescue DiscourseAi::Mcp::Client::SessionExpiredError+ initialized = client.initialize_session+ current_context.store_mcp_session(self.class.server_id, initialized[:session_id])+ client.call_tool(self.class.tool_name, parameters, session_id: initialized[:session_id])+ end++ def normalize_content(result)+ content = Array(result["content"])++ text =+ content+ .filter_map do |item|+ if item["type"] == "text"+ item["text"]+ elsif item.present?+ item.to_json+ end+ end+ .join("\n")++ return text if text.present?+ if result["structuredContent"].present?+ return JSON.pretty_generate(result["structuredContent"])+ end++ result.to_json+ end++ def server+ @server ||= AiMcpServer.find(self.class.server_id)+ end++ def formatted_parameters+ format_parameter_lines(parameters.as_json).join(" \n")+ end++ def format_parameter_lines(value, prefix = nil)+ case value+ when Hash+ value.flat_map do |key, nested_value|+ nested_prefix = prefix.present? ? "#{prefix}.#{key}" : key.to_s+ format_parameter_lines(nested_value, nested_prefix)+ end+ when Array+ return ["#{prefix}: []"] if value.empty?++ if value.all? { |item| scalar_value?(item) }+ ["#{prefix}: #{value.map { |item| format_scalar(item) }.join(", ")}"]+ else+ value.flat_map.with_index do |item, index|+ format_parameter_lines(item, "#{prefix}[#{index}]")+ end+ end+ else+ ["#{prefix}: #{format_scalar(value)}"]+ end+ rescue JSON::GeneratorError, TypeError+ ["#{prefix}: #{value.to_json}"]+ end++ def scalar_value?(value)+ value.nil? || value.is_a?(String) || value.is_a?(Numeric) || value == true ||+ value == false+ end++ def format_scalar(value)+ return "null" if value.nil?+ return value if value.is_a?(String)++ value.to_s+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/completions/tool_definition.rb b/plugins/discourse-ai/lib/completions/tool_definition.rbindex 85c9bbae386..79f762d0292 100644--- a/plugins/discourse-ai/lib/completions/tool_definition.rb+++ b/plugins/discourse-ai/lib/completions/tool_definition.rb@@ -96,6 +96,8 @@ module DiscourseAienddef parameters_json_schema+ return @json_schema if @json_schema+properties = {}required = []@@ -112,15 +114,21 @@ module DiscourseAiresultend- attr_reader :name, :description, :parameters+ attr_reader :name, :description, :parameters, :json_schemadef self.from_hash(hash)- allowed_keys = %i[name description parameters]+ allowed_keys = %i[name description parameters json_schema]extra_keys = hash.keys - allowed_keysif !extra_keys.empty?raise ArgumentError, "Unexpected keys in tool definition: #{extra_keys}"end+ if hash[:json_schema]+ return(+ new(name: hash[:name], description: hash[:description], json_schema: hash[:json_schema])+ )+ end+params = hash[:parameters] || []parameter_objects =params.map do |param|@@ -134,13 +142,21 @@ module DiscourseAinew(name: hash[:name], description: hash[:description], parameters: parameter_objects)end- def initialize(name:, description:, parameters: [])+ def initialize(name:, description:, parameters: [], json_schema: nil)raise ArgumentError, "name must be a string" if !name.is_a?(String) || name.empty?if !description.is_a?(String) || description.empty?raise ArgumentError, "description must be a string"end+ if json_schema+ @name = name+ @description = description+ @parameters = []+ @json_schema = json_schema+ return+ end+raise ArgumentError, "parameters must be an array" if !parameters.is_a?(Array)# Check for duplicated parameter names@@ -156,10 +172,13 @@ module DiscourseAienddef to_h+ return { name: @name, description: @description, json_schema: @json_schema } if @json_schema{ name: @name, description: @description, parameters: @parameters.map(&:to_h) }enddef coerce_parameters(params)+ return params if @json_schema+result = {}return result if !params.is_a?(Hash)diff --git a/plugins/discourse-ai/lib/mcp/client.rb b/plugins/discourse-ai/lib/mcp/client.rbnew file mode 100644index 00000000000..446c7b75bea--- /dev/null+++ b/plugins/discourse-ai/lib/mcp/client.rb@@ -0,0 +1,294 @@+# frozen_string_literal: true++module DiscourseAi+ module Mcp+ class Client+ MCP_SESSION_ID_HEADER = "Mcp-Session-Id"+ JSONRPC_VERSION = "2.0"+ PROTOCOL_VERSION = "2025-03-26"+ USER_AGENT = "Discourse AI MCP Client"+ MAX_RESPONSE_BODY_LENGTH = 5.megabytes++ Error = Class.new(StandardError)+ AuthorizationRequiredError = Class.new(Error)+ SessionExpiredError = Class.new(Error)+ UnauthorizedError =+ Class.new(Error) do+ attr_reader :challenge_header++ def initialize(message = nil, challenge_header: nil)+ @challenge_header = challenge_header+ super(message)+ end+ end++ Response = Struct.new(:payload, :session_id, :status, :headers, keyword_init: true)++ def initialize(server)+ @server = server+ end++ def initialize_session+ response =+ post_jsonrpc(+ "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {+ tools: {+ },+ },+ clientInfo: {+ name: USER_AGENT,+ version: Discourse::VERSION::STRING,+ },+ },+ )++ result = extract_result!(response.payload)+ notify_initialized(response.session_id)++ { session_id: response.session_id, result: result }+ end++ def list_tools(session_id: nil)+ response = post_jsonrpc("tools/list", session_id: session_id)+ result = extract_result!(response.payload)+ Array(result["tools"])+ end++ def call_tool(tool_name, arguments, session_id: nil)+ response =+ post_jsonrpc(+ "tools/call",+ params: {+ name: tool_name,+ arguments: arguments,+ },+ session_id: session_id,+ accept_sse: true,+ )++ extract_result!(response.payload)+ end++ private++ attr_reader :server++ def notify_initialized(session_id)+ post_jsonrpc("notifications/initialized", session_id: session_id, notification: true)+ rescue Error => e+ Rails.logger.warn(+ "Discourse AI MCP initialize notification failed for server #{server.id}: #{e.message}",+ )+ end++ def post_jsonrpc(+ method,+ params: nil,+ session_id: nil,+ accept_sse: false,+ notification: false,+ allow_oauth_retry: true+ )+ uri = validate_uri!++ payload = { jsonrpc: JSONRPC_VERSION, method: method }+ payload[:params] = params if params.present?+ payload[:id] = SecureRandom.uuid unless notification++ headers = default_headers(session_id: session_id)+ response, raw_body = perform_request(uri, payload, headers)++ handle_response(response, raw_body, session_id: session_id)+ rescue UnauthorizedError => e+ if server.oauth? && allow_oauth_retry && server.oauth_token_store.refresh_token.present?+ DiscourseAi::Mcp::OAuthFlow.refresh!(server)++ return(+ post_jsonrpc(+ method,+ params: params,+ session_id: session_id,+ accept_sse: accept_sse,+ notification: notification,+ allow_oauth_retry: false,+ )+ )+ end++ discovery =+ DiscourseAi::Mcp::OAuthDiscovery.discover!(server, challenge_header: e.challenge_header)+ server.store_oauth_discovery!(discovery) if server.persisted?++ raise AuthorizationRequiredError,+ I18n.t(+ "discourse_ai.mcp_servers.errors.oauth_authorization_required",+ issuer: discovery.issuer,+ )+ rescue AuthorizationRequiredError+ raise+ rescue Net::ReadTimeout, Net::OpenTimeout+ raise Error, I18n.t("discourse_ai.mcp_servers.errors.timeout")+ rescue JSON::ParserError+ raise Error, I18n.t("discourse_ai.mcp_servers.errors.invalid_response")+ end++ def perform_request(uri, payload, headers)+ response = nil+ raw_body = +""+ total_bytes = 0++ FinalDestination::HTTP.start(+ uri.hostname,+ uri.port,+ use_ssl: uri.scheme == "https",+ open_timeout: server.timeout_seconds,+ read_timeout: server.timeout_seconds,+ ) do |http|+ request = FinalDestination::HTTP::Post.new(uri.request_uri)+ request["User-Agent"] = USER_AGENT+ headers.each { |key, value| request[key] = value }+ request.body = payload.to_json++ http.request(request) do |http_response|+ response = http_response+ http_response.read_body do |chunk|+ total_bytes += chunk.bytesize+ ensure_response_body_limit!(total_bytes)+ raw_body << chunk+ end+ end+ end++ [response, raw_body]+ end++ def handle_response(response, raw_body, session_id:)+ status = response.code.to_i++ if status == 404 && session_id.present?+ raise SessionExpiredError, I18n.t("discourse_ai.mcp_servers.errors.session_expired")+ end++ if status == 401 && server.oauth?+ raise UnauthorizedError.new(+ I18n.t("discourse_ai.mcp_servers.errors.request_failed", status: status),+ challenge_header: response["WWW-Authenticate"],+ )+ end++ body =+ if response["Content-Type"].to_s.include?("text/event-stream")+ parse_sse_body(raw_body)+ else+ parse_json_body(raw_body)+ end++ if status < 200 || status >= 300+ message = body.is_a?(Hash) ? body.dig("error", "message") : nil+ raise Error,+ message.presence ||+ I18n.t("discourse_ai.mcp_servers.errors.request_failed", status: status)+ end++ Response.new(+ payload: body,+ session_id: response[MCP_SESSION_ID_HEADER],+ status: status,+ headers: response.to_hash,+ )+ end++ def parse_json_body(body)+ return {} if body.blank?++ JSON.parse(body)+ end++ def parse_sse_body(raw_body)+ events = []+ buffer = raw_body.dup++ while (separator = sse_separator_end(buffer))+ event = parse_sse_event(buffer.slice!(0, separator))+ events << event if event.present?+ end++ event = parse_sse_event(buffer)+ events << event if event.present?++ events.reverse_each.find do |payload|+ payload.is_a?(Hash) && (payload.key?("result") || payload.key?("error"))+ end || {}+ end++ def default_headers(session_id:)+ ensure_oauth_access_token! if server.oauth?++ headers = {+ "Content-Type" => "application/json",+ "Accept" => "application/json, text/event-stream",+ }++ if server.auth_header.present? && server.auth_header_value.present?+ headers[server.auth_header] = server.auth_header_value+ end++ headers[MCP_SESSION_ID_HEADER] = session_id if session_id.present?+ headers+ end++ def extract_result!(payload)+ error = payload["error"]+ if error.present?+ raise Error,+ error["message"].presence ||+ I18n.t("discourse_ai.mcp_servers.errors.invalid_response")+ end++ payload["result"] || {}+ end++ def validate_uri!+ uri = AiMcpServer.parse_public_uri(server.url)+ raise Error, I18n.t("discourse_ai.mcp_servers.invalid_url_not_https") if uri.nil?++ AiMcpServer.validate_hostname_public!(uri.hostname)+ uri+ rescue FinalDestination::SSRFError, SocketError, URI::InvalidURIError+ raise Error, I18n.t("discourse_ai.mcp_servers.invalid_url_not_reachable")+ end++ def ensure_response_body_limit!(size)+ return if size <= MAX_RESPONSE_BODY_LENGTH++ raise Error, I18n.t("discourse_ai.mcp_servers.errors.invalid_response")+ end++ def ensure_oauth_access_token!+ return if !server.oauth? || !server.oauth_needs_refresh?++ DiscourseAi::Mcp::OAuthFlow.refresh!(server)+ end++ def sse_separator_end(buffer)+ buffer.match(/\r?\n\r?\n/)&.end(0)+ end++ def parse_sse_event(raw_event)+ data =+ raw_event+ .lines(chomp: true)+ .grep(/\Adata:/)+ .map { |line| line.sub(/\Adata:\s?/, "") }+ .join("\n")++ return if data.blank? || data == "[DONE]"++ JSON.parse(data)+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/mcp/oauth_discovery.rb b/plugins/discourse-ai/lib/mcp/oauth_discovery.rbnew file mode 100644index 00000000000..e6cca82d769--- /dev/null+++ b/plugins/discourse-ai/lib/mcp/oauth_discovery.rb@@ -0,0 +1,142 @@+# frozen_string_literal: true++module DiscourseAi+ module Mcp+ class OAuthDiscovery+ Result =+ Struct.new(+ :resource,+ :resource_metadata_url,+ :issuer,+ :authorization_endpoint,+ :token_endpoint,+ :revocation_endpoint,+ keyword_init: true,+ )++ class << self+ def discover!(server, challenge_header: nil)+ resource_metadata_url =+ challenge_parameters(challenge_header)["resource_metadata"] ||+ default_well_known_url(server.url, "oauth-protected-resource")++ resource_metadata = get_json!(server, resource_metadata_url)+ issuer =+ Array(resource_metadata["authorization_servers"]).first ||+ resource_metadata["authorization_server"]+ if issuer.blank?+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.oauth_discovery_failed")+ end++ auth_server_metadata =+ get_json!(server, default_well_known_url(issuer, "oauth-authorization-server"))+ authorization_endpoint = auth_server_metadata["authorization_endpoint"].presence+ token_endpoint = auth_server_metadata["token_endpoint"].presence++ if authorization_endpoint.blank? || token_endpoint.blank?+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.oauth_discovery_failed")+ end++ validate_discovered_url!(authorization_endpoint)+ validate_discovered_url!(token_endpoint)++ revocation_endpoint = auth_server_metadata["revocation_endpoint"].presence+ validate_discovered_url!(revocation_endpoint) if revocation_endpoint.present?++ Result.new(+ resource: resource_metadata["resource"].presence || server.url,+ resource_metadata_url: resource_metadata_url,+ issuer: auth_server_metadata["issuer"].presence || issuer,+ authorization_endpoint: authorization_endpoint,+ token_endpoint: token_endpoint,+ revocation_endpoint: revocation_endpoint,+ )+ end++ def challenge_parameters(header)+ value = header.to_s[/Bearer\s+(.+)\z/i, 1]+ return {} if value.blank?++ value+ .scan(/([a-zA-Z_]+)="([^"]*)"|([a-zA-Z_]+)=([^,\s]+)/)+ .each_with_object({}) do |parts, hash|+ key = parts[0] || parts[2]+ parsed_value = parts[1] || parts[3]+ hash[key] = parsed_value if key.present?+ end+ end++ def default_well_known_url(raw_url, suffix)+ uri = AiMcpServer.parse_public_uri(raw_url)+ if uri.nil?+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.invalid_url_not_https")+ end++ path = uri.path.to_s+ path = "" if path == "/"+ path = path.sub(%r{/\z}, "")++ duplicated = uri.dup+ duplicated.path = "/.well-known/#{suffix}#{path}"+ duplicated.query = nil+ duplicated.to_s+ end++ private++ def get_json!(server, 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)++ response = nil+ FinalDestination::HTTP.start(+ uri.hostname,+ uri.port,+ use_ssl: true,+ open_timeout: server.timeout_seconds,+ read_timeout: server.timeout_seconds,+ ) do |http|+ request = FinalDestination::HTTP::Get.new(uri.request_uri)+ request["Accept"] = "application/json"+ request["User-Agent"] = DiscourseAi::Mcp::Client::USER_AGENT+ response = http.request(request)+ end++ if response.code.to_i != 200+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t(+ "discourse_ai.mcp_servers.errors.oauth_discovery_failed_with_status",+ status: response.code.to_i,+ )+ end++ JSON.parse(response.body.presence || "{}")+ rescue JSON::ParserError+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.oauth_discovery_failed")+ end++ def validate_discovered_url!(url)+ uri = AiMcpServer.parse_public_uri(url)+ if uri.nil?+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.oauth_discovery_failed")+ end++ AiMcpServer.validate_hostname_public!(uri.hostname)+ rescue FinalDestination::SSRFError, SocketError, URI::InvalidURIError+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.oauth_discovery_failed")+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/mcp/oauth_flow.rb b/plugins/discourse-ai/lib/mcp/oauth_flow.rbnew file mode 100644index 00000000000..b8e404fc12d--- /dev/null+++ b/plugins/discourse-ai/lib/mcp/oauth_flow.rb@@ -0,0 +1,293 @@+# frozen_string_literal: true++require "base64"+require "openssl"++module DiscourseAi+ module Mcp+ class OAuthFlow+ STATE_TTL = 10.minutes++ class << self+ def start!(server:, user:)+ validate_local_oauth_urls!(server)++ discovery = OAuthDiscovery.discover!(server)+ server.store_oauth_discovery!(discovery)++ state = SecureRandom.hex(32)+ code_verifier = generate_code_verifier+ Rails.cache.write(+ state_cache_key(state),+ {+ "ai_mcp_server_id" => server.id,+ "user_id" => user.id,+ "code_verifier" => code_verifier,+ },+ expires_in: STATE_TTL,+ )++ build_authorization_url(+ server: server,+ discovery: discovery,+ state: state,+ code_verifier: code_verifier,+ )+ end++ def complete!(params:, current_user:)+ state = params[:state].to_s+ payload = Rails.cache.read(state_cache_key(state))+ Rails.cache.delete(state_cache_key(state))++ if payload.blank? || payload["user_id"].to_i != current_user.id+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.oauth_state_invalid")+ end++ server = AiMcpServer.find(payload["ai_mcp_server_id"])+ if params[:error].present?+ raise DiscourseAi::Mcp::Client::Error,+ params[:error_description].presence || params[:error].to_s.tr("_", " ")+ end++ discovery = server.oauth_discovery_result || OAuthDiscovery.discover!(server)+ token_payload =+ token_request(+ server: server,+ endpoint: discovery.token_endpoint,+ params: {+ grant_type: "authorization_code",+ code: params[:code].to_s,+ redirect_uri: server.oauth_callback_url,+ code_verifier: payload["code_verifier"],+ client_id: server.effective_oauth_client_id,+ resource: discovery.resource.presence || server.url,+ },+ )++ store_token_response!(server, token_payload, preserve_refresh_token: false)+ server.mark_oauth_authorized!+ DiscourseAi::Mcp::ToolRegistry.invalidate!(server.id)+ AiAgent.agent_cache.flush!+ server+ rescue StandardError => e+ server&.mark_oauth_error!(e.message)+ raise+ end++ def refresh!(server)+ discovery = server.oauth_discovery_result || OAuthDiscovery.discover!(server)+ refresh_token = server.oauth_token_store.refresh_token+ if refresh_token.blank?+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.oauth_refresh_token_missing")+ end++ token_payload =+ token_request(+ server: server,+ endpoint: discovery.token_endpoint,+ params: {+ grant_type: "refresh_token",+ refresh_token: refresh_token,+ client_id: server.effective_oauth_client_id,+ resource: discovery.resource.presence || server.url,+ },+ )++ store_token_response!(server, token_payload, preserve_refresh_token: true)+ token_payload["access_token"]+ rescue StandardError => e+ server.mark_oauth_refresh_failed!(e.message)+ raise+ end++ def disconnect!(server)+ discovery = server.oauth_discovery_result++ if discovery&.revocation_endpoint.present?+ revoke_token(+ server,+ discovery.revocation_endpoint,+ server.oauth_token_store.access_token,+ )+ revoke_token(+ server,+ discovery.revocation_endpoint,+ server.oauth_token_store.refresh_token,+ )+ end++ server.clear_oauth_credentials!+ DiscourseAi::Mcp::ToolRegistry.invalidate!(server.id)+ AiAgent.agent_cache.flush!+ end++ private++ def build_authorization_url(server:, discovery:, state:, code_verifier:)+ code_challenge =+ Base64.urlsafe_encode64(Digest::SHA256.digest(code_verifier)).tr("+/", "-_").delete("=")++ query = {+ response_type: "code",+ client_id: server.effective_oauth_client_id,+ redirect_uri: server.oauth_callback_url,+ state: state,+ code_challenge: code_challenge,+ code_challenge_method: "S256",+ resource: discovery.resource.presence || server.url,+ }+ query[:scope] = server.oauth_scopes if server.oauth_scopes.present?++ uri = URI(discovery.authorization_endpoint)+ uri.query = Rack::Utils.build_query(query)+ uri.to_s+ end++ def token_request(server:, endpoint:, params:)+ connection =+ Faraday.new(request: { timeout: server.timeout_seconds }) do |builder|+ builder.request :url_encoded+ builder.adapter FinalDestination::FaradayAdapter+ end++ validate_endpoint!(endpoint)++ headers = { "Accept" => "application/json" }+ if server.oauth_client_registration == "manual" &&+ server.oauth_client_secret_value.present?+ headers["Authorization"] = basic_auth_header(+ server.effective_oauth_client_id,+ server.oauth_client_secret_value,+ )+ end++ response = connection.post(endpoint, params, headers)++ if response.status != 200+ message =+ begin+ JSON.parse(response.body).dig("error_description")+ rescue StandardError+ nil+ end+ raise DiscourseAi::Mcp::Client::Error,+ message.presence ||+ I18n.t(+ "discourse_ai.mcp_servers.errors.oauth_token_exchange_failed",+ status: response.status,+ )+ end++ JSON.parse(response.body)+ rescue JSON::ParserError+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.invalid_response")+ end++ def store_token_response!(server, token_payload, preserve_refresh_token:)+ refresh_token =+ if preserve_refresh_token+ token_payload["refresh_token"].presence || server.oauth_token_store.refresh_token+ else+ token_payload["refresh_token"]+ end++ server.update_oauth_tokens!(+ access_token: token_payload["access_token"],+ refresh_token: refresh_token,+ token_type: token_payload["token_type"],+ expires_in: token_payload["expires_in"],+ granted_scopes: token_payload["scope"],+ )+ end++ def revoke_token(server, endpoint, token)+ return if token.blank?++ validate_endpoint!(endpoint)++ connection =+ Faraday.new(request: { timeout: server.timeout_seconds }) do |builder|+ builder.request :url_encoded+ builder.adapter FinalDestination::FaradayAdapter+ end++ headers = { "Accept" => "application/json" }+ if server.oauth_client_registration == "manual" &&+ server.oauth_client_secret_value.present?+ headers["Authorization"] = basic_auth_header(+ server.effective_oauth_client_id,+ server.oauth_client_secret_value,+ )+ end++ connection.post(+ endpoint,+ { token: token, client_id: server.effective_oauth_client_id },+ headers,+ )+ rescue StandardError => e+ Rails.logger.warn(+ "Discourse AI MCP OAuth revoke failed for server #{server.id}: #{e.message}",+ )+ end++ def basic_auth_header(client_id, client_secret)+ "Basic #{Base64.strict_encode64("#{client_id}:#{client_secret}")}"+ end++ def generate_code_verifier+ Base64.urlsafe_encode64(OpenSSL::Random.random_bytes(32)).delete("=")+ end++ def state_cache_key(state)+ "discourse-ai:mcp-oauth-state:#{state}"+ 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++ def validate_local_oauth_urls!(server)+ callback_uri = URI.parse(server.oauth_callback_url)+ if callback_uri.scheme != "https"+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.oauth_https_required")+ end++ return if server.oauth_client_registration == "manual"++ metadata_url = server.oauth_client_metadata_url+ metadata_uri = AiMcpServer.parse_public_uri(metadata_url)+ if metadata_uri.nil?+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t(+ "discourse_ai.mcp_servers.errors.oauth_client_metadata_public_https_required",+ url: metadata_url,+ )+ end++ AiMcpServer.validate_hostname_public!(metadata_uri.hostname)+ rescue FinalDestination::SSRFError, SocketError, URI::InvalidURIError+ raise DiscourseAi::Mcp::Client::Error,+ I18n.t(+ "discourse_ai.mcp_servers.errors.oauth_client_metadata_public_https_required",+ url: server.oauth_client_metadata_url,+ )+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/mcp/oauth_token_store.rb b/plugins/discourse-ai/lib/mcp/oauth_token_store.rbnew file mode 100644index 00000000000..9ca815fa5ef--- /dev/null+++ b/plugins/discourse-ai/lib/mcp/oauth_token_store.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++module DiscourseAi+ module Mcp+ class OAuthTokenStore+ def initialize(server)+ @server = server+ end++ def access_token+ record&.access_token+ end++ def refresh_token+ record&.refresh_token+ end++ def write!(access_token:, refresh_token:)+ oauth_token = record || server.build_oauth_token+ oauth_token.access_token = access_token unless access_token.nil?+ oauth_token.refresh_token = refresh_token unless refresh_token.nil?++ if oauth_token.access_token.blank? && oauth_token.refresh_token.blank?+ oauth_token.destroy! if oauth_token.persisted?+ else+ oauth_token.save!+ end++ reset_association_cache+ end++ def clear!+ record&.destroy!+ reset_association_cache+ end++ private++ attr_reader :server++ def record+ server.oauth_token+ end++ def reset_association_cache+ server.association(:oauth_token).reset+ end+ end+ end+enddiff --git a/plugins/discourse-ai/lib/mcp/tool_registry.rb b/plugins/discourse-ai/lib/mcp/tool_registry.rbnew file mode 100644index 00000000000..860c4f6be29--- /dev/null+++ b/plugins/discourse-ai/lib/mcp/tool_registry.rb@@ -0,0 +1,152 @@+# frozen_string_literal: true++module DiscourseAi+ module Mcp+ class ToolRegistry+ CACHE_VERSION = 1+ CACHE_TTL = 1.hour++ class << self+ def cache_key(server_id)+ current_db = RailsMultisite::ConnectionManagement.current_db+ "discourse-ai:mcp-tools:v#{CACHE_VERSION}:#{current_db}:#{server_id}"+ end++ def invalidate!(server_id)+ Rails.cache.delete(cache_key(server_id))+ end++ def tool_definitions_for(server)+ payload = Rails.cache.read(cache_key(server.id))++ return refresh!(server, raise_on_error: false) if payload.blank?++ if Time.zone.parse(payload["expires_at"]) <= Time.zone.now+ Jobs.enqueue(:refresh_ai_mcp_server_tools, ai_mcp_server_id: server.id)+ end++ Array(payload["definitions"])+ rescue ArgumentError+ refresh!(server, raise_on_error: false)+ end++ def refresh!(server, raise_on_error: false)+ client = DiscourseAi::Mcp::Client.new(server)+ initialized = client.initialize_session+ definitions = client.list_tools(session_id: initialized[:session_id])+ write_cache(server.id, definitions)++ server.update_columns(+ last_health_status: "healthy",+ last_health_error: nil,+ last_checked_at: Time.zone.now,+ last_tools_synced_at: Time.zone.now,+ protocol_version: initialized[:result]["protocolVersion"],+ server_capabilities: initialized[:result]["capabilities"] || {},+ )++ definitions+ rescue StandardError => e+ server.update_columns(+ last_health_status: "error",+ last_health_error: e.message.truncate(1000),+ last_checked_at: Time.zone.now,+ )++ cached = Rails.cache.read(cache_key(server.id))+ return Array(cached&.dig("definitions")) if cached.present? && !raise_on_error++ raise if raise_on_error++ []+ end++ def tool_classes_for_servers(servers, reserved_names: [], selected_tool_names_by_server: {})+ servers = Array(servers).select { |server| !server.oauth? || server.oauth_connected? }++ definitions_by_server =+ servers.each_with_object({}) do |server, hash|+ definitions = tool_definitions_for(server)+ selected_tool_names =+ normalize_selected_tool_names(selected_tool_names_by_server, server)++ hash[server] = if selected_tool_names.blank?+ definitions+ else+ definitions.select do |definition|+ selected_tool_names.include?(definition["name"].to_s)+ end+ end+ end++ original_names =+ definitions_by_server.values.flatten.filter_map do |definition|+ definition["name"].presence+ end+ name_counts = original_names.tally+ taken_names = reserved_names.map(&:downcase).to_set++ definitions_by_server.flat_map do |server, definitions|+ definitions.filter_map do |definition|+ tool_name = definition["name"].to_s+ next if tool_name.blank?++ function_name =+ unique_function_name(+ tool_name,+ server,+ taken_names,+ needs_namespace: name_counts[tool_name].to_i > 1,+ )++ taken_names << function_name.downcase++ DiscourseAi::Agents::Tools::Mcp.class_instance(+ server.id,+ tool_name,+ definition,+ function_name: function_name,+ )+ end+ end+ end++ private++ def normalize_selected_tool_names(selected_tool_names_by_server, server)+ selected_tool_names_by_server[server.id] || selected_tool_names_by_server[server.id.to_s]+ end++ def write_cache(server_id, definitions)+ now = Time.zone.now+ Rails.cache.write(+ cache_key(server_id),+ {+ "definitions" => definitions,+ "fetched_at" => now.iso8601,+ "expires_at" => (now + CACHE_TTL).iso8601,+ },+ expires_in: CACHE_TTL * 2,+ )+ end++ def unique_function_name(original_name, server, taken_names, needs_namespace:)+ candidate = original_name++ if needs_namespace || taken_names.include?(candidate.downcase)+ prefix = server.name.to_s.parameterize(separator: "_").presence || "server_#{server.id}"+ candidate = "#{prefix}__#{original_name}"+ end++ suffix = 2+ while taken_names.include?(candidate.downcase)+ candidate = "#{candidate}_#{suffix}"+ suffix += 1+ end++ candidate+ end+ end+ end+ end+enddiff --git a/plugins/discourse-ai/plugin.rb b/plugins/discourse-ai/plugin.rbindex 1005cb48886..e381a93a7b1 100644--- a/plugins/discourse-ai/plugin.rb+++ b/plugins/discourse-ai/plugin.rb@@ -69,6 +69,9 @@ Rails.autoloaders.main.push_dir(File.join(__dir__, "lib"), namespace: DiscourseArequire_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_flow"DiscourseAi::Configuration::Module::NAMES.each do |module_name|register_site_setting_area("ai-features/#{module_name}")diff --git a/plugins/discourse-ai/spec/fabricators/ai_mcp_server_fabricator.rb b/plugins/discourse-ai/spec/fabricators/ai_mcp_server_fabricator.rbnew file mode 100644index 00000000000..a840944e6c6--- /dev/null+++ b/plugins/discourse-ai/spec/fabricators/ai_mcp_server_fabricator.rb@@ -0,0 +1,11 @@+# frozen_string_literal: true++Fabricator(:ai_mcp_server) do+ name { sequence(:name) { |n| "MCP Server #{n}" } }+ description "External MCP server"+ url { sequence(:url) { |n| "https://mcp#{n}.example.com" } }+ auth_header "Authorization"+ auth_scheme "Bearer"+ enabled true+ timeout_seconds 30+enddiff --git a/plugins/discourse-ai/spec/lib/agents/tools/mcp_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/mcp_spec.rbnew file mode 100644index 00000000000..1b093841400--- /dev/null+++ b/plugins/discourse-ai/spec/lib/agents/tools/mcp_spec.rb@@ -0,0 +1,156 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Agents::Tools::Mcp do+ fab!(:user)+ fab!(:ai_mcp_server)++ before { enable_current_plugin }++ def tool_class+ described_class.class_instance(+ ai_mcp_server.id,+ "search_issues",+ {+ "title" => "Search issues",+ "name" => "search_issues",+ "description" => "Search issues across external MCP data sources.",+ "inputSchema" => {+ "type" => "object",+ "properties" => {+ "query" => {+ "type" => "string",+ "description" => "Search query",+ },+ },+ "required" => ["query"],+ },+ },+ )+ end++ it "passes through the raw JSON schema with anyOf/oneOf/allOf/$ref resolved" do+ klass =+ described_class.class_instance(+ ai_mcp_server.id,+ "search",+ {+ "name" => "search",+ "description" => "Search",+ "inputSchema" => {+ "type" => "object",+ "$defs" => {+ "StatusFilter" => {+ "type" => "object",+ "properties" => {+ "status" => {+ "type" => "string",+ },+ },+ },+ },+ "properties" => {+ "places" => {+ "anyOf" => [+ { "items" => { "type" => "string" }, "type" => "array" },+ { "type" => "null" },+ ],+ "default" => nil,+ },+ "mode" => {+ "oneOf" => [{ "type" => "integer" }, { "type" => "null" }],+ },+ "ids" => {+ "type" => "array",+ "items" => {+ "anyOf" => [{ "type" => "integer" }, { "type" => "null" }],+ },+ },+ "sort" => {+ "anyOf" => [{ "type" => "string", "enum" => %w[asc desc] }, { "type" => "null" }],+ "description" => "Sort order",+ },+ "filter" => {+ "$ref" => "#/$defs/StatusFilter",+ },+ "combined" => {+ "allOf" => [+ { "type" => "object", "properties" => { "a" => { "type" => "string" } } },+ { "properties" => { "b" => { "type" => "integer" } }, "required" => ["b"] },+ ],+ },+ },+ "required" => %w[places],+ },+ },+ )++ sig = klass.signature+ schema = sig[:json_schema]++ expect(schema[:properties][:places][:type]).to eq("array")+ expect(schema[:properties][:places][:items]).to eq({ type: "string" })++ expect(schema[:properties][:mode][:type]).to eq("integer")++ expect(schema[:properties][:ids][:type]).to eq("array")+ expect(schema[:properties][:ids][:items][:type]).to eq("integer")++ expect(schema[:properties][:sort][:type]).to eq("string")+ expect(schema[:properties][:sort][:enum]).to eq(%w[asc desc])+ expect(schema[:properties][:sort][:description]).to eq("Sort order")++ expect(schema[:properties][:filter][:type]).to eq("object")+ expect(schema[:properties][:filter][:properties][:status][:type]).to eq("string")++ expect(schema[:properties][:combined][:type]).to eq("object")+ expect(schema[:properties][:combined][:properties][:a][:type]).to eq("string")+ expect(schema[:properties][:combined][:properties][:b][:type]).to eq("integer")+ expect(schema[:properties][:combined][:required]).to eq(["b"])++ expect(schema[:required]).to eq(%w[places])+ expect(schema).not_to have_key(:"$defs")+ end++ it "uses a short title in thinking summaries and renders the invocation parameters in details" do+ tool = tool_class.new({ query: "bug" }, bot_user: user, llm: nil)++ expect(tool.summary).to eq("Search issues")+ expect(tool.details).to eq("query: bug")+ end++ it "invokes the remote tool and stores the turn session" do+ context = DiscourseAi::Agents::BotContext.new(messages: [])+ DiscourseAi::Mcp::Client+ .any_instance+ .stubs(:initialize_session)+ .returns({ session_id: "session-1", result: {} })+ DiscourseAi::Mcp::Client+ .any_instance+ .stubs(:call_tool)+ .returns({ "content" => [{ "type" => "text", "text" => "Found results" }] })++ tool = tool_class.new({ query: "bug" }, bot_user: user, llm: nil, context: context)++ expect(tool.invoke).to eq({ result: "Found results" })+ expect(context.mcp_session_for(ai_mcp_server.id)).to eq("session-1")+ end++ it "reuses the same turn session across multiple invocations" do+ context = DiscourseAi::Agents::BotContext.new(messages: [])+ DiscourseAi::Mcp::Client+ .any_instance+ .stubs(:initialize_session)+ .returns({ session_id: "session-1", result: {} })+ DiscourseAi::Mcp::Client+ .any_instance+ .stubs(:call_tool)+ .returns({ "content" => [{ "type" => "text", "text" => "Found results" }] })++ first = tool_class.new({ query: "bug" }, bot_user: user, llm: nil, context: context)+ second = tool_class.new({ query: "feature" }, bot_user: user, llm: nil, context: context)++ expect(first.invoke).to eq({ result: "Found results" })+ expect(second.invoke).to eq({ result: "Found results" })+ expect(context.mcp_session_for(ai_mcp_server.id)).to eq("session-1")+ end+enddiff --git a/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rb b/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rbindex 42dea0067c8..43f3dd5b588 100644--- a/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rb+++ b/plugins/discourse-ai/spec/lib/completions/cancel_manager_spec.rb@@ -6,13 +6,12 @@ describe DiscourseAi::Completions::CancelManager dobefore doenable_current_pluginWebMock.disable!- FinalDestination::SSRFDetector.allow_ip_lookups_in_test!- SiteSetting.allowed_internal_hosts = "127.0.0.1"+ FinalDestination::SSRFDetector.stubs(:lookup_and_filter_ips).returns(["127.0.0.1"])endafter do+ FinalDestination::SSRFDetector.unstub(:lookup_and_filter_ips)WebMock.enable!- FinalDestination::SSRFDetector.allow_ip_lookups_in_test!endit "can stop monitoring for cancellation cleanly" dodiff --git a/plugins/discourse-ai/spec/lib/mcp/client_spec.rb b/plugins/discourse-ai/spec/lib/mcp/client_spec.rbnew file mode 100644index 00000000000..fe2a5ca13f0--- /dev/null+++ b/plugins/discourse-ai/spec/lib/mcp/client_spec.rb@@ -0,0 +1,194 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Mcp::Client do+ fab!(:ai_secret)+ fab!(:server) { Fabricate(:ai_mcp_server, ai_secret: ai_secret, url: "https://mcp.example.com") }++ before do+ enable_current_plugin+ AiMcpServer.stubs(:validate_hostname_public!).returns(true)+ end++ describe "#initialize_session" do+ it "initializes a session and notifies the server" do+ stub_request(:post, server.url).to_return(+ {+ status: 200,+ body: <<~SSE,+ event: message+ data: {"jsonrpc":"2.0","result":{"protocolVersion":"2025-03-26","capabilities":{"tools":{}}}}++ SSE+ headers: {+ "Content-Type" => "text/event-stream",+ "Mcp-Session-Id" => "session-1",+ },+ },+ { status: 202, body: "", headers: { "Content-Type" => "application/json" } },+ )++ result = described_class.new(server).initialize_session++ expect(result).to eq(+ session_id: "session-1",+ result: {+ "protocolVersion" => "2025-03-26",+ "capabilities" => {+ "tools" => {+ },+ },+ },+ )++ expect(+ a_request(:post, server.url).with do |request|+ payload = JSON.parse(request.body)++ payload["method"] == "initialize" &&+ request.headers["Accept"] == "application/json, text/event-stream" &&+ request.headers["Authorization"] == "Bearer #{ai_secret.secret}"+ end,+ ).to have_been_made.once++ expect(+ a_request(:post, server.url).with do |request|+ payload = JSON.parse(request.body)++ payload["method"] == "notifications/initialized" &&+ request.headers["Accept"] == "application/json, text/event-stream" &&+ request.headers["Mcp-Session-Id"] == "session-1"+ end,+ ).to have_been_made.once+ end+ end++ describe "#call_tool" do+ it "parses streamable HTTP SSE responses with CRLF separators" do+ stub_request(:post, server.url).to_return(+ status: 200,+ body: [+ %(event: message\r\ndata: {"jsonrpc":"2.0","params":{"progress":0.5}}\r\n\r\n),+ %(event: message\r\ndata: {"jsonrpc":"2.0","result":{"content":[{"type":"text","text":"Hello from MCP"}]}}\r\n\r\n),+ %(data: [DONE]\r\n\r\n),+ ].join,+ headers: {+ "Content-Type" => "text/event-stream",+ },+ )++ result = described_class.new(server).call_tool("lookup", { id: 1 }, session_id: "session-1")++ expect(result).to eq("content" => [{ "type" => "text", "text" => "Hello from MCP" }])+ end++ it "raises when a session expires" do+ stub_request(:post, server.url).to_return(+ status: 404,+ body: "",+ headers: {+ "Content-Type" => "application/json",+ },+ )++ expect do+ described_class.new(server).call_tool("lookup", {}, session_id: "session-1")+ end.to raise_error(+ described_class::SessionExpiredError,+ I18n.t("discourse_ai.mcp_servers.errors.session_expired"),+ )+ end+ end++ describe "OAuth flows" do+ it "raises an authorization error when OAuth authorization is required" do+ server.update!(auth_type: "oauth", ai_secret_id: nil, oauth_status: "disconnected")+ discovery =+ DiscourseAi::Mcp::OAuthDiscovery::Result.new(+ resource: server.url,+ resource_metadata_url: "#{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,+ )++ DiscourseAi::Mcp::OAuthDiscovery.stubs(:discover!).returns(discovery)+ stub_request(:post, server.url).to_return(+ status: 401,+ body: "",+ headers: {+ "Content-Type" => "application/json",+ "WWW-Authenticate" =>+ 'Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource"',+ },+ )++ expect { described_class.new(server).initialize_session }.to raise_error(+ described_class::AuthorizationRequiredError,+ I18n.t(+ "discourse_ai.mcp_servers.errors.oauth_authorization_required",+ issuer: "https://auth.example.com",+ ),+ )+ end++ it "refreshes once and retries when an OAuth token is rejected" do+ server.update!(auth_type: "oauth", ai_secret_id: nil, oauth_status: "connected")+ server.oauth_token_store.write!(+ access_token: "expired-access-token",+ refresh_token: "refresh-token",+ )++ server.stubs(:auth_header_value).returns(+ "Bearer expired-access-token",+ "Bearer fresh-access-token",+ "Bearer fresh-access-token",+ )+ DiscourseAi::Mcp::OAuthFlow.expects(:refresh!).with(server).once++ stub_request(:post, server.url).to_return(+ { status: 401, body: "", headers: { "Content-Type" => "application/json" } },+ {+ status: 200,+ body: {+ jsonrpc: "2.0",+ result: {+ protocolVersion: "2025-03-26",+ capabilities: {+ tools: {+ },+ },+ },+ }.to_json,+ headers: {+ "Content-Type" => "application/json",+ "Mcp-Session-Id" => "session-2",+ },+ },+ { status: 202, body: "", headers: { "Content-Type" => "application/json" } },+ )++ result = described_class.new(server).initialize_session++ expect(result[:session_id]).to eq("session-2")+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).to have_been_made.twice+ end+ end++ it "rejects non-public endpoints at request time" do+ insecure_server = Fabricate.build(:ai_mcp_server, url: "https://localhost/mcp")+ AiMcpServer+ .expects(:validate_hostname_public!)+ .with("localhost")+ .raises(FinalDestination::SSRFError, "localhost is not allowed")++ expect { described_class.new(insecure_server).initialize_session }.to raise_error(+ described_class::Error,+ I18n.t("discourse_ai.mcp_servers.invalid_url_not_reachable"),+ )+ end+enddiff --git a/plugins/discourse-ai/spec/lib/mcp/oauth_flow_spec.rb b/plugins/discourse-ai/spec/lib/mcp/oauth_flow_spec.rbnew file mode 100644index 00000000000..50f8ee3e462--- /dev/null+++ b/plugins/discourse-ai/spec/lib/mcp/oauth_flow_spec.rb@@ -0,0 +1,71 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Mcp::OAuthFlow do+ fab!(:user)+ fab!(:oauth_client_secret, :ai_secret)+ fab!(:ai_mcp_server) { Fabricate(:ai_mcp_server, auth_type: "oauth") }++ before do+ enable_current_plugin+ AiMcpServer.stubs(:validate_hostname_public!).returns(true)+ end++ describe ".start!" do+ it "rejects insecure Discourse site URLs before starting OAuth" do+ Discourse.stubs(:base_url).returns("http://mcp.home.arpa")++ expect { described_class.start!(server: ai_mcp_server, user: user) }.to raise_error(+ DiscourseAi::Mcp::Client::Error,+ I18n.t("discourse_ai.mcp_servers.errors.oauth_https_required"),+ )+ end+ end++ describe ".refresh!" do+ it "uses HTTP basic auth without sending client_secret in the request body" do+ ai_mcp_server.update!(+ oauth_client_registration: "manual",+ oauth_client_id: "client-id",+ oauth_client_secret_ai_secret_id: oauth_client_secret.id,+ )+ ai_mcp_server.oauth_token_store.write!(+ access_token: "expired-access-token",+ refresh_token: "refresh-token",+ )+ ai_mcp_server.stubs(:oauth_discovery_result).returns(+ 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,+ ),+ )++ stub_request(:post, "https://auth.example.com/token")+ .with do |request|+ decoded_body = Rack::Utils.parse_nested_query(request.body)+ request.headers["Authorization"] ==+ "Basic #{Base64.strict_encode64("client-id:#{oauth_client_secret.secret}")}" &&+ decoded_body["refresh_token"] == "refresh-token" && !decoded_body.key?("client_secret")+ end+ .to_return(+ status: 200,+ body: {+ access_token: "fresh-access-token",+ refresh_token: "fresh-refresh-token",+ token_type: "Bearer",+ }.to_json,+ headers: {+ "Content-Type" => "application/json",+ },+ )++ described_class.refresh!(ai_mcp_server)++ expect(ai_mcp_server.reload.oauth_token.access_token).to eq("fresh-access-token")+ expect(ai_mcp_server.oauth_token.refresh_token).to eq("fresh-refresh-token")+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/mcp/tool_registry_spec.rb b/plugins/discourse-ai/spec/lib/mcp/tool_registry_spec.rbnew file mode 100644index 00000000000..8a11a307a62--- /dev/null+++ b/plugins/discourse-ai/spec/lib/mcp/tool_registry_spec.rb@@ -0,0 +1,81 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Mcp::ToolRegistry do+ before { enable_current_plugin }++ describe ".cache_key" do+ it "namespaces the cache by current multisite database" do+ RailsMultisite::ConnectionManagement.stubs(:current_db).returns("second")++ expect(described_class.cache_key(42)).to eq("discourse-ai:mcp-tools:v1:second:42")+ end+ end++ describe ".tool_classes_for_servers" do+ fab!(:first_server) { Fabricate(:ai_mcp_server, name: "Jira") }+ fab!(:second_server) { Fabricate(:ai_mcp_server, name: "GitHub") }++ it "namespaces colliding tool names" do+ described_class+ .stubs(:tool_definitions_for)+ .with(first_server)+ .returns([{ "name" => "search", "description" => "Search Jira", "inputSchema" => {} }])+ described_class+ .stubs(:tool_definitions_for)+ .with(second_server)+ .returns([{ "name" => "search", "description" => "Search GitHub", "inputSchema" => {} }])++ classes =+ described_class.tool_classes_for_servers(+ [first_server, second_server],+ reserved_names: ["search"],+ )++ expect(classes.map { |klass| klass.signature[:name] }).to contain_exactly(+ "jira__search",+ "github__search",+ )+ end++ it "ignores disconnected oauth servers" do+ disconnected_oauth_server =+ Fabricate(+ :ai_mcp_server,+ name: "OAuth Docs",+ auth_type: "oauth",+ oauth_status: "disconnected",+ )++ described_class+ .stubs(:tool_definitions_for)+ .with(disconnected_oauth_server)+ .returns([{ "name" => "search", "description" => "Search docs", "inputSchema" => {} }])++ classes = described_class.tool_classes_for_servers([disconnected_oauth_server])++ expect(classes).to eq([])+ end++ it "filters tool classes by selected tool names" do+ described_class+ .stubs(:tool_definitions_for)+ .with(first_server)+ .returns(+ [+ { "name" => "search", "description" => "Search Jira", "inputSchema" => {} },+ { "name" => "create", "description" => "Create Jira", "inputSchema" => {} },+ ],+ )++ classes =+ described_class.tool_classes_for_servers(+ [first_server],+ selected_tool_names_by_server: {+ first_server.id => ["create"],+ },+ )++ expect(classes.map { |klass| klass.signature[:name] }).to eq(["create"])+ end+ end+enddiff --git a/plugins/discourse-ai/spec/models/ai_agent_mcp_server_spec.rb b/plugins/discourse-ai/spec/models/ai_agent_mcp_server_spec.rbnew file mode 100644index 00000000000..c0505479be6--- /dev/null+++ b/plugins/discourse-ai/spec/models/ai_agent_mcp_server_spec.rb@@ -0,0 +1,23 @@+# frozen_string_literal: true++RSpec.describe AiAgentMcpServer do+ fab!(:ai_mcp_server)++ before { enable_current_plugin }++ it "memoizes serialized tools for count calculations" do+ ai_mcp_server+ .expects(:tools_for_serialization)+ .once+ .returns(+ [{ name: "search_issues", token_count: 3 }, { name: "create_issue", token_count: 5 }],+ )++ assignment =+ described_class.new(ai_mcp_server: ai_mcp_server, selected_tool_names: ["search_issues"])++ expect(assignment.tools_for_serialization).to eq([{ name: "search_issues", token_count: 3 }])+ expect(assignment.tool_count).to eq(1)+ expect(assignment.token_count).to eq(3)+ end+enddiff --git a/plugins/discourse-ai/spec/models/ai_agent_spec.rb b/plugins/discourse-ai/spec/models/ai_agent_spec.rbindex d24813e900c..799386cddc0 100644--- a/plugins/discourse-ai/spec/models/ai_agent_spec.rb+++ b/plugins/discourse-ai/spec/models/ai_agent_spec.rb@@ -166,6 +166,63 @@ RSpec.describe AiAgent doexpect(klass.allow_chat_direct_messages).to eq(true)end+ it "attaches mcp tool classes for assigned servers" do+ ai_mcp_server = Fabricate(:ai_mcp_server, name: "Jira")+ agent =+ AiAgent.create!(+ name: "mcp_agent",+ description: "test",+ system_prompt: "test",+ tools: [],+ allowed_group_ids: [],+ )+ agent.ai_mcp_servers << ai_mcp_server++ DiscourseAi::Mcp::ToolRegistry.stubs(:tool_classes_for_servers).returns(+ [+ DiscourseAi::Agents::Tools::Mcp.class_instance(+ ai_mcp_server.id,+ "search_issues",+ { "name" => "search_issues", "description" => "Search issues", "inputSchema" => {} },+ ),+ ],+ )++ klass = agent.class_instance++ expect(klass.new.tools.map { |tool| tool.signature[:name] }).to include("search_issues")+ end++ it "passes selected MCP tool names to the registry" do+ ai_mcp_server = Fabricate(:ai_mcp_server, name: "Jira")+ agent =+ AiAgent.create!(+ name: "mcp_agent",+ description: "test",+ system_prompt: "test",+ tools: [],+ allowed_group_ids: [],+ )+ agent.ai_mcp_servers << ai_mcp_server+ agent+ .ai_agent_mcp_servers+ .find_by!(ai_mcp_server_id: ai_mcp_server.id)+ .update!(selected_tool_names: ["search_issues"])++ DiscourseAi::Mcp::ToolRegistry+ .expects(:tool_classes_for_servers)+ .with(+ [ai_mcp_server],+ reserved_names: [],+ selected_tool_names_by_server: {+ ai_mcp_server.id => ["search_issues"],+ },+ )+ .returns([])++ agent.class_instance+ end+it "does not allow setting allowing chat without a default_llm" doagent =AiAgent.create(diff --git a/plugins/discourse-ai/spec/models/ai_mcp_server_spec.rb b/plugins/discourse-ai/spec/models/ai_mcp_server_spec.rbnew file mode 100644index 00000000000..577f700f6bc--- /dev/null+++ b/plugins/discourse-ai/spec/models/ai_mcp_server_spec.rb@@ -0,0 +1,158 @@+# frozen_string_literal: true++RSpec.describe AiMcpServer do+ fab!(:ai_secret)+ fab!(:oauth_client_secret, :ai_secret)++ before { enable_current_plugin }++ it "is valid with a public https url" do+ server = Fabricate.build(:ai_mcp_server, ai_secret: ai_secret)++ expect(server).to be_valid+ end++ it "rejects non-https urls" do+ server = Fabricate.build(:ai_mcp_server, url: "http://example.com")++ expect(server).not_to be_valid+ expect(server.errors[:url]).to include(I18n.t("discourse_ai.mcp_servers.invalid_url_not_https"))+ end++ it "rejects localhost urls" do+ server = Fabricate.build(:ai_mcp_server, url: "https://localhost/mcp")++ expect(server).not_to be_valid+ expect(server.errors[:url]).to include(+ I18n.t("discourse_ai.mcp_servers.invalid_url_not_reachable"),+ )+ end++ it "rejects private ip urls" do+ server = Fabricate.build(:ai_mcp_server, url: "https://127.0.0.1/mcp")++ expect(server).not_to be_valid+ expect(server.errors[:url]).to include(+ I18n.t("discourse_ai.mcp_servers.invalid_url_not_reachable"),+ )+ end++ it "builds a bearer auth header from the configured secret" do+ server = Fabricate(:ai_mcp_server, ai_secret: ai_secret, auth_scheme: "Bearer")++ expect(server.auth_header_value).to eq("Bearer #{ai_secret.secret}")+ end++ it "sends the raw secret when auth scheme is blank" do+ server = Fabricate(:ai_mcp_server, ai_secret: ai_secret, auth_scheme: "")++ expect(server.auth_header_value).to eq(ai_secret.secret)+ end++ it "requires an OAuth client ID for manual OAuth registration" do+ server =+ Fabricate.build(+ :ai_mcp_server,+ auth_type: "oauth",+ oauth_client_registration: "manual",+ oauth_client_secret_ai_secret_id: oauth_client_secret.id,+ oauth_client_id: nil,+ )++ expect(server).not_to be_valid+ expect(server.errors[:oauth_client_id]).to include(+ I18n.t("discourse_ai.mcp_servers.oauth_client_id_required"),+ )+ end++ it "builds an OAuth bearer header from the stored access token" 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")+ expect(server.oauth_token.access_token).to eq("oauth-access-token")+ expect(server.oauth_token.refresh_token).to eq("refresh")+ end++ it "uses the client metadata URL unless manual registration is selected" do+ server = Fabricate(:ai_mcp_server, auth_type: "oauth")++ expect(server.effective_oauth_client_id).to eq(server.oauth_client_metadata_url)++ server.oauth_client_registration = "manual"+ server.oauth_client_id = "manual-client-id"++ expect(server.effective_oauth_client_id).to eq("manual-client-id")+ end++ it "clears stored OAuth credentials when the OAuth configuration changes" do+ server =+ Fabricate(+ :ai_mcp_server,+ auth_type: "oauth",+ oauth_status: "connected",+ oauth_token_type: "Bearer",+ )+ server.oauth_token_store.write!(access_token: "access-token", refresh_token: "refresh-token")++ server.update!(url: "https://different.example.com/mcp")++ expect(server.reload.oauth_status).to eq("disconnected")+ expect(server.oauth_token).to be_blank+ expect(server.oauth_token_store.access_token).to be_blank+ expect(server.oauth_token_store.refresh_token).to be_blank+ end++ it "memoizes serialized tools for count calculations" do+ server = Fabricate(:ai_mcp_server)++ server+ .expects(:tool_definitions)+ .once+ .returns(+ [{ "name" => "search_issues", "description" => "Search issues", "inputSchema" => {} }],+ )+ DiscourseAi::Agents::Tools::Mcp+ .expects(:class_instance)+ .once+ .returns(+ stub(+ signature: {+ description: "Search issues",+ json_schema: {+ type: "object",+ properties: {+ query: {+ type: "string",+ description: "Search query",+ },+ },+ required: ["query"],+ },+ },+ ),+ )++ expect(server.tools_for_serialization).to contain_exactly(+ a_hash_including(+ name: "search_issues",+ parameters: [+ a_hash_including(+ name: "query",+ type: "string",+ description: "Search query",+ required: true,+ ),+ ],+ ),+ )+ expect(server.tool_count).to eq(1)+ expect(server.token_count).to be > 0+ end+enddiff --git a/plugins/discourse-ai/spec/models/ai_secret_spec.rb b/plugins/discourse-ai/spec/models/ai_secret_spec.rbindex b9f6c05a62f..dcc794688ee 100644--- a/plugins/discourse-ai/spec/models/ai_secret_spec.rb+++ b/plugins/discourse-ai/spec/models/ai_secret_spec.rb@@ -93,6 +93,24 @@ RSpec.describe AiSecret doexpect(ai_secret.in_use?).to eq(true)end++ it "returns true when used by an mcp server" do+ Fabricate(:ai_mcp_server, ai_secret: ai_secret)++ expect(ai_secret.in_use?).to eq(true)+ end++ it "returns true when used as an OAuth client secret for an mcp server" do+ Fabricate(+ :ai_mcp_server,+ auth_type: "oauth",+ oauth_client_registration: "manual",+ oauth_client_secret: ai_secret,+ oauth_client_id: "manual-client",+ )++ expect(ai_secret.in_use?).to eq(true)+ endenddescribe "ai_secret_id existence validation" do@@ -139,5 +157,35 @@ RSpec.describe AiSecret doexpect(tool_usage).to be_presentexpect(tool_usage[:name]).to include("Weather Tool")end++ it "lists mcp servers using this secret" do+ server = Fabricate(:ai_mcp_server, name: "Jira", ai_secret: ai_secret)++ usage = ai_secret.used_by+ server_usage = usage.find { |u| u[:type] == "mcp_server" }++ expect(server_usage).to be_present+ expect(server_usage[:id]).to eq(server.id)+ expect(server_usage[:name]).to eq("Jira")+ end++ it "lists mcp servers using this secret as an OAuth client secret" do+ server =+ Fabricate(+ :ai_mcp_server,+ name: "OAuth Jira",+ auth_type: "oauth",+ oauth_client_registration: "manual",+ oauth_client_secret: ai_secret,+ oauth_client_id: "manual-client",+ )++ usage = ai_secret.used_by+ server_usage = usage.find { |u| u[:type] == "mcp_server_oauth_client_secret" }++ expect(server_usage).to be_present+ expect(server_usage[:id]).to eq(server.id)+ expect(server_usage[:name]).to eq("OAuth Jira")+ endendenddiff --git a/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb b/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rbindex 0060de9c875..c0c18c9977f 100644--- a/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb+++ b/plugins/discourse-ai/spec/requests/admin/ai_agents_controller_spec.rb@@ -131,6 +131,54 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController do)end+ it "includes configured mcp servers in meta" do+ Fabricate(:ai_mcp_server, name: "Jira")+ DiscourseAi::Mcp::ToolRegistry.stubs(:tool_definitions_for).returns(+ [{ "name" => "search_issues", "description" => "Search issues", "inputSchema" => {} }],+ )++ get "/admin/plugins/discourse-ai/ai-agents.json"++ expect(response).to be_successful+ expect(response.parsed_body["meta"]["mcp_servers"]).to include(+ a_hash_including(+ "name" => "Jira",+ "tool_count" => 1,+ "token_count" => an_instance_of(Integer),+ "tools" => [a_hash_including("name" => "search_issues")],+ ),+ )+ end++ it "includes selected MCP tool metadata in the serialized agent" do+ server = Fabricate(:ai_mcp_server, name: "Jira")+ ai_agent.ai_mcp_servers << server+ ai_agent+ .ai_agent_mcp_servers+ .find_by!(ai_mcp_server_id: server.id)+ .update!(selected_tool_names: ["search_issues"])+ DiscourseAi::Mcp::ToolRegistry.stubs(:tool_definitions_for).returns(+ [{ "name" => "search_issues", "description" => "Search issues", "inputSchema" => {} }],+ )++ get "/admin/plugins/discourse-ai/ai-agents/#{ai_agent.id}/edit.json"++ expect(response).to be_successful+ expect(response.parsed_body.dig("ai_agent", "mcp_servers")).to include(+ a_hash_including(+ "name" => "Jira",+ "tool_count" => 1,+ "token_count" => an_instance_of(Integer),+ "selected_tool_names" => ["search_issues"],+ "selected_tool_count" => 1,+ "selected_token_count" => an_instance_of(Integer),+ ),+ )+ expect(response.parsed_body.dig("ai_agent", "mcp_server_tool_names")).to eq(+ { server.id.to_s => ["search_issues"] },+ )+ end+context "with translations" dobefore doSiteSetting.default_locale = "fr"@@ -202,6 +250,11 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController dodescribe "POST #create" docontext "with valid params" dolet(:valid_attributes) do+ ai_mcp_server = Fabricate(:ai_mcp_server, name: "Jira")+ DiscourseAi::Mcp::ToolRegistry.stubs(:tool_definitions_for).returns(+ [{ "name" => "search_issues", "description" => "Search issues" }],+ )+{name: "superbot",description: "Assists with tasks",@@ -215,6 +268,10 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doallow_chat_direct_messages: true,default_llm_id: llm_model.id,forced_tool_count: 2,+ mcp_server_ids: [ai_mcp_server.id],+ mcp_server_tool_names: {+ ai_mcp_server.id.to_s => ["search_issues"],+ },execution_mode: "agentic",max_turn_tokens: 5000,compression_threshold: 80,@@ -253,6 +310,8 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doagent = AiAgent.find(agent_json["id"])expect(agent.tools).to eq([["search", { "base_query" => "test" }, true]])+ expect(agent.ai_mcp_servers.pluck(:name)).to eq(["Jira"])+ expect(agent.ai_agent_mcp_servers.first.selected_tool_names).to eq(["search_issues"])expect(agent.top_p).to eq(0.1)expect(agent.temperature).to eq(0.5)}.to change(AiAgent, :count).by(1)@@ -447,6 +506,74 @@ RSpec.describe DiscourseAi::Admin::AiAgentsController doexpect(agent.compression_threshold).to eq(75)end+ it "supports updating selected MCP tool names" do+ server = Fabricate(:ai_mcp_server, name: "Jira")+ agent = Fabricate(:ai_agent, name: "test_bot2")+ agent.ai_mcp_servers << server+ DiscourseAi::Mcp::ToolRegistry+ .stubs(:tool_definitions_for)+ .with(server)+ .returns(+ [{ "name" => "search_issues", "description" => "Search issues", "inputSchema" => {} }],+ )++ put "/admin/plugins/discourse-ai/ai-agents/#{agent.id}.json",+ params: {+ ai_agent: {+ mcp_server_ids: [server.id],+ mcp_server_tool_names: {+ server.id.to_s => ["search_issues"],+ },+ },+ }++ expect(response).to have_http_status(:ok)+ expect(agent.reload.ai_agent_mcp_servers.first.selected_tool_names).to eq(["search_issues"])+ end++ it "preserves hidden disabled MCP assignments when updating visible ones" do+ enabled_server = Fabricate(:ai_mcp_server, name: "Jira")+ disabled_server = Fabricate(:ai_mcp_server, name: "Legacy Docs", enabled: false)+ agent = Fabricate(:ai_agent, name: "test_bot2")+ agent.ai_mcp_servers << enabled_server+ agent.ai_mcp_servers << disabled_server+ DiscourseAi::Mcp::ToolRegistry+ .stubs(:tool_definitions_for)+ .with(enabled_server)+ .returns(+ [{ "name" => "search_issues", "description" => "Search issues", "inputSchema" => {} }],+ )+ agent+ .ai_agent_mcp_servers+ .find_by!(ai_mcp_server_id: disabled_server.id)+ .update!(selected_tool_names: ["search_legacy"])++ put "/admin/plugins/discourse-ai/ai-agents/#{agent.id}.json",+ params: {+ ai_agent: {+ name: "updated",+ mcp_server_ids: [enabled_server.id],+ mcp_server_tool_names: {+ enabled_server.id.to_s => ["search_issues"],+ },+ },+ }++ expect(response).to have_http_status(:ok)++ agent.reload+ expect(agent.ai_mcp_servers.pluck(:id)).to contain_exactly(+ enabled_server.id,+ disabled_server.id,+ )+ expect(+ agent+ .ai_agent_mcp_servers+ .find_by!(ai_mcp_server_id: disabled_server.id)+ .selected_tool_names,+ ).to eq(["search_legacy"])+ end+it "supports updating vision params" doagent = Fabricate(:ai_agent, name: "test_bot2")put "/admin/plugins/discourse-ai/ai-agents/#{agent.id}.json",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.rbnew file mode 100644index 00000000000..3386f549581--- /dev/null+++ b/plugins/discourse-ai/spec/requests/admin/ai_mcp_servers_controller_spec.rb@@ -0,0 +1,300 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Admin::AiMcpServersController do+ fab!(:admin)+ fab!(:ai_secret)++ before do+ enable_current_plugin+ sign_in(admin)+ DiscourseAi::Mcp::ToolRegistry.stubs(:tool_definitions_for).returns([])+ end++ describe "GET #index" do+ fab!(:ai_mcp_server)++ it "returns mcp servers and secrets metadata" do+ DiscourseAi::Mcp::ToolRegistry.stubs(:tool_definitions_for).returns(+ [+ {+ "name" => "search_issues",+ "title" => "Search issues",+ "description" => "Search issues",+ "inputSchema" => {+ "type" => "object",+ "properties" => {+ "query" => {+ "type" => "string",+ "description" => "Search query",+ },+ },+ "required" => ["query"],+ },+ },+ ],+ )++ get "/admin/plugins/discourse-ai/ai-mcp-servers.json"++ expect(response).to be_successful+ expect(response.parsed_body["ai_mcp_servers"].length).to eq(1)+ expect(response.parsed_body["meta"]["ai_secrets"].length).to eq(1)+ expect(response.parsed_body["ai_mcp_servers"].first["tool_count"]).to eq(1)+ expect(response.parsed_body["ai_mcp_servers"].first["tools"]).to match(+ [+ a_hash_including(+ "name" => "search_issues",+ "title" => "Search issues",+ "description" => "Search issues",+ "parameters" => [+ {+ "name" => "query",+ "type" => "string",+ "description" => "Search query",+ "required" => true,+ },+ ],+ "token_count" => an_instance_of(Integer),+ ),+ ],+ )+ end+ end++ describe "browser routes under ai-tools" do+ fab!(:ai_mcp_server)++ it "serves the nested new path used by the Ember route" do+ get "/admin/plugins/discourse-ai/ai-tools/mcp-servers/new"++ expect(response).to be_successful+ end++ it "serves the nested edit path used by the Ember route" do+ get "/admin/plugins/discourse-ai/ai-tools/mcp-servers/#{ai_mcp_server.id}/edit"++ expect(response).to be_successful+ end+ end++ describe "POST #create" do+ it "creates an mcp server" do+ expect {+ post "/admin/plugins/discourse-ai/ai-mcp-servers.json",+ params: {+ ai_mcp_server: {+ name: "Jira",+ description: "Jira MCP",+ url: "https://jira.example.com/mcp",+ ai_secret_id: ai_secret.id,+ },+ }.to_json,+ headers: {+ "CONTENT_TYPE" => "application/json",+ }+ }.to change(AiMcpServer, :count).by(1)++ expect(response).to have_http_status(:created)+ expect(response.parsed_body["ai_mcp_server"]["name"]).to eq("Jira")+ end++ it "rejects localhost urls" do+ expect {+ post "/admin/plugins/discourse-ai/ai-mcp-servers.json",+ params: {+ ai_mcp_server: {+ name: "Internal",+ description: "Internal MCP",+ url: "https://localhost/mcp",+ },+ }.to_json,+ headers: {+ "CONTENT_TYPE" => "application/json",+ }+ }.not_to change(AiMcpServer, :count)++ expect(response).to have_http_status(:unprocessable_entity)+ expect(response.parsed_body["errors"].join(" ")).to include(+ I18n.t("discourse_ai.mcp_servers.invalid_url_not_reachable"),+ )+ end+ end++ describe "POST #test" do+ it "returns discovered tool metadata" do+ DiscourseAi::Mcp::Client+ .any_instance+ .stubs(:initialize_session)+ .returns(+ {+ session_id: "session-1",+ result: {+ "protocolVersion" => "2025-03-26",+ "capabilities" => {+ "tools" => {+ },+ },+ },+ },+ )+ DiscourseAi::Mcp::Client+ .any_instance+ .stubs(:list_tools)+ .returns([{ "name" => "search_issues" }, { "name" => "create_issue" }])++ post "/admin/plugins/discourse-ai/ai-mcp-servers/test.json",+ params: {+ ai_mcp_server: {+ name: "Jira",+ description: "Jira MCP",+ url: "https://jira.example.com/mcp",+ },+ }.to_json,+ headers: {+ "CONTENT_TYPE" => "application/json",+ }++ expect(response).to be_successful+ expect(response.parsed_body["tool_count"]).to eq(2)+ expect(response.parsed_body["tool_names"]).to contain_exactly("search_issues", "create_issue")+ end++ it "requires OAuth servers to be saved before testing" do+ post "/admin/plugins/discourse-ai/ai-mcp-servers/test.json",+ params: {+ ai_mcp_server: {+ name: "OAuth Docs",+ description: "OAuth server",+ url: "https://docs.example.com/mcp",+ auth_type: "oauth",+ },+ }.to_json,+ headers: {+ "CONTENT_TYPE" => "application/json",+ }++ expect(response).to have_http_status(:bad_request)+ expect(response.parsed_body["errors"]).to include(+ I18n.t("discourse_ai.mcp_servers.errors.oauth_save_before_connect"),+ )+ end++ 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,+ )+ ai_mcp_server.oauth_token_store.write!(+ access_token: "stale-access-token",+ refresh_token: "refresh-token",+ )++ client = mock+ DiscourseAi::Mcp::Client+ .expects(:new)+ .with do |test_server|+ expect(test_server).not_to be_persisted+ expect(test_server.url).to eq("https://changed.example.com/mcp")+ expect(test_server.oauth_token_store.access_token).to be_blank+ expect(test_server.oauth_access_token_expires_at).to be_nil+ true+ end+ .returns(client)+ client.expects(:initialize_session).returns(+ {+ session_id: "session-1",+ result: {+ "protocolVersion" => "2025-03-26",+ "capabilities" => {+ },+ },+ },+ )+ client.expects(:list_tools).with(session_id: "session-1").returns([])++ post "/admin/plugins/discourse-ai/ai-mcp-servers/#{ai_mcp_server.id}/test.json",+ params: {+ ai_mcp_server: {+ name: ai_mcp_server.name,+ description: ai_mcp_server.description,+ url: "https://changed.example.com/mcp",+ auth_type: "oauth",+ oauth_client_registration: ai_mcp_server.oauth_client_registration,+ },+ }.to_json,+ headers: {+ "CONTENT_TYPE" => "application/json",+ }++ expect(response).to be_successful+ end+ end++ describe "GET #oauth_start" do+ fab!(:ai_mcp_server) { Fabricate(:ai_mcp_server, auth_type: "oauth") }++ it "redirects to the OAuth authorization URL" do+ DiscourseAi::Mcp::OAuthFlow+ .expects(:start!)+ .with(server: ai_mcp_server, user: admin)+ .returns("https://auth.example.com/authorize")++ get "/admin/plugins/discourse-ai/ai-mcp-servers/#{ai_mcp_server.id}/oauth/start.json"++ expect(response).to redirect_to("https://auth.example.com/authorize")+ end++ it "redirects to the OAuth authorization URL for the browser HTML route" do+ DiscourseAi::Mcp::OAuthFlow+ .expects(:start!)+ .with(server: ai_mcp_server, user: admin)+ .returns("https://auth.example.com/authorize")++ get "/admin/plugins/discourse-ai/ai-mcp-servers/#{ai_mcp_server.id}/oauth/start"++ expect(response).to redirect_to("https://auth.example.com/authorize")+ end+ end++ describe "GET #oauth_callback" do+ fab!(:ai_mcp_server) { Fabricate(:ai_mcp_server, auth_type: "oauth") }++ it "redirects back to the MCP server editor after authorization" do+ DiscourseAi::Mcp::OAuthFlow.expects(:complete!).returns(ai_mcp_server)++ get "/admin/plugins/discourse-ai/ai-mcp-servers/oauth/callback.json", params: { state: "abc" }++ expect(response).to redirect_to(ai_mcp_server.admin_edit_url)+ end++ it "redirects back to the MCP server editor for the browser HTML callback route" do+ DiscourseAi::Mcp::OAuthFlow.expects(:complete!).returns(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+ end++ describe "DELETE #oauth_disconnect" do+ fab!(:ai_mcp_server) do+ Fabricate(:ai_mcp_server, auth_type: "oauth", oauth_status: "connected")+ end++ it "disconnects OAuth credentials and returns the updated server" do+ DiscourseAi::Mcp::OAuthFlow+ .expects(:disconnect!)+ .with(ai_mcp_server)+ .once { ai_mcp_server.clear_oauth_credentials! }++ delete "/admin/plugins/discourse-ai/ai-mcp-servers/#{ai_mcp_server.id}/oauth/disconnect.json"++ expect(response).to be_successful+ expect(response.parsed_body["ai_mcp_server"]["oauth_status"]).to eq("disconnected")+ end+ end+enddiff --git a/plugins/discourse-ai/spec/requests/mcp_oauth_controller_spec.rb b/plugins/discourse-ai/spec/requests/mcp_oauth_controller_spec.rbnew file mode 100644index 00000000000..e1f6f860ef8--- /dev/null+++ b/plugins/discourse-ai/spec/requests/mcp_oauth_controller_spec.rb@@ -0,0 +1,19 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::McpOauthController do+ before { enable_current_plugin }++ describe "GET #client_metadata" do+ it "returns a client metadata document" do+ 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")+ expect(response.parsed_body["redirect_uris"]).to include(+ "#{Discourse.base_url}/admin/plugins/discourse-ai/ai-mcp-servers/oauth/callback",+ )+ 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+ end+enddiff --git a/plugins/discourse-ai/spec/services/discourse_ai/agent_exporter_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/agent_exporter_spec.rbindex d28a656ac78..219c2196d52 100644--- a/plugins/discourse-ai/spec/services/discourse_ai/agent_exporter_spec.rb+++ b/plugins/discourse-ai/spec/services/discourse_ai/agent_exporter_spec.rb@@ -32,6 +32,30 @@ RSpec.describe DiscourseAi::AgentExporter doendend+ context "when the agent has assigned mcp servers" do+ fab!(:ai_mcp_server) { Fabricate(:ai_mcp_server, name: "Jira") }+ fab!(:ai_agent) { Fabricate(:ai_agent, tools: []) }++ let(:exporter) { described_class.new(agent: ai_agent) }++ before { ai_agent.ai_mcp_servers << ai_mcp_server }++ it "exports mcp server names" do+ expect(export_json["agent"]["mcp_servers"]).to eq([{ "name" => "Jira" }])+ end++ it "exports selected MCP tool names when present" do+ ai_agent+ .ai_agent_mcp_servers+ .find_by!(ai_mcp_server_id: ai_mcp_server.id)+ .update!(selected_tool_names: ["search_issues"])++ expect(export_json["agent"]["mcp_servers"]).to eq(+ [{ "name" => "Jira", "selected_tool_names" => ["search_issues"] }],+ )+ end+ end+context "when the agent does not exist" doit "raises an error if initialized with a non agent" doexpect { described_class.new(agent: nil) }.to raise_error(diff --git a/plugins/discourse-ai/spec/services/discourse_ai/agent_importer_spec.rb b/plugins/discourse-ai/spec/services/discourse_ai/agent_importer_spec.rbindex dc295c88737..f16fc4f2745 100644--- a/plugins/discourse-ai/spec/services/discourse_ai/agent_importer_spec.rb+++ b/plugins/discourse-ai/spec/services/discourse_ai/agent_importer_spec.rb@@ -175,6 +175,85 @@ RSpec.describe DiscourseAi::AgentImporter doendend+ context "when importing mcp server assignments" do+ fab!(:ai_mcp_server) { Fabricate(:ai_mcp_server, name: "Jira") }+ fab!(:ai_agent) { Fabricate(:ai_agent, tools: []) }++ let!(:export_json) do+ ai_agent.ai_mcp_servers << ai_mcp_server+ DiscourseAi::AgentExporter.new(agent: ai_agent).export+ end++ it "rebinds the imported agent to local mcp servers by name" do+ ai_agent.destroy++ importer = described_class.new(json: export_json)+ agent = importer.import!++ expect(agent.ai_mcp_servers.pluck(:name)).to eq(["Jira"])+ end++ it "restores selected MCP tool names" do+ ai_agent+ .ai_agent_mcp_servers+ .find_by!(ai_mcp_server_id: ai_mcp_server.id)+ .update!(selected_tool_names: ["search_issues"])+ DiscourseAi::Mcp::ToolRegistry+ .stubs(:tool_definitions_for)+ .with(ai_mcp_server)+ .returns(+ [+ { "name" => "search_issues", "description" => "Search", "inputSchema" => {} },+ { "name" => "create_issue", "description" => "Create", "inputSchema" => {} },+ ],+ )++ refreshed_export_json = DiscourseAi::AgentExporter.new(agent: ai_agent).export+ ai_agent.destroy++ importer = described_class.new(json: refreshed_export_json)+ agent = importer.import!++ expect(agent.ai_agent_mcp_servers.first.selected_tool_names).to eq(["search_issues"])+ end++ it "raises when imported selected MCP tools do not exist locally" do+ ai_agent+ .ai_agent_mcp_servers+ .find_by!(ai_mcp_server_id: ai_mcp_server.id)+ .update!(selected_tool_names: ["search_issues"])++ refreshed_export_json = DiscourseAi::AgentExporter.new(agent: ai_agent).export+ ai_agent.destroy++ DiscourseAi::Mcp::ToolRegistry+ .stubs(:tool_definitions_for)+ .with(ai_mcp_server)+ .returns([{ "name" => "create_issue", "description" => "Create", "inputSchema" => {} }])++ importer = described_class.new(json: refreshed_export_json)++ expect { importer.import! }.to raise_error(+ DiscourseAi::AgentImporter::ImportError,+ ) do |error|+ expect(error.message).to eq(+ I18n.t("discourse_ai.errors.mcp_server_tools_not_found", name: "Jira"),+ )+ expect(error.conflicts[:mcp_servers]).to eq(["Jira"])+ end+ end++ it "raises when the referenced mcp server is missing" do+ ai_mcp_server.destroy++ importer = described_class.new(json: export_json)++ expect { importer.import! }.to raise_error(+ DiscourseAi::AgentImporter::ImportError,+ ) { |error| expect(error.conflicts[:mcp_servers]).to eq(["Jira"]) }+ end+ end+context "with legacy persona format" dolet(:legacy_hash) do{diff --git a/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb b/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rbindex 06d1b157f3e..473732e76d2 100644--- a/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb+++ b/plugins/discourse-ai/spec/system/admin_ai_agent_spec.rb@@ -4,6 +4,8 @@ RSpec.describe "Admin AI agent configuration" dofab!(:admin)let(:page_header) { PageObjects::Components::DPageHeader.new }let(:form) { PageObjects::Components::FormKit.new("form") }+ let(:agent_editor_page) { PageObjects::Pages::AdminAiAgent.new }+ let(:mcp_tool_selector_modal) { PageObjects::Modals::AiAgentMcpToolSelector.new }before doenable_current_plugin@@ -127,4 +129,122 @@ RSpec.describe "Admin AI agent configuration" dovisit "/admin/plugins/discourse-ai/ai-personas/#{agent.id}/edit"expect(page).to have_current_path("/admin/plugins/discourse-ai/ai-agents/#{agent.id}/edit")end++ it "allows selecting a subset of MCP tools for an agent" do+ agent = Fabricate(:ai_agent, name: "Test Agent")+ mcp_server = Fabricate(:ai_mcp_server, name: "GitHub", last_health_status: "healthy")++ DiscourseAi::Mcp::ToolRegistry.stubs(:tool_definitions_for).returns([])+ DiscourseAi::Mcp::ToolRegistry+ .stubs(:tool_definitions_for)+ .with(mcp_server)+ .returns(+ [+ {+ "name" => "search_issues",+ "title" => "Search issues",+ "description" => "Search GitHub issues",+ "inputSchema" => {+ "type" => "object",+ "properties" => {+ "query" => {+ "type" => "string",+ "description" => "Search query",+ },+ },+ "required" => ["query"],+ },+ },+ {+ "name" => "create_issue",+ "title" => "Create issue",+ "description" => "Create a GitHub issue",+ "inputSchema" => {+ "type" => "object",+ "properties" => {+ "title" => {+ "type" => "string",+ "description" => "Issue title",+ },+ },+ "required" => ["title"],+ },+ },+ ],+ )++ agent_editor_page.visit_edit(agent)+ agent_editor_page.select_mcp_server(mcp_server)++ expect(agent_editor_page).to have_mcp_server_summary(+ "GitHub",+ I18n.t("js.discourse_ai.ai_agent.mcp_server_enabled_tool_count", count: 2),+ )++ agent_editor_page.open_mcp_tool_selector("GitHub")++ expect(mcp_tool_selector_modal).to be_open+ expect(mcp_tool_selector_modal).to have_tool_selected("search_issues")+ expect(mcp_tool_selector_modal).to have_tool_selected("create_issue")++ mcp_tool_selector_modal.toggle_tool("create_issue")++ expect(mcp_tool_selector_modal).to have_selection_summary(1, 2)++ mcp_tool_selector_modal.click_primary_button++ expect(mcp_tool_selector_modal).to be_closed+ expect(agent_editor_page).to have_mcp_server_summary(+ "GitHub",+ I18n.t("js.discourse_ai.ai_agent.mcp_server_enabled_tools", count: 1, total: 2),+ )+ expect(agent_editor_page).to have_mcp_server_action(+ "GitHub",+ I18n.t("js.discourse_ai.ai_agent.mcp_server_edit_tools"),+ )++ agent_editor_page.form.submit++ expect(page).to have_content(I18n.t("js.discourse_ai.ai_agent.saved"))+ wait_for do+ agent+ .reload+ .ai_agent_mcp_servers+ .find_by!(ai_mcp_server_id: mcp_server.id)+ .selected_tool_names == ["search_issues"]+ end++ agent_editor_page.visit_edit(agent)++ expect(agent_editor_page).to have_mcp_server_summary(+ "GitHub",+ I18n.t("js.discourse_ai.ai_agent.mcp_server_enabled_tools", count: 1, total: 2),+ )++ agent_editor_page.open_mcp_tool_selector("GitHub")++ expect(mcp_tool_selector_modal).to have_tool_selected("search_issues")+ expect(mcp_tool_selector_modal).to have_tool_unselected("create_issue")+ expect(mcp_tool_selector_modal).to have_selection_summary(1, 2)+ end++ it "renders the new agent form when MCP servers exist" do+ Fabricate(:ai_mcp_server, name: "GitHub", enabled: true)+ DiscourseAi::Mcp::ToolRegistry.stubs(:tool_definitions_for).returns(+ [+ {+ "name" => "search_issues",+ "description" => "Search",+ "inputSchema" => {+ "type" => "object",+ },+ },+ ],+ )++ visit "/admin/plugins/discourse-ai/ai-agents/new"++ expect(page).to have_current_path("/admin/plugins/discourse-ai/ai-agents/new")+ expect(page).to have_field("name")+ endenddiff --git a/plugins/discourse-ai/spec/system/ai_bot/tool_list_editor_spec.rb b/plugins/discourse-ai/spec/system/ai_bot/tool_list_editor_spec.rbindex fbaa3480af8..55682f6282c 100644--- a/plugins/discourse-ai/spec/system/ai_bot/tool_list_editor_spec.rb+++ b/plugins/discourse-ai/spec/system/ai_bot/tool_list_editor_spec.rb@@ -134,6 +134,38 @@ describe "AI Tool List Editor Dropdown" doexpect(tool_menu).to have_css(".btn[data-option='empty_tool']")end+ it "displays credential name after creating a new secret and saving an MCP server" do+ DiscourseAi::Mcp::ToolRegistry.stubs(:tool_definitions_for).returns([])++ visit "/admin/plugins/discourse-ai/ai-tools/mcp-servers/new"++ form = PageObjects::Components::FormKit.new("form.ai-mcp-server-editor")++ form.field("name").fill_in("Test MCP")+ form.field("description").fill_in("A test server")+ form.field("url").fill_in("https://mcp.example.com")+ form.field("auth_type").select("header_secret")++ find(".ai-secret-selector__add-btn").click++ modal = PageObjects::Components::FormKit.new(".ai-secret-create-modal form")+ modal.field("name").fill_in("My API Key")+ modal.field("secret").fill_in("sk-secret-123")+ modal.submit++ expect(page).to have_no_css(".ai-secret-create-modal")++ secret_selector = PageObjects::Components::SelectKit.new(".ai-secret-selector__dropdown")+ expect(secret_selector).to have_selected_name("My API Key")++ form.submit++ expect(page).to have_current_path(%r{/admin/plugins/discourse-ai/ai-tools/mcp-servers/\d+})++ secret_selector = PageObjects::Components::SelectKit.new(".ai-secret-selector__dropdown")+ expect(secret_selector).to have_selected_name("My API Key")+ end+it "resets menu state when closing dropdown" dovisit "/admin/plugins/discourse-ai/ai-tools"diff --git a/plugins/discourse-ai/spec/system/page_objects/modals/ai_agent_mcp_tool_selector.rb b/plugins/discourse-ai/spec/system/page_objects/modals/ai_agent_mcp_tool_selector.rbnew file mode 100644index 00000000000..d2f85981fd5--- /dev/null+++ b/plugins/discourse-ai/spec/system/page_objects/modals/ai_agent_mcp_tool_selector.rb@@ -0,0 +1,37 @@+# frozen_string_literal: true++module PageObjects+ module Modals+ class AiAgentMcpToolSelector < PageObjects::Modals::Base+ BODY_SELECTOR = ".ai-agent-mcp-tools-modal__body"+ MODAL_SELECTOR = ".ai-agent-mcp-tools-modal"++ def toggle_tool(tool_name)+ tool_checkbox(tool_name).click+ self+ end++ def has_tool_selected?(tool_name)+ tool_checkbox(tool_name).checked?+ end++ def has_tool_unselected?(tool_name)+ !tool_checkbox(tool_name).checked?+ end++ def has_selection_summary?(count, total)+ body.has_css?(+ ".ai-agent-mcp-tools-modal__selection-summary",+ text:+ I18n.t("js.discourse_ai.ai_agent.mcp_tools_modal.selection_summary", count:, total:),+ )+ end++ private++ def tool_checkbox(tool_name)+ body.find("[data-tool-name='#{tool_name}'] input[type='checkbox']", visible: :all)+ end+ end+ end+enddiff --git a/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_agent.rb b/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_agent.rbnew file mode 100644index 00000000000..49938d3fcec--- /dev/null+++ b/plugins/discourse-ai/spec/system/page_objects/pages/admin_ai_agent.rb@@ -0,0 +1,50 @@+# frozen_string_literal: true++module PageObjects+ module Pages+ class AdminAiAgent < PageObjects::Pages::Base+ def visit_edit(agent)+ page.visit("/admin/plugins/discourse-ai/ai-agents/#{agent.id}/edit")+ self+ end++ def form+ @form ||= PageObjects::Components::FormKit.new("form")+ end++ def select_mcp_server(server)+ mcp_server_selector.expand+ mcp_server_selector.search(server.name)+ mcp_server_selector.select_row_by_name(server.name)+ mcp_server_selector.collapse+ self+ end++ def open_mcp_tool_selector(server_name)+ find_mcp_server_item(server_name).find(".ai-agent-editor__mcp-server-action").click+ self+ end++ def has_mcp_server_summary?(server_name, summary_text)+ find_mcp_server_item(server_name).has_text?(summary_text)+ end++ def has_mcp_server_action?(server_name, label)+ find_mcp_server_item(server_name).has_css?(+ ".ai-agent-editor__mcp-server-action",+ text: label,+ )+ end++ private++ def mcp_server_selector+ PageObjects::Components::SelectKit.new("#control-mcp_server_ids .select-kit")+ end++ def find_mcp_server_item(server_name)+ page.find(".ai-agent-editor__mcp-server-item", text: server_name)+ end+ end+ end+enddiff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-mcp-server-editor-form-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-mcp-server-editor-form-test.gjsnew file mode 100644index 00000000000..4362d4e7a66--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-mcp-server-editor-form-test.gjs@@ -0,0 +1,119 @@+import Service from "@ember/service";+import { render, settled } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import formKit from "discourse/tests/helpers/form-kit-helper";+import AiMcpServerEditorForm from "discourse/plugins/discourse-ai/discourse/components/ai-mcp-server-editor-form";++class ToastsStub extends Service {+ success() {}+}++module("Integration | Component | ai-mcp-server-editor-form", function (hooks) {+ setupRenderingTest(hooks, { stubRouter: true });++ hooks.beforeEach(function () {+ this.owner.unregister("service:toasts");+ this.owner.register("service:toasts", ToastsStub);++ const router = this.owner.lookup("service:router");+ router.replaceWith = async () => {};+ router.transitionTo = async () => {};++ this.secrets = [{ id: 1, name: "Microsoft token" }];+ this.mcpServers = { content: [] };+ this.savedPayload = null;+ this.model = {+ isNew: true,+ enabled: true,+ timeout_seconds: 30,+ oauth_status: "disconnected",+ oauth_client_metadata_url: "https://meta.example.com/discourse-ai.json",+ save: async (payload) => {+ this.savedPayload = payload;+ Object.assign(this.model, payload, { id: 42, isNew: false });+ return this.model;+ },+ destroyRecord: async () => {},+ };+ });++ test("preserves empty auth_scheme instead of defaulting to Bearer", async function (assert) {+ this.model.isNew = false;+ this.model.id = 42;+ this.model.name = "Data Commons";+ this.model.description = "Google Data Commons";+ this.model.url = "https://api.datacommons.org/mcp";+ this.model.auth_type = "header_secret";+ this.model.ai_secret_id = 1;+ this.model.auth_header = "X-API-Key";+ this.model.auth_scheme = "";++ await render(+ <template>+ <AiMcpServerEditorForm+ @model={{this.model}}+ @mcpServers={{this.mcpServers}}+ @secrets={{this.secrets}}+ />+ </template>+ );++ assert.form().field("auth_scheme").hasValue("");++ await formKit().submit();+ await settled();++ assert.strictEqual(+ this.savedPayload.auth_scheme,+ "",+ "submits empty auth_scheme, not Bearer"+ );+ });++ test("switching auth mode keeps the entered URL and reveals credential fields", async function (assert) {+ await render(+ <template>+ <AiMcpServerEditorForm+ @model={{this.model}}+ @mcpServers={{this.mcpServers}}+ @secrets={{this.secrets}}+ />+ </template>+ );++ assert.false(+ formKit().hasField("max_calls_per_turn"),+ "does not render a max calls per turn field"+ );+ assert+ .dom(+ '.form-kit__field[data-name="timeout_seconds"] .fk-d-tooltip__trigger'+ )+ .exists("shows a tooltip for the timeout field");++ await formKit().field("name").fillIn("Microsoft");+ await formKit().field("description").fillIn("This is a description");+ await formKit().field("url").fillIn("https://learn.microsoft.com/api/mcp");++ await formKit().field("auth_type").select("header_secret");+ await settled();++ assert.dom(".ai-secret-selector").exists("shows credential selector");+ assert.form().field("url").hasValue("https://learn.microsoft.com/api/mcp");++ await formKit().submit();+ await settled();++ assert.strictEqual(+ this.savedPayload.url,+ "https://learn.microsoft.com/api/mcp",+ "submits the entered URL"+ );+ assert.strictEqual(+ this.savedPayload.auth_type,+ "header_secret",+ "submits the selected auth type"+ );+ });+});diff --git a/plugins/discourse-ai/test/javascripts/integration/components/ai-tool-list-editor-test.gjs b/plugins/discourse-ai/test/javascripts/integration/components/ai-tool-list-editor-test.gjsnew file mode 100644index 00000000000..d9c61661add--- /dev/null+++ b/plugins/discourse-ai/test/javascripts/integration/components/ai-tool-list-editor-test.gjs@@ -0,0 +1,99 @@+import Service from "@ember/service";+import { click, render } from "@ember/test-helpers";+import { module, test } from "qunit";+import { setupRenderingTest } from "discourse/tests/helpers/component-test";+import AiToolListEditor from "discourse/plugins/discourse-ai/discourse/components/ai-tool-list-editor";++class AdminPluginNavManagerStub extends Service {+ currentPlugin = { name: "discourse-ai" };+}++class ModalStub extends Service {+ shownComponent = null;+ shownOptions = null;++ show(component, options) {+ this.shownComponent = component;+ this.shownOptions = options;+ }+}++module("Integration | Component | ai-tool-list-editor", function (hooks) {+ setupRenderingTest(hooks, { stubRouter: true });++ hooks.beforeEach(function () {+ this.owner.unregister("service:admin-plugin-nav-manager");+ this.owner.register(+ "service:admin-plugin-nav-manager",+ AdminPluginNavManagerStub+ );++ this.owner.unregister("service:modal");+ this.owner.register("service:modal", ModalStub);++ this.modal = this.owner.lookup("service:modal");+ this.tools = {+ content: [],+ resultSetMeta: { presets: [] },+ };+ this.mcpServers = {+ content: [+ {+ id: 1,+ name: "microsoft mcp",+ description: "Microsoft Learn tools",+ tool_count: 1,+ last_health_status: "healthy",+ tools: [+ {+ name: "microsoft_docs_search",+ title: "Microsoft Docs Search",+ description: "Search official Microsoft documentation.",+ parameters: [+ {+ name: "query",+ type: "string",+ description: "Search query",+ required: true,+ },+ ],+ },+ ],+ },+ ],+ };+ });++ test("clicking the MCP tool count opens the tools modal with tool details", async function (assert) {+ await render(+ <template>+ <AiToolListEditor+ @tools={{this.tools}}+ @mcpServers={{this.mcpServers}}+ />+ </template>+ );++ assert+ .dom(".ai-tool-list__mcp-tools-button")+ .hasText("1 tool", "renders the tool count as a button");++ await click(".ai-tool-list__mcp-tools-button");++ assert.strictEqual(+ this.modal.shownOptions.model.serverName,+ "microsoft mcp",+ "passes the server name to the modal"+ );+ assert.strictEqual(+ this.modal.shownOptions.model.tools[0].title,+ "Microsoft Docs Search",+ "passes tool metadata to the modal"+ );+ assert.strictEqual(+ this.modal.shownOptions.model.tools[0].parameters[0].name,+ "query",+ "passes tool parameter metadata to the modal"+ );+ });+});diff --git a/plugins/discourse-ai/test/javascripts/unit/models/ai-agent-test.js b/plugins/discourse-ai/test/javascripts/unit/models/ai-agent-test.jsindex eef3c43d444..e498f770fa1 100644--- a/plugins/discourse-ai/test/javascripts/unit/models/ai-agent-test.js+++ b/plugins/discourse-ai/test/javascripts/unit/models/ai-agent-test.js@@ -4,6 +4,7 @@ import AiAgent from "discourse/plugins/discourse-ai/discourse/admin/models/ai-agmodule("Discourse AI | Unit | Model | ai-agent", function () {test("toPOJO", function (assert) {const properties = {+ mcp_server_tool_names: { 9: ["search_issues"] },tools: [["ToolName", { option1: "value1", option2: "value2" }, false],"ToolName2",@@ -16,6 +17,9 @@ module("Discourse AI | Unit | Model | ai-agent", function () {assert.deepEqual(aiAgentPOJO.tools, ["ToolName", "ToolName2", "ToolName3"]);assert.strictEqual(aiAgentPOJO.toolOptions["ToolName"].option1, "value1");assert.strictEqual(aiAgentPOJO.toolOptions["ToolName"].option2, "value2");+ assert.deepEqual(aiAgentPOJO.mcp_server_tool_names, {+ 9: ["search_issues"],+ });});test("fromPOJO", function (assert) {@@ -49,6 +53,8 @@ module("Discourse AI | Unit | Model | ai-agent", function () {allow_topic_mentions: true,allow_chat_channel_mentions: true,allow_chat_direct_messages: true,+ mcp_server_ids: [3],+ mcp_server_tool_names: { 3: ["search_issues"] },};const updatedValue = "updated";@@ -64,5 +70,8 @@ module("Discourse AI | Unit | Model | ai-agent", function () {assert.deepEqual(updatedAgent.tools, [["ToolName", { option1: updatedValue }, true],]);+ assert.deepEqual(updatedAgent.mcp_server_tool_names, {+ 3: ["search_issues"],+ });});});