A platform for community discussion. Free, open, simple.
FEATURE: negotiate MCP protocol versions (#44271)
Samf18a1985b22e
diff --git a/plugins/discourse-ai/config/locales/server.en.yml b/plugins/discourse-ai/config/locales/server.en.ymlindex 2a60b2ba699..e6ed4e5d154 100644--- a/plugins/discourse-ai/config/locales/server.en.yml+++ b/plugins/discourse-ai/config/locales/server.en.yml@@ -389,6 +389,17 @@ en: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."+ unsupported_protocol_version: "Unsupported MCP protocol version: %{version}"+ no_supported_version: "No supported MCP protocol version advertised"+ modern_request_rejected: "Modern MCP request rejected"+ invalid_discovery_response: "Invalid MCP server/discover response"+ missing_protocol_version: "Missing MCP protocol version in initialize response"+ tool_unavailable: "MCP tool definition unavailable: %{name}"+ invalid_tool_schema: "Invalid MCP tool input schema"+ invalid_header_annotation: "Invalid x-mcp-header annotation"+ unsupported_schema_reference: "Unsupported MCP tool schema reference"+ invalid_header_value: "Invalid MCP header value"+ invalid_annotated_argument: "Invalid MCP annotated tool argument"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."diff --git a/plugins/discourse-ai/lib/agents/bot_context.rb b/plugins/discourse-ai/lib/agents/bot_context.rbindex dbb8c167539..93e0adab316 100644--- a/plugins/discourse-ai/lib/agents/bot_context.rb+++ b/plugins/discourse-ai/lib/agents/bot_context.rb@@ -243,10 +243,13 @@ module DiscourseAi@mcp_state&.dig(server_id.to_i, :session_id)end- def store_mcp_session(server_id, session_id)+ def mcp_protocol_version_for(server_id)+ @mcp_state&.dig(server_id.to_i, :protocol_version)+ end++ def store_mcp_session(server_id, session_id, protocol_version: nil)@mcp_state ||= {}- state = (@mcp_state[server_id.to_i] ||= { session_id: nil })- state[:session_id] = session_id+ @mcp_state[server_id.to_i] = { session_id: session_id, protocol_version: protocol_version }endendenddiff --git a/plugins/discourse-ai/lib/agents/tools/mcp.rb b/plugins/discourse-ai/lib/agents/tools/mcp.rbindex 1a3312b0970..0c9f3240883 100644--- a/plugins/discourse-ai/lib/agents/tools/mcp.rb+++ b/plugins/discourse-ai/lib/agents/tools/mcp.rb@@ -145,30 +145,43 @@ module DiscourseAicurrent_server = servercurrent_context = context || DiscourseAi::Agents::BotContext.new(messages: [])- client = DiscourseAi::Mcp::Client.new(current_server)+ protocol_version = current_context.mcp_protocol_version_for(self.class.server_id)+ client = DiscourseAi::Mcp::Client.new(current_server, protocol_version: protocol_version)result = invoke_with_session(client, current_context)return error_response(normalize_content(result)) if result["isError"]{ result: normalize_content(result) }+ rescue DiscourseAi::Mcp::HeaderMapper::InvalidArgumentError => error+ error_response(error.message)endprivatedef 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)+ initialize_and_store(client, current_context) if client.protocol_version.blank?+ call_tool(client, current_context)rescue DiscourseAi::Mcp::Client::SessionExpiredError+ initialize_and_store(client, current_context)+ call_tool(client, current_context)+ end++ def initialize_and_store(client, current_context)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])+ current_context.store_mcp_session(+ self.class.server_id,+ initialized[:session_id],+ protocol_version: initialized[:result]["protocolVersion"],+ )+ end++ def call_tool(client, current_context)+ client.call_tool(+ self.class.tool_name,+ parameters,+ session_id: current_context.mcp_session_for(self.class.server_id),+ input_schema: self.class.schema_value["inputSchema"],+ )enddef normalize_content(result)diff --git a/plugins/discourse-ai/lib/mcp/client.rb b/plugins/discourse-ai/lib/mcp/client.rbindex 44b574ffd2e..53168f2ee9e 100644--- a/plugins/discourse-ai/lib/mcp/client.rb+++ b/plugins/discourse-ai/lib/mcp/client.rb@@ -5,7 +5,29 @@ module DiscourseAiclass ClientMCP_SESSION_ID_HEADER = "Mcp-Session-Id"JSONRPC_VERSION = "2.0"- PROTOCOL_VERSION = "2025-03-26"+ PROTOCOL_VERSION = "2025-11-25"+ MODERN_PROTOCOL_VERSION = "2026-07-28"+ SUPPORTED_CLASSIC_PROTOCOL_VERSIONS = [PROTOCOL_VERSION, "2025-03-26"].freeze+ SUPPORTED_PROTOCOL_VERSIONS = [+ MODERN_PROTOCOL_VERSION,+ *SUPPORTED_CLASSIC_PROTOCOL_VERSIONS,+ ].freeze+ MODERN_ERROR_CODES = [-32_020, -32_021, -32_022].freeze+ DISCOVERY_TOLERATED_STATUSES = [400, 404, 405].freeze+ CLASSIC_INITIALIZE_TOLERATED_STATUSES = [400].freeze+ POST_JSONRPC_OPTIONS = %i[+ params+ session_id+ accept_sse+ notification+ allow_result_error+ tolerate_statuses+ input_schema+ allow_oauth_retry+ ].freeze+ PROTOCOL_META_KEY = "io.modelcontextprotocol/protocolVersion"+ CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"+ CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"USER_AGENT = "Discourse AI MCP Client"MAX_RESPONSE_BODY_LENGTH = 5.megabytes@@ -24,16 +46,70 @@ module DiscourseAiResponse = Struct.new(:payload, :session_id, :status, :headers, keyword_init: true)- def initialize(server)+ attr_reader :protocol_version++ def initialize(server, protocol_version: nil)@server = server+ if protocol_version.present? && !SUPPORTED_PROTOCOL_VERSIONS.include?(protocol_version)+ raise Error,+ I18n.t(+ "discourse_ai.mcp_servers.errors.unsupported_protocol_version",+ version: protocol_version,+ )+ end+ @protocol_version = protocol_versionenddef initialize_session+ @protocol_version = MODERN_PROTOCOL_VERSION+ probe = post_jsonrpc("server/discover", tolerate_statuses: DISCOVERY_TOLERATED_STATUSES)+ error = probe.payload["error"] if probe.payload.is_a?(Hash)+ if probe.payload.is_a?(Hash) && probe.payload["jsonrpc"] == JSONRPC_VERSION &&+ error.is_a?(Hash) && MODERN_ERROR_CODES.include?(error["code"])+ if error["code"] == -32_022+ supported = error["data"].is_a?(Hash) ? error["data"]["supported"] : nil+ supported = supported.is_a?(Array) ? supported : []+ version = SUPPORTED_PROTOCOL_VERSIONS.find { |candidate| supported.include?(candidate) }+ if version.nil?+ raise Error, I18n.t("discourse_ai.mcp_servers.errors.no_supported_version")+ end+ return initialize_classic_session(version) if version != MODERN_PROTOCOL_VERSION+ end++ raise_response_error!(+ probe.payload,+ fallback: "discourse_ai.mcp_servers.errors.modern_request_rejected",+ )+ end++ return initialize_classic_session if classic_fallback?(probe)++ raise_response_error!(probe.payload, status: probe.status) if probe.status >= 400++ result = extract_result!(probe.payload)+ unless result["supportedVersions"].is_a?(Array) &&+ result["supportedVersions"].include?(MODERN_PROTOCOL_VERSION)+ raise Error, I18n.t("discourse_ai.mcp_servers.errors.invalid_discovery_response")+ end++ { session_id: nil, result: result.merge("protocolVersion" => MODERN_PROTOCOL_VERSION) }+ end++ def initialize_classic_session(offer = PROTOCOL_VERSION)+ if SUPPORTED_CLASSIC_PROTOCOL_VERSIONS.exclude?(offer)+ raise Error,+ I18n.t(+ "discourse_ai.mcp_servers.errors.unsupported_protocol_version",+ version: offer,+ )+ end++ @protocol_version = nilresponse =post_jsonrpc("initialize",params: {- protocolVersion: PROTOCOL_VERSION,+ protocolVersion: offer,capabilities: {tools: {},@@ -43,9 +119,30 @@ module DiscourseAiversion: Discourse::VERSION::STRING,},},+ tolerate_statuses: CLASSIC_INITIALIZE_TOLERATED_STATUSES,)+ if offer == PROTOCOL_VERSION && rejected_classic_version?(response.payload)+ return initialize_classic_session("2025-03-26")+ end+ raise_response_error!(response.payload, status: response.status) if response.status >= 400+result = extract_result!(response.payload)+ version = result["protocolVersion"]+ if version.blank?+ raise Error, I18n.t("discourse_ai.mcp_servers.errors.missing_protocol_version")+ end+ if !SUPPORTED_CLASSIC_PROTOCOL_VERSIONS.include?(version)+ return initialize_classic_session("2025-03-26") if offer == PROTOCOL_VERSION++ raise Error,+ I18n.t(+ "discourse_ai.mcp_servers.errors.unsupported_protocol_version",+ version: version,+ )+ end++ @protocol_version = versionnotify_initialized(response.session_id){ session_id: response.session_id, result: result }@@ -54,10 +151,30 @@ module DiscourseAidef list_tools(session_id: nil)response = post_jsonrpc("tools/list", session_id: session_id)result = extract_result!(response.payload)- Array(result["tools"])+ Array(result["tools"]).reject do |tool|+ next false if protocol_version != MODERN_PROTOCOL_VERSION+ next true unless tool.is_a?(Hash)++ begin+ HeaderMapper.new(tool["inputSchema"]).annotations+ false+ rescue Error => error+ Rails.logger.warn("Invalid MCP tool #{tool["name"]}: #{error.message}")+ true+ end+ endend- def call_tool(tool_name, arguments, session_id: nil)+ def call_tool(tool_name, arguments, session_id: nil, input_schema: nil)+ if protocol_version == MODERN_PROTOCOL_VERSION && input_schema.nil?+ tool = list_tools.find { |definition| definition["name"] == tool_name }+ if tool.nil?+ raise Error, I18n.t("discourse_ai.mcp_servers.errors.tool_unavailable", name: tool_name)+ end++ input_schema = tool["inputSchema"]+ end+response =post_jsonrpc("tools/call",@@ -66,6 +183,7 @@ module DiscourseAiarguments: arguments,},session_id: session_id,+ input_schema: input_schema,accept_sse: true,allow_result_error: true,)@@ -85,45 +203,52 @@ module DiscourseAi)end- def post_jsonrpc(- method,- params: nil,- session_id: nil,- accept_sse: false,- notification: false,- allow_result_error: false,- allow_oauth_retry: true- )+ def post_jsonrpc(method, **options)+ options.assert_valid_keys(*POST_JSONRPC_OPTIONS)uri = validate_uri!+ params = options[:params]+ session_id = options[:session_id]++ if protocol_version == MODERN_PROTOCOL_VERSION+ params =+ (params || {}).merge(+ _meta: {+ PROTOCOL_META_KEY => protocol_version,+ CLIENT_INFO_META_KEY => {+ name: USER_AGENT,+ version: Discourse::VERSION::STRING,+ },+ CAPABILITIES_META_KEY => {+ },+ },+ )+ endpayload = { jsonrpc: JSONRPC_VERSION, method: method }payload[:params] = params if params.present?- payload[:id] = SecureRandom.uuid unless notification+ payload[:id] = SecureRandom.uuid unless options[:notification]headers = default_headers(session_id: session_id)+ if protocol_version == MODERN_PROTOCOL_VERSION+ headers.merge!(+ HeaderMapper.request_headers(method, params, input_schema: options[:input_schema]),+ )+ endresponse, raw_body = perform_request(uri, payload, headers)handle_response(response,raw_body,session_id: session_id,- allow_result_error: allow_result_error,+ allow_result_error: options[:allow_result_error],+ tolerate_statuses: options.fetch(:tolerate_statuses, []),)rescue UnauthorizedError => e- if server.oauth? && allow_oauth_retry && server.oauth_token_store.refresh_token.present?+ if server.oauth? && options.fetch(:allow_oauth_retry, true) &&+ 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_result_error: allow_result_error,- allow_oauth_retry: false,- )- )+ return post_jsonrpc(method, **options.merge(allow_oauth_retry: false))enddiscovery =@@ -173,10 +298,10 @@ module DiscourseAi[response, raw_body]end- def handle_response(response, raw_body, session_id:, allow_result_error:)+ def handle_response(response, raw_body, session_id:, allow_result_error:, tolerate_statuses:)status = response.code.to_i- if status == 404 && session_id.present?+ if status == 404 && session_id.present? && protocol_version != MODERN_PROTOCOL_VERSIONraise SessionExpiredError, I18n.t("discourse_ai.mcp_servers.errors.session_expired")end@@ -188,21 +313,29 @@ module DiscourseAiendbody =- if response["Content-Type"].to_s.include?("text/event-stream")- parse_sse_body(raw_body)- else- parse_json_body(raw_body)+ begin+ if response["Content-Type"].to_s.include?("text/event-stream")+ parse_sse_body(raw_body)+ else+ parse_json_body(raw_body)+ end+ rescue JSON::ParserError+ unless tolerate_statuses == DISCOVERY_TOLERATED_STATUSES &&+ tolerate_statuses.include?(status)+ raise+ end++ {}end+ return build_response(response, body, status) if tolerate_statuses.include?(status)+if status < 200 || status >= 300if allow_result_error && tool_result_error?(body)return build_response(response, body, status)end- 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)+ raise_response_error!(body, status: status)endbuild_response(response, body, status)@@ -238,24 +371,72 @@ module DiscourseAi"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+ if server.auth_header.present? && (auth_header_value = server.auth_header_value).present?+ headers[server.auth_header] = auth_header_valueend- headers[MCP_SESSION_ID_HEADER] = session_id if session_id.present?+ headers["MCP-Protocol-Version"] = protocol_version if protocol_version.present?+ headers[MCP_SESSION_ID_HEADER] = session_id if session_id.present? &&+ protocol_version != MODERN_PROTOCOL_VERSIONheadersend- def extract_result!(payload)+ def classic_fallback?(response)+ return true if response.status == 400+ return method_not_found?(response.payload) if response.status == 200+ return false if [404, 405].exclude?(response.status)++ method_not_found?(response.payload) || !response.payload.is_a?(Hash) ||+ response.payload["jsonrpc"] != JSONRPC_VERSION+ end++ def method_not_found?(payload)+ payload.is_a?(Hash) && payload["jsonrpc"] == JSONRPC_VERSION &&+ payload["error"].is_a?(Hash) && payload["error"]["code"] == -32_601+ end++ def rejected_classic_version?(payload)+ return false unless payload.is_a?(Hash) && payload["jsonrpc"] == JSONRPC_VERSION+error = payload["error"]- if error.present?- raise Error,- error["message"].presence ||- I18n.t("discourse_ai.mcp_servers.errors.invalid_response")+ return false unless error.is_a?(Hash) && error["code"].is_a?(Integer)+ return false if MODERN_ERROR_CODES.include?(error["code"])++ message = error["message"]+ message.is_a?(String) &&+ message.match?(+ /\b(?:unsupported|unrecognized|not supported|invalid)\s+(?:MCP\s+)?protocol\s+version\b|\bprotocol\s+version\b.*\b(?:unsupported|unrecognized|not supported|invalid)\b/i,+ )+ end++ def raise_response_error!(+ payload,+ status: nil,+ fallback: "discourse_ai.mcp_servers.errors.request_failed"+ )+ error = payload["error"] if payload.is_a?(Hash)+ message = error["message"] if error.is_a?(Hash)+ raise Error, message.presence || I18n.t(fallback, status: status)+ end++ def extract_result!(payload)+ unless payload.is_a?(Hash)+ raise Error, I18n.t("discourse_ai.mcp_servers.errors.invalid_response")+ end++ if payload["error"].present?+ raise_response_error!(+ payload,+ fallback: "discourse_ai.mcp_servers.errors.invalid_response",+ )+ end++ result = payload["result"] || {}+ unless result.is_a?(Hash)+ raise Error, I18n.t("discourse_ai.mcp_servers.errors.invalid_response")end- payload["result"] || {}+ resultenddef build_response(response, body, status)diff --git a/plugins/discourse-ai/lib/mcp/header_mapper.rb b/plugins/discourse-ai/lib/mcp/header_mapper.rbnew file mode 100644index 00000000000..4081538f4c5--- /dev/null+++ b/plugins/discourse-ai/lib/mcp/header_mapper.rb@@ -0,0 +1,212 @@+# frozen_string_literal: true++module DiscourseAi+ module Mcp+ class HeaderMapper+ InvalidArgumentError = Class.new(Client::Error)++ HEADER_NAME = /\A[!#$%&'*+.^_`|~0-9A-Za-z-]+\z/+ PRIMITIVE_TYPES = %w[string integer boolean].freeze+ DATA_KEYWORDS = %w[default examples const enum dependentRequired].freeze+ SCHEMA_MAP_KEYWORDS = %w[properties patternProperties dependentSchemas].freeze++ def self.request_headers(method, params, input_schema: nil)+ headers = { "Mcp-Method" => method }+ if %w[tools/call resources/read prompts/get].include?(method)+ headers["Mcp-Name"] = encode(params[:name] || params[:uri])+ end+ if method == "tools/call"+ new(input_schema).annotations.each do |name, (path, type)|+ value = argument_header(params[:arguments] || {}, path, type)+ headers["Mcp-Param-#{name}"] = value if value+ end+ end+ headers+ end++ def initialize(schema)+ @root = schema+ end++ def annotations+ unless @root.is_a?(Hash)+ raise Client::Error, I18n.t("discourse_ai.mcp_servers.errors.invalid_tool_schema")+ end++ headers = {}+ scan(@root, [], headers, [])+ headers+ end++ private++ def scan(node, path, headers, references)+ return unless node.is_a?(Hash)++ if node.key?("x-mcp-header")+ name = node["x-mcp-header"]+ unless path.present? && name.is_a?(String) && name.match?(HEADER_NAME) &&+ PRIMITIVE_TYPES.include?(node["type"]) &&+ !headers.keys.any? { |existing| existing.casecmp?(name) }+ raise Client::Error, I18n.t("discourse_ai.mcp_servers.errors.invalid_header_annotation")+ end+ headers[name] = [path, node["type"]]+ end++ node.each do |key, value|+ case key+ when "$ref"+ target = resolve_reference(value)+ next if target.nil?++ if references.include?(value)+ unsupported_reference! if contains_annotation?(target)+ next+ end+ scan(target, path, headers, references + [value])+ when "properties"+ if value.is_a?(Hash)+ each_schema_child(key, value) do |property, schema|+ scan(schema, path + [property], headers, references)+ end+ else+ reject_annotations!("properties" => value)+ end+ when "allOf"+ if value.is_a?(Array)+ each_schema_child(key, value) do |_property, schema|+ scan(schema, path, headers, references)+ end+ else+ reject_annotations!("allOf" => value)+ end+ when "$defs", "definitions", "x-mcp-header", *DATA_KEYWORDS+ next+ else+ reject_annotations!(key => value)+ end+ end+ end++ def resolve_reference(ref)+ unless ref.is_a?(String) && ref.start_with?("#") && !ref.match?(/%(?![0-9A-Fa-f]{2})/)+ unsupported_reference!+ end++ pointer = URI::DEFAULT_PARSER.unescape(ref.delete_prefix("#"))+ valid_pointer = pointer.valid_encoding? && (pointer.empty? || pointer.start_with?("/"))+ unsupported_reference! if !valid_pointer++ segments = pointer.empty? ? [] : pointer.split("/", -1).drop(1)+ unsupported_reference! if segments.any? { |segment| segment.match?(/~(?![01])/) }++ target =+ segments.reduce(@root) do |schema, segment|+ segment = segment.gsub("~1", "/").gsub("~0", "~")+ case schema+ when Hash+ schema[segment]+ when Array+ unsupported_reference! unless segment.match?(/\A(?:0|[1-9][0-9]*)\z/)+ index = segment.to_i+ unsupported_reference! if index >= schema.length+ schema[index]+ when NilClass+ nil+ else+ unsupported_reference!+ end+ end+ # A missing local target cannot contribute header annotations.+ return nil if target.nil?++ unsupported_reference! unless target.is_a?(Hash)+ target+ end++ def each_schema_child(key, value)+ return enum_for(:each_schema_child, key, value) unless block_given?++ if SCHEMA_MAP_KEYWORDS.include?(key) && value.is_a?(Hash)+ value.each { |property, schema| yield property, schema }+ elsif key == "allOf" && value.is_a?(Array)+ value.each { |schema| yield nil, schema }+ else+ yield nil, value+ end+ end++ def contains_annotation?(node, visited = Set.new)+ case node+ when Hash+ return false if visited.include?(node.object_id)++ visited.add(node.object_id)+ return true if node.key?("x-mcp-header")++ node.any? do |key, value|+ case key+ when "$ref"+ contains_annotation?(resolve_reference(value), visited)+ when "$defs", "definitions", *DATA_KEYWORDS+ false+ else+ each_schema_child(key, value).any? do |_property, schema|+ contains_annotation?(schema, visited)+ end+ end+ end+ when Array+ node.any? { |value| contains_annotation?(value, visited) }+ else+ false+ end+ end++ def reject_annotations!(node)+ if contains_annotation?(node)+ raise Client::Error, I18n.t("discourse_ai.mcp_servers.errors.invalid_header_annotation")+ end+ end++ def unsupported_reference!+ raise Client::Error, I18n.t("discourse_ai.mcp_servers.errors.unsupported_schema_reference")+ end++ def self.encode(value)+ if value.nil?+ raise Client::Error, I18n.t("discourse_ai.mcp_servers.errors.invalid_header_value")+ end++ value = value.to_s+ if value.ascii_only? && value.match?(/\A[\x09\x20-\x7E]*\z/) && value == value.strip &&+ !value.match?(/\A=\?base64\?.*\?=\z/)+ value+ else+ "=?base64?#{[value.encode("UTF-8")].pack("m0")}?="+ end+ end++ def self.argument_header(arguments, path, type)+ value = path.reduce(arguments.as_json) { |node, key| node.is_a?(Hash) ? node[key] : nil }+ return if value.nil?++ valid =+ case type+ when "string"+ value.is_a?(String)+ when "integer"+ value.is_a?(Integer) && value.abs <= (2**53 - 1)+ when "boolean"+ value == true || value == false+ end+ unless valid+ raise InvalidArgumentError,+ I18n.t("discourse_ai.mcp_servers.errors.invalid_annotated_argument")+ end++ encode(value)+ end+ end+ end+enddiff --git a/plugins/discourse-ai/spec/lib/agents/tools/mcp_spec.rb b/plugins/discourse-ai/spec/lib/agents/tools/mcp_spec.rbindex e53102cf5af..d4ff108eb91 100644--- a/plugins/discourse-ai/spec/lib/agents/tools/mcp_spec.rb+++ b/plugins/discourse-ai/spec/lib/agents/tools/mcp_spec.rb@@ -123,7 +123,7 @@ RSpec.describe DiscourseAi::Agents::Tools::Mcp doDiscourseAi::Mcp::Client.any_instance.stubs(:initialize_session)- .returns({ session_id: "session-1", result: {} })+ .returns({ session_id: "session-1", result: { "protocolVersion" => "2025-11-25" } })DiscourseAi::Mcp::Client.any_instance.stubs(:call_tool)@@ -140,7 +140,7 @@ RSpec.describe DiscourseAi::Agents::Tools::Mcp doDiscourseAi::Mcp::Client.any_instance.stubs(:initialize_session)- .returns({ session_id: "session-1", result: {} })+ .returns({ session_id: "session-1", result: { "protocolVersion" => "2025-11-25" } })DiscourseAi::Mcp::Client.any_instance.stubs(:call_tool)@@ -154,12 +154,223 @@ RSpec.describe DiscourseAi::Agents::Tools::Mcp doexpect(context.mcp_session_for(ai_mcp_server.id)).to eq("session-1")end+ it "reuses a negotiated version and session ID across client instances" do+ context = DiscourseAi::Agents::BotContext.new(messages: [])+ stub_request(:post, ai_mcp_server.url).to_return do |request|+ method = JSON.parse(request.body)["method"]+ case method+ when "server/discover"+ { status: 400, body: "" }+ when "initialize"+ {+ status: 200,+ body: { result: { protocolVersion: "2025-03-26" } }.to_json,+ headers: {+ "Mcp-Session-Id" => "session-1",+ },+ }+ when "notifications/initialized"+ { status: 202 }+ else+ { status: 200, body: { result: { content: [{ type: "text", text: "Found" }] } }.to_json }+ end+ end++ 2.times do+ tool = tool_class.new({ query: "bug" }, bot_user: user, llm: nil, context: context)+ expect(tool.invoke).to eq(result: "Found")+ end++ expect(context.mcp_session_for(ai_mcp_server.id)).to eq("session-1")+ expect(context.mcp_protocol_version_for(ai_mcp_server.id)).to eq("2025-03-26")+ expect(+ a_request(:post, ai_mcp_server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).to have_been_made.once+ expect(+ a_request(:post, ai_mcp_server.url).with do |request|+ JSON.parse(request.body)["method"] == "tools/call" &&+ request.headers["Mcp-Protocol-Version"] == "2025-03-26" &&+ request.headers["Mcp-Session-Id"] == "session-1"+ end,+ ).to have_been_made.twice+ end++ it "reuses a negotiated version for a stateless server across client instances" do+ context = DiscourseAi::Agents::BotContext.new(messages: [])+ stub_request(:post, ai_mcp_server.url).to_return do |request|+ method = JSON.parse(request.body)["method"]+ case method+ when "server/discover"+ { status: 400, body: "" }+ when "initialize"+ { status: 200, body: { result: { protocolVersion: "2025-11-25" } }.to_json }+ when "notifications/initialized"+ { status: 202 }+ else+ { status: 200, body: { result: { content: [{ type: "text", text: "Found" }] } }.to_json }+ end+ end++ 2.times do+ tool = tool_class.new({ query: "bug" }, bot_user: user, llm: nil, context: context)+ expect(tool.invoke).to eq(result: "Found")+ end++ expect(context.mcp_session_for(ai_mcp_server.id)).to be_nil+ expect(context.mcp_protocol_version_for(ai_mcp_server.id)).to eq("2025-11-25")+ expect(+ a_request(:post, ai_mcp_server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).to have_been_made.once+ expect(+ a_request(:post, ai_mcp_server.url).with do |request|+ JSON.parse(request.body)["method"] == "tools/call" &&+ request.headers["Mcp-Protocol-Version"] == "2025-11-25" &&+ request.headers["Mcp-Session-Id"].nil?+ end,+ ).to have_been_made.twice+ end++ it "reuses modern stateless negotiation across tool invocations" do+ context = DiscourseAi::Agents::BotContext.new(messages: [])+ stub_request(:post, ai_mcp_server.url).to_return do |request|+ result =+ if JSON.parse(request.body)["method"] == "server/discover"+ { supportedVersions: ["2026-07-28"], capabilities: {} }+ else+ { content: [{ type: "text", text: "Found" }] }+ end+ { status: 200, body: { jsonrpc: "2.0", result: result }.to_json }+ end++ 2.times do+ tool = tool_class.new({ query: "bug" }, bot_user: user, llm: nil, context: context)+ expect(tool.invoke).to eq(result: "Found")+ end++ expect(context.mcp_session_for(ai_mcp_server.id)).to be_nil+ expect(context.mcp_protocol_version_for(ai_mcp_server.id)).to eq("2026-07-28")+ expect(+ a_request(:post, ai_mcp_server.url).with do |request|+ JSON.parse(request.body)["method"] == "server/discover"+ end,+ ).to have_been_made.once+ expect(+ a_request(:post, ai_mcp_server.url).with do |request|+ body = JSON.parse(request.body)+ body["method"] == "tools/call" &&+ body.dig("params", "_meta", "io.modelcontextprotocol/protocolVersion") == "2026-07-28" &&+ request.headers["Mcp-Protocol-Version"] == "2026-07-28" &&+ request.headers["Mcp-Method"] == "tools/call" &&+ request.headers["Mcp-Name"] == "search_issues" && request.headers["Mcp-Session-Id"].nil?+ end,+ ).to have_been_made.twice+ end++ it "renegotiates once after a classic session expires on the wire" do+ context = DiscourseAi::Agents::BotContext.new(messages: [])+ initialization_count = 0+ stub_request(:post, ai_mcp_server.url).to_return do |request|+ case JSON.parse(request.body)["method"]+ when "server/discover"+ { status: 400, body: "" }+ when "initialize"+ initialization_count += 1+ {+ status: 200,+ body: { result: { protocolVersion: "2025-03-26" } }.to_json,+ headers: {+ "Mcp-Session-Id" => "session-#{initialization_count}",+ },+ }+ when "notifications/initialized"+ { status: 202 }+ when "tools/call"+ if request.headers["Mcp-Session-Id"] == "session-1"+ { status: 404, body: "" }+ else+ { status: 200, body: { result: { content: [{ type: "text", text: "Found" }] } }.to_json }+ end+ end+ end++ tool = tool_class.new({ query: "bug" }, bot_user: user, llm: nil, context: context)++ expect(tool.invoke).to eq(result: "Found")+ expect(context.mcp_session_for(ai_mcp_server.id)).to eq("session-2")+ expect(context.mcp_protocol_version_for(ai_mcp_server.id)).to eq("2025-03-26")+ expect(+ a_request(:post, ai_mcp_server.url).with do |request|+ JSON.parse(request.body)["method"] == "tools/call" &&+ %w[session-1 session-2].include?(request.headers["Mcp-Session-Id"])+ end,+ ).to have_been_made.twice+ expect(+ a_request(:post, ai_mcp_server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).to have_been_made.twice+ end++ it "stops retrying when the replacement classic session also expires" do+ context = DiscourseAi::Agents::BotContext.new(messages: [])+ initialization_count = 0+ stub_request(:post, ai_mcp_server.url).to_return do |request|+ case JSON.parse(request.body)["method"]+ when "server/discover"+ { status: 400, body: "" }+ when "initialize"+ initialization_count += 1+ {+ status: 200,+ body: { result: { protocolVersion: "2025-03-26" } }.to_json,+ headers: {+ "Mcp-Session-Id" => "session-#{initialization_count}",+ },+ }+ when "notifications/initialized"+ { status: 202 }+ when "tools/call"+ { status: 404, body: "" }+ end+ end++ tool = tool_class.new({ query: "bug" }, bot_user: user, llm: nil, context: context)++ expect { tool.invoke }.to raise_error(DiscourseAi::Mcp::Client::SessionExpiredError)+ expect(+ a_request(:post, ai_mcp_server.url).with do |request|+ JSON.parse(request.body)["method"] == "tools/call"+ end,+ ).to have_been_made.twice+ expect(initialization_count).to eq(2)+ end++ it "returns invalid annotated arguments as model-visible errors without calling the server" do+ klass = tool_class+ klass.schema_value["inputSchema"]["properties"]["query"]["x-mcp-header"] = "Query"+ context = DiscourseAi::Agents::BotContext.new(messages: [])+ context.store_mcp_session(ai_mcp_server.id, nil, protocol_version: "2026-07-28")+ AiMcpServer.stubs(:validate_hostname_public!).returns(true)++ tool = klass.new({ query: 123 }, bot_user: user, llm: nil, context: context)++ expect(tool.invoke).to eq(+ status: "error",+ error: I18n.t("discourse_ai.mcp_servers.errors.invalid_annotated_argument"),+ )+ expect(a_request(:post, ai_mcp_server.url)).not_to have_been_made+ end+it "returns tool execution errors as text the model can inspect" docontext = DiscourseAi::Agents::BotContext.new(messages: [])DiscourseAi::Mcp::Client.any_instance.stubs(:initialize_session)- .returns({ session_id: "session-1", result: {} })+ .returns({ session_id: "session-1", result: { "protocolVersion" => "2025-11-25" } })DiscourseAi::Mcp::Client.any_instance.stubs(:call_tool)diff --git a/plugins/discourse-ai/spec/lib/mcp/client_spec.rb b/plugins/discourse-ai/spec/lib/mcp/client_spec.rbindex 86bd5874e66..e66a364ce49 100644--- a/plugins/discourse-ai/spec/lib/mcp/client_spec.rb+++ b/plugins/discourse-ai/spec/lib/mcp/client_spec.rb@@ -9,7 +9,20 @@ RSpec.describe DiscourseAi::Mcp::Client doAiMcpServer.stubs(:validate_hostname_public!).returns(true)end- describe "#initialize_session" do+ def stub_oauth_refresh+ server.update!(auth_type: "oauth", ai_secret_id: nil, oauth_status: "connected")+ server.oauth_token_store.write!(access_token: "expired-token", refresh_token: "refresh-token")+ allow(DiscourseAi::Mcp::OAuthFlow).to receive(:refresh!).with(server) do+ server.oauth_token_store.write!(access_token: "fresh-token", refresh_token: "refresh-token")+ end+ stub_request(:post, server.url).with(+ headers: {+ "Authorization" => "Bearer expired-token",+ },+ ).to_return(status: 401, body: "")+ end++ describe "#initialize_classic_session" doit "initializes a session and notifies the server" dostub_request(:post, server.url).to_return({@@ -27,7 +40,7 @@ RSpec.describe DiscourseAi::Mcp::Client do{ status: 202, body: "", headers: { "Content-Type" => "application/json" } },)- result = described_class.new(server).initialize_session+ result = described_class.new(server).initialize_classic_sessionexpect(result).to eq(session_id: "session-1",@@ -45,6 +58,8 @@ RSpec.describe DiscourseAi::Mcp::Client dopayload = JSON.parse(request.body)payload["method"] == "initialize" &&+ payload.dig("params", "protocolVersion") == "2025-11-25" &&+ request.headers["Mcp-Protocol-Version"].nil? &&request.headers["Accept"] == "application/json, text/event-stream" &&request.headers["Authorization"] == "Bearer #{ai_secret.secret}"end,@@ -55,11 +70,530 @@ RSpec.describe DiscourseAi::Mcp::Client dopayload = JSON.parse(request.body)payload["method"] == "notifications/initialized" &&+ request.headers["Mcp-Protocol-Version"] == "2025-03-26" &&request.headers["Accept"] == "application/json, text/event-stream" &&request.headers["Mcp-Session-Id"] == "session-1"end,).to have_been_made.onceend++ it "sends the negotiated 2025-03-26 version on subsequent requests" do+ stub_request(:post, server.url).to_return(+ {+ status: 200,+ body: { jsonrpc: "2.0", result: { protocolVersion: "2025-03-26" } }.to_json,+ },+ { status: 202, body: "" },+ { status: 200, body: { jsonrpc: "2.0", result: { tools: [] } }.to_json },+ )++ client = described_class.new(server)+ client.initialize_classic_session+ expect(client.list_tools).to eq([])+ expect(+ a_request(:post, server.url).with do |request|+ %w[notifications/initialized tools/list].include?(JSON.parse(request.body)["method"]) &&+ request.headers["Mcp-Protocol-Version"] == "2025-03-26"+ end,+ ).to have_been_made.twice+ end++ it "uses 2025-11-25 for external servers that select it" do+ stub_request(:post, server.url).to_return(+ {+ status: 200,+ body: { jsonrpc: "2.0", result: { protocolVersion: "2025-11-25" } }.to_json,+ },+ { status: 202, body: "" },+ { status: 200, body: { jsonrpc: "2.0", result: { tools: [] } }.to_json },+ )++ client = described_class.new(server)+ client.initialize_classic_session+ expect(client.list_tools).to eq([])+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "tools/list" &&+ request.headers["Mcp-Protocol-Version"] == "2025-11-25"+ end,+ ).to have_been_made.once+ end++ it "retries 2025-03-26 once when a legacy server explicitly rejects the latest offer" do+ [+ { status: 200, message: "Unsupported protocol version 2025-11-25" },+ { status: 400, message: "Protocol version 2025-11-25 is not supported" },+ ].each do |failure|+ stub_request(:post, server.url).to_return(+ {+ status: failure[:status],+ body: { jsonrpc: "2.0", error: { code: -32_602, message: failure[:message] } }.to_json,+ },+ { status: 200, body: { result: { protocolVersion: "2025-03-26" } }.to_json },+ { status: 202, body: "" },+ )++ result = described_class.new(server).initialize_classic_session+ expect(result[:result]["protocolVersion"]).to eq("2025-03-26")+ end+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body).dig("params", "protocolVersion") == "2025-03-26"+ end,+ ).to have_been_made.twice+ end++ it "retries 2025-03-26 when the server selects unsupported 2025-06-18" do+ stub_request(:post, server.url).to_return(+ { status: 200, body: { result: { protocolVersion: "2025-06-18" } }.to_json },+ { status: 200, body: { result: { protocolVersion: "2025-03-26" } }.to_json },+ { status: 202, body: "" },+ )++ result = described_class.new(server).initialize_classic_session++ expect(result[:result]["protocolVersion"]).to eq("2025-03-26")+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body).dig("params", "protocolVersion") == "2025-03-26"+ end,+ ).to have_been_made.once+ end++ it "does not retry classic initialization for unrelated errors" do+ [200, 400].each do |status|+ stub_request(:post, server.url).to_return(+ status: status,+ body: { jsonrpc: "2.0", error: { code: -32_602, message: "Invalid arguments" } }.to_json,+ )++ expect { described_class.new(server).initialize_classic_session }.to raise_error(+ described_class::Error,+ "Invalid arguments",+ )+ end+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).to have_been_made.twice+ end++ it "rejects a malformed classic initialize error instead of falling back" do+ stub_request(:post, server.url).to_return(status: 400, body: "not JSON")++ expect { described_class.new(server).initialize_classic_session }.to raise_error(+ described_class::Error,+ I18n.t("discourse_ai.mcp_servers.errors.invalid_response"),+ )+ expect(a_request(:post, server.url)).to have_been_made.once+ end++ it "rejects missing and unsupported versions after offering the oldest supported version" do+ [nil, "2026-07-28", "2025-06-18"].each do |version|+ stub_request(:post, server.url).to_return(+ status: 200,+ body: { jsonrpc: "2.0", result: { protocolVersion: version } }.to_json,+ )++ expect {+ described_class.new(server).initialize_classic_session("2025-03-26")+ }.to raise_error(described_class::Error, /MCP protocol version/)+ end+ expect(a_request(:post, server.url)).to have_been_made.times(3)+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "notifications/initialized"+ end,+ ).not_to have_been_made+ end++ it "rejects an unsupported cached protocol version" do+ expect do described_class.new(server, protocol_version: "2026-08-01") end.to raise_error(+ described_class::Error,+ /Unsupported MCP protocol version/,+ )+ end+ end++ describe "dual-era negotiation" do+ it "uses stateless 2026-07-28 requests with matching metadata and safe annotated headers" do+ schema = {+ "type" => "object",+ "properties" => {+ "region" => {+ "type" => "string",+ "x-mcp-header" => "Region",+ },+ "options" => {+ "type" => "object",+ "properties" => {+ "urgent" => {+ "type" => "boolean",+ "x-mcp-header" => "Urgent",+ },+ "count" => {+ "type" => "integer",+ "x-mcp-header" => "Count",+ },+ },+ },+ },+ }+ stub_request(:post, server.url).to_return do |request|+ result =+ case JSON.parse(request.body)["method"]+ when "server/discover"+ { supportedVersions: ["2026-07-28"], capabilities: { tools: {} } }+ when "tools/list"+ { tools: [{ name: "sample", inputSchema: schema }] }+ else+ { content: [{ type: "text", text: "Done" }] }+ end+ { status: 200, body: { jsonrpc: "2.0", result: result }.to_json }+ end++ client = described_class.new(server)+ expect(client.initialize_session).to eq(+ session_id: nil,+ result: {+ "supportedVersions" => ["2026-07-28"],+ "capabilities" => {+ "tools" => {+ },+ },+ "protocolVersion" => "2026-07-28",+ },+ )+ expect(client.list_tools.pluck("name")).to eq(["sample"])+ expect(+ client.call_tool(+ "=?base64?literal?=",+ { region: "Hello, 世界", options: { urgent: false, count: 42 } },+ session_id: "ignored-legacy-session",+ input_schema: schema,+ ),+ ).to eq("content" => [{ "type" => "text", "text" => "Done" }])++ expect(+ a_request(:post, server.url).with do |request|+ body = JSON.parse(request.body)+ metadata = body.dig("params", "_meta")+ metadata["io.modelcontextprotocol/protocolVersion"] == "2026-07-28" &&+ metadata["io.modelcontextprotocol/clientCapabilities"] == {} &&+ metadata.dig("io.modelcontextprotocol/clientInfo", "name") ==+ described_class::USER_AGENT &&+ request.headers["Mcp-Protocol-Version"] == "2026-07-28" &&+ request.headers["Mcp-Method"] == body["method"] &&+ request.headers["Mcp-Session-Id"].nil?+ end,+ ).to have_been_made.times(3)+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "tools/call" &&+ request.headers["Mcp-Name"] == "=?base64?PT9iYXNlNjQ/bGl0ZXJhbD89?=" &&+ request.headers["Mcp-Param-Region"] == "=?base64?SGVsbG8sIOS4lueVjA==?=" &&+ request.headers["Mcp-Param-Urgent"] == "false" &&+ request.headers["Mcp-Param-Count"] == "42"+ end,+ ).to have_been_made.once+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).not_to have_been_made+ end++ it "falls back to classic initialize only after a non-modern 400 response" do+ stub_request(:post, server.url).to_return(+ { status: 400, body: "not JSON" },+ { status: 200, body: { result: { protocolVersion: "2025-03-26" } }.to_json },+ { status: 202, body: "" },+ )++ result = described_class.new(server).initialize_session++ expect(result[:result]["protocolVersion"]).to eq("2025-03-26")+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "server/discover" &&+ request.headers["Mcp-Protocol-Version"] == "2026-07-28"+ end,+ ).to have_been_made.once+ expect(+ a_request(:post, server.url).with do |request|+ body = JSON.parse(request.body)+ body["method"] == "initialize" && body.dig("params", "protocolVersion") == "2025-11-25" &&+ request.headers["Mcp-Protocol-Version"].nil?+ end,+ ).to have_been_made.once+ end++ it "falls back on a legacy JSON-RPC Invalid Request response to the modern probe" do+ stub_request(:post, server.url).to_return(+ {+ status: 400,+ body: { jsonrpc: "2.0", error: { code: -32_600, message: "Invalid Request" } }.to_json,+ },+ { status: 200, body: { result: { protocolVersion: "2025-03-26" } }.to_json },+ { status: 202, body: "" },+ )++ client = described_class.new(server)+ expect(client.initialize_session[:result]["protocolVersion"]).to eq("2025-03-26")+ expect(+ a_request(:post, server.url).with do |request|+ body = JSON.parse(request.body)+ body["method"] == "initialize" && request.headers["Mcp-Protocol-Version"].nil?+ end,+ ).to have_been_made.once+ end++ it "falls back when discovery returns JSON-RPC method not found with HTTP 200" do+ stub_request(:post, server.url).to_return(+ {+ status: 200,+ body: { jsonrpc: "2.0", error: { code: -32_601, message: "Method not found" } }.to_json,+ },+ { status: 200, body: { result: { protocolVersion: "2025-11-25" } }.to_json },+ { status: 202, body: "" },+ )++ result = described_class.new(server).initialize_session++ expect(result[:result]["protocolVersion"]).to eq("2025-11-25")+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).to have_been_made.once+ end++ it "falls back on bare HTTP 404 and 405 discovery responses" do+ [404, 405].each do |status|+ stub_request(:post, server.url).to_return(+ { status: status, body: "Not Found" },+ { status: 200, body: { result: { protocolVersion: "2025-03-26" } }.to_json },+ { status: 202, body: "" },+ )++ result = described_class.new(server).initialize_session+ expect(result[:result]["protocolVersion"]).to eq("2025-03-26")+ end+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).to have_been_made.twice+ end++ it "falls back on plain framework JSON 404 and 405 discovery responses" do+ [404, 405].each do |status|+ stub_request(:post, server.url).to_return(+ { status: status, body: { error: "Not Found" }.to_json },+ { status: 200, body: { result: { protocolVersion: "2025-03-26" } }.to_json },+ { status: 202, body: "" },+ )++ expect(described_class.new(server).initialize_session[:result]["protocolVersion"]).to eq(+ "2025-03-26",+ )+ end+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).to have_been_made.twice+ end++ it "does not fall back on unrelated discovery errors or recognized modern header errors" do+ [+ { status: 404, body: { jsonrpc: "2.0", error: { code: -32_000, message: "Busy" } } },+ {+ status: 404,+ body: {+ jsonrpc: "2.0",+ error: {+ code: -32_020,+ message: "Header mismatch",+ },+ },+ },+ {+ status: 405,+ body: {+ jsonrpc: "2.0",+ error: {+ code: -32_021,+ message: "Header mismatch",+ },+ },+ },+ ].each do |failure|+ stub_request(:post, server.url).to_return(+ status: failure[:status],+ body: failure[:body].to_json,+ )++ expect { described_class.new(server).initialize_session }.to raise_error(+ described_class::Error,+ /Busy|Header mismatch/,+ )+ end+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).not_to have_been_made+ end++ it "falls through to 2025-03-26 after an explicit legacy initialize rejection" do+ stub_request(:post, server.url).to_return(+ { status: 404, body: "" },+ {+ status: 400,+ body: {+ jsonrpc: "2.0",+ error: {+ code: -32_602,+ message: "Unsupported protocol version 2025-11-25",+ },+ }.to_json,+ },+ { status: 200, body: { result: { protocolVersion: "2025-03-26" } }.to_json },+ { status: 202, body: "" },+ )++ client = described_class.new(server)+ expect(client.initialize_session[:result]["protocolVersion"]).to eq("2025-03-26")+ expect(client.protocol_version).to eq("2025-03-26")+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body).dig("params", "protocolVersion") == "2025-03-26"+ end,+ ).to have_been_made.once+ end++ it "uses only an advertised classic version after a modern unsupported-version error" do+ stub_request(:post, server.url).to_return(+ {+ status: 400,+ body: {+ jsonrpc: "2.0",+ error: {+ code: -32_022,+ message: "Unsupported version",+ data: {+ supported: ["2025-03-26"],+ },+ },+ }.to_json,+ },+ { status: 200, body: { result: { protocolVersion: "2025-03-26" } }.to_json },+ { status: 202, body: "" },+ )++ expect(described_class.new(server).initialize_session[:result]["protocolVersion"]).to eq(+ "2025-03-26",+ )+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body).dig("params", "protocolVersion") == "2025-03-26"+ end,+ ).to have_been_made.once+ end++ it "never falls back for recognized modern errors without an advertised compatible version" do+ [+ { code: -32_022, data: { supported: ["2026-08-01"] } },+ { code: -32_020, data: { header: "Mcp-Method" } },+ { code: -32_021 },+ ].each do |error|+ stub_request(:post, server.url).to_return(+ status: 400,+ body: { jsonrpc: "2.0", error: error.merge(message: "Modern request rejected") }.to_json,+ )+ expect { described_class.new(server).initialize_session }.to raise_error(+ described_class::Error,+ )+ end+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).not_to have_been_made+ end++ it "rejects a successful discovery without the requested modern version" do+ stub_request(:post, server.url).to_return(+ status: 200,+ body: { jsonrpc: "2.0", result: { supportedVersions: ["2026-08-01"] } }.to_json,+ )++ expect { described_class.new(server).initialize_session }.to raise_error(+ described_class::Error,+ "Invalid MCP server/discover response",+ )+ end++ it "rejects malformed discovery response shapes" do+ [["unexpected"], 42, { result: [] }, { result: "unsupported" }].each do |payload|+ stub_request(:post, server.url).to_return(status: 200, body: payload.to_json)++ expect { described_class.new(server).initialize_session }.to raise_error(+ described_class::Error,+ I18n.t("discourse_ai.mcp_servers.errors.invalid_response"),+ )+ end+ end++ it "rejects invalid annotated tools rather than sending incomplete modern calls" do+ invalid_schema = {+ "type" => "object",+ "properties" => {+ "query" => {+ "type" => "string",+ "x-mcp-header" => "bad\r\nheader",+ },+ },+ }+ stub_request(:post, server.url).to_return(+ status: 200,+ body: {+ result: {+ tools: [+ { name: "invalid", inputSchema: invalid_schema },+ { name: "valid", inputSchema: { type: "object" } },+ ],+ },+ }.to_json,+ )++ client = described_class.new(server, protocol_version: "2026-07-28")+ expect(client.list_tools.pluck("name")).to eq(["valid"])+ expect do+ client.call_tool("invalid", { query: "secret" }, input_schema: invalid_schema)+ end.to raise_error(described_class::Error, "Invalid x-mcp-header annotation")+ end++ it "does not downgrade after a non-400 probe failure" do+ [403, 500].each do |status|+ stub_request(:post, server.url).to_return(+ status: status,+ body: { error: { message: "Denied" } }.to_json,+ )++ expect { described_class.new(server).initialize_session }.to raise_error(+ described_class::Error,+ "Denied",+ )+ end+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).not_to have_been_made+ endenddescribe "#call_tool" do@@ -79,6 +613,11 @@ RSpec.describe DiscourseAi::Mcp::Client doresult = described_class.new(server).call_tool("lookup", { id: 1 }, session_id: "session-1")expect(result).to eq("content" => [{ "type" => "text", "text" => "Hello from MCP" }])+ expect(+ a_request(:post, server.url).with do |request|+ request.headers["Mcp-Protocol-Version"].nil?+ end,+ ).to have_been_made.onceendit "returns tool execution errors from the response body even on non-2xx statuses" do@@ -120,33 +659,22 @@ RSpec.describe DiscourseAi::Mcp::Client doendit "preserves allow_result_error when retrying after an OAuth refresh" 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: 404,- body: {- jsonrpc: "2.0",- result: {- content: [{ type: "text", text: "Not found: Project google.com:chops-prod" }],- isError: true,- },- }.to_json,- headers: {- "Content-Type" => "application/json",+ stub_oauth_refresh+ stub_request(:post, server.url).with(+ headers: {+ "Authorization" => "Bearer fresh-token",+ },+ ).to_return(+ status: 404,+ body: {+ jsonrpc: "2.0",+ result: {+ content: [{ type: "text", text: "Not found: Project google.com:chops-prod" }],+ isError: true,},+ }.to_json,+ headers: {+ "Content-Type" => "application/json",},)@@ -156,6 +684,13 @@ RSpec.describe DiscourseAi::Mcp::Client do"content" => [{ "type" => "text", "text" => "Not found: Project google.com:chops-prod" }],"isError" => true,)+ expect(DiscourseAi::Mcp::OAuthFlow).to have_received(:refresh!).with(server).once+ expect(+ a_request(:post, server.url).with(headers: { "Authorization" => "Bearer expired-token" }),+ ).to have_been_made.once+ expect(+ a_request(:post, server.url).with(headers: { "Authorization" => "Bearer fresh-token" }),+ ).to have_been_made.onceendit "raises when a session expires" do@@ -210,21 +745,12 @@ RSpec.describe DiscourseAi::Mcp::Client doendit "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" } },+ stub_oauth_refresh+ stub_request(:post, server.url).with(+ headers: {+ "Authorization" => "Bearer fresh-token",+ },+ ).to_return({status: 200,body: {@@ -245,14 +771,107 @@ RSpec.describe DiscourseAi::Mcp::Client do{ status: 202, body: "", headers: { "Content-Type" => "application/json" } },)- result = described_class.new(server).initialize_session+ result = described_class.new(server).initialize_classic_sessionexpect(result[:session_id]).to eq("session-2")+ expect(DiscourseAi::Mcp::OAuthFlow).to have_received(:refresh!).with(server).onceexpect(a_request(:post, server.url).with do |request|- JSON.parse(request.body)["method"] == "initialize"+ JSON.parse(request.body)["method"] == "initialize" &&+ request.headers["Authorization"] == "Bearer expired-token"end,- ).to have_been_made.twice+ ).to have_been_made.once+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize" &&+ request.headers["Authorization"] == "Bearer fresh-token"+ end,+ ).to have_been_made.once+ end++ it "refreshes OAuth before retrying a modern discovery request" do+ stub_oauth_refresh+ stub_request(:post, server.url).with(+ headers: {+ "Authorization" => "Bearer fresh-token",+ },+ ).to_return(+ status: 200,+ body: { jsonrpc: "2.0", result: { supportedVersions: ["2026-07-28"] } }.to_json,+ )++ result = described_class.new(server).initialize_session++ expect(result[:result]["protocolVersion"]).to eq("2026-07-28")+ expect(DiscourseAi::Mcp::OAuthFlow).to have_received(:refresh!).with(server).once+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "server/discover" &&+ request.headers["Mcp-Protocol-Version"] == "2026-07-28" &&+ request.headers["Authorization"] == "Bearer expired-token"+ end,+ ).to have_been_made.once+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "server/discover" &&+ request.headers["Mcp-Protocol-Version"] == "2026-07-28" &&+ request.headers["Authorization"] == "Bearer fresh-token"+ end,+ ).to have_been_made.once+ end++ it "keeps classic initialization errors visible after an OAuth refresh" do+ stub_oauth_refresh+ stub_request(:post, server.url).with(+ headers: {+ "Authorization" => "Bearer fresh-token",+ },+ ).to_return(+ status: 400,+ body: { error: { code: -32_602, message: "Invalid arguments" } }.to_json,+ )++ expect { described_class.new(server).initialize_classic_session }.to raise_error(+ described_class::Error,+ "Invalid arguments",+ )+ expect(DiscourseAi::Mcp::OAuthFlow).to have_received(:refresh!).with(server).once+ expect(+ a_request(:post, server.url).with(headers: { "Authorization" => "Bearer expired-token" }),+ ).to have_been_made.once+ expect(+ a_request(:post, server.url).with(headers: { "Authorization" => "Bearer fresh-token" }),+ ).to have_been_made.once+ end++ it "keeps discovery fallback status tolerance after an OAuth refresh" do+ stub_oauth_refresh+ stub_request(:post, server.url).with(+ headers: {+ "Authorization" => "Bearer fresh-token",+ },+ ).to_return(+ { status: 400, body: "not JSON" },+ { status: 200, body: { result: { protocolVersion: "2025-03-26" } }.to_json },+ { status: 202, body: "" },+ )++ result = described_class.new(server).initialize_session++ expect(result[:result]["protocolVersion"]).to eq("2025-03-26")+ expect(DiscourseAi::Mcp::OAuthFlow).to have_received(:refresh!).with(server).once+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "server/discover" &&+ request.headers["Authorization"] == "Bearer expired-token"+ end,+ ).to have_been_made.once+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "server/discover" &&+ request.headers["Authorization"] == "Bearer fresh-token"+ end,+ ).to have_been_made.onceendenddiff --git a/plugins/discourse-ai/spec/lib/mcp/header_mapper_spec.rb b/plugins/discourse-ai/spec/lib/mcp/header_mapper_spec.rbnew file mode 100644index 00000000000..3ec45b995cf--- /dev/null+++ b/plugins/discourse-ai/spec/lib/mcp/header_mapper_spec.rb@@ -0,0 +1,352 @@+# frozen_string_literal: true++RSpec.describe DiscourseAi::Mcp::HeaderMapper do+ def tool_headers(schema, arguments = {})+ described_class.request_headers(+ "tools/call",+ { name: "search", arguments: arguments },+ input_schema: schema,+ )+ end++ describe ".request_headers" do+ it "maps reachable local references and ignores unused definitions" do+ schema = {+ "$defs" => {+ "Region" => {+ "type" => "string",+ "x-mcp-header" => "Region",+ },+ "Place/Config" => {+ "properties" => {+ "active" => {+ "type" => "boolean",+ "x-mcp-header" => "Active",+ },+ },+ },+ "Unused" => {+ "type" => "string",+ "x-mcp-header" => "bad\r\nheader",+ },+ },+ "properties" => {+ "region" => {+ "$ref" => "#/$defs/Region",+ },+ "config" => {+ "$ref" => "#/$defs/Place~1Config",+ },+ },+ }++ expect(tool_headers(schema, region: "West", config: { active: false })).to eq(+ "Mcp-Method" => "tools/call",+ "Mcp-Name" => "search",+ "Mcp-Param-Region" => "West",+ "Mcp-Param-Active" => "false",+ )+ end++ it "resolves array indices, percent-encoded names and empty pointer keys" do+ schema = {+ "$defs" => {+ "Region" => {+ "allOf" => [{ "type" => "string", "x-mcp-header" => "Region" }],+ },+ "Place Config+East" => {+ "type" => "string",+ "x-mcp-header" => "Place",+ },+ "Empty" => {+ "properties" => {+ "" => {+ "type" => "boolean",+ "x-mcp-header" => "Empty",+ },+ },+ },+ },+ "properties" => {+ "region" => {+ "$ref" => "#/$defs/Region/allOf/0",+ },+ "place" => {+ "$ref" => "#/$defs/Place%20Config+East",+ },+ "empty" => {+ "$ref" => "#/$defs/Empty/properties/",+ },+ },+ }++ expect(tool_headers(schema, region: "West", place: "Central", empty: false)).to eq(+ "Mcp-Method" => "tools/call",+ "Mcp-Name" => "search",+ "Mcp-Param-Region" => "West",+ "Mcp-Param-Place" => "Central",+ "Mcp-Param-Empty" => "false",+ )+ end++ it "rejects malformed pointer escapes, array indices and external references" do+ schema = {+ "$defs" => {+ "Region" => {+ "allOf" => [{ "type" => "string" }],+ },+ },+ "properties" => {+ "region" => {+ "$ref" => nil,+ },+ },+ }+ bad_refs = %w[+ #/$defs/Region/allOf/01+ #/$defs/Region/allOf/-+ #/$defs/Region/allOf/1+ #/$defs/Region/allOf/name+ #/$defs/Region~2allOf/0+ #/$defs/Region%GG+ #/$defs/Region%FF+ #Region+ https://schemas.example.com/region+ ]++ bad_refs.each do |ref|+ schema["properties"]["region"]["$ref"] = ref+ expect { tool_headers(schema) }.to raise_error(+ DiscourseAi::Mcp::Client::Error,+ "Unsupported MCP tool schema reference",+ )+ end+ end++ it "rejects annotated cycles but permits unannotated recursive references" do+ node = { "properties" => { "parent" => { "$ref" => "#/$defs/Node" } } }+ schema = { "$defs" => { "Node" => node }, "properties" => { "parent" => node } }+ expect(tool_headers(schema)).to eq("Mcp-Method" => "tools/call", "Mcp-Name" => "search")++ node["properties"]["name"] = { "type" => "string", "x-mcp-header" => "Name" }+ expect { tool_headers(schema) }.to raise_error(+ DiscourseAi::Mcp::Client::Error,+ "Unsupported MCP tool schema reference",+ )+ end++ it "permits unannotated root references and literal annotation data" do+ schema = {+ "properties" => {+ "parent" => {+ "$ref" => "#",+ },+ "entries" => {+ "items" => {+ "properties" => {+ "x-mcp-header" => {+ "type" => "string",+ },+ },+ },+ },+ },+ "default" => {+ "x-mcp-header" => "literal",+ },+ "examples" => [{ "x-mcp-header" => "literal" }],+ "const" => {+ "x-mcp-header" => "literal",+ },+ "enum" => [{ "x-mcp-header" => "literal" }],+ }+ expect(tool_headers(schema)).to eq("Mcp-Method" => "tools/call", "Mcp-Name" => "search")++ schema["properties"]["region"] = { "type" => "string", "x-mcp-header" => "Region" }+ expect { tool_headers(schema) }.to raise_error(+ DiscourseAi::Mcp::Client::Error,+ "Unsupported MCP tool schema reference",+ )+ end++ it "rejects annotations through unsupported branches inline and through local references" do+ annotation = { "type" => "string", "x-mcp-header" => "Token" }+ branches = {+ "items" => annotation,+ "anyOf" => [{ "$ref" => "#/$defs/Token/allOf/0" }],+ "additionalProperties" => annotation,+ "patternProperties" => {+ "^token$" => annotation,+ },+ "dependentSchemas" => {+ "token" => {+ "properties" => {+ "value" => annotation,+ },+ },+ },+ }++ branches.each do |keyword, value|+ inline = {+ "properties" => {+ "token" => {+ keyword => value,+ },+ },+ "$defs" => {+ "Token" => {+ "allOf" => [annotation],+ },+ },+ }+ referenced = {+ "$defs" => {+ "Nested" => {+ keyword => value,+ },+ "Token" => {+ "allOf" => [annotation],+ },+ },+ "properties" => {+ "token" => {+ "$ref" => "#/$defs/Nested",+ },+ },+ }+ [inline, referenced].each do |schema|+ expect { tool_headers(schema) }.to raise_error(+ DiscourseAi::Mcp::Client::Error,+ "Invalid x-mcp-header annotation",+ )+ end+ end+ end++ it "treats schema-map keys named x-mcp-header as property names" do+ nested = {+ "patternProperties" => {+ "x-mcp-header" => {+ "type" => "string",+ },+ },+ "dependentSchemas" => {+ "x-mcp-header" => {+ "properties" => {+ "other" => {+ "type" => "string",+ },+ },+ },+ },+ }+ schema = {+ "$defs" => {+ "Nested" => nested,+ },+ "properties" => {+ "inline" => {+ "items" => nested,+ },+ "referenced" => {+ "anyOf" => [{ "$ref" => "#/$defs/Nested" }],+ },+ },+ }+ expect(tool_headers(schema)).to eq("Mcp-Method" => "tools/call", "Mcp-Name" => "search")+ end++ it "treats dependentRequired as data even behind unsupported branches and references" do+ required = { "dependentRequired" => { "x-mcp-header" => ["token"] } }+ schema = {+ "dependentRequired" => {+ "x-mcp-header" => ["other"],+ },+ "$defs" => {+ "Required" => required,+ },+ "properties" => {+ "inline" => {+ "anyOf" => [required],+ },+ "referenced" => {+ "items" => {+ "$ref" => "#/$defs/Required",+ },+ },+ },+ }++ expect(tool_headers(schema)).to eq("Mcp-Method" => "tools/call", "Mcp-Name" => "search")+ end++ it "ignores unused and unresolved references but rejects reachable external references" do+ schema = {+ "$defs" => {+ "Unused" => {+ "$ref" => "https://schemas.example.com/tool.json",+ },+ },+ "properties" => {+ "local" => {+ "$ref" => "#/$defs/Missing",+ },+ },+ }+ expect(tool_headers(schema)).to eq("Mcp-Method" => "tools/call", "Mcp-Name" => "search")++ schema["properties"]["remote"] = { "$ref" => "https://schemas.example.com/tool.json" }+ expect { tool_headers(schema) }.to raise_error(+ DiscourseAi::Mcp::Client::Error,+ "Unsupported MCP tool schema reference",+ )+ end++ it "rejects unsafe annotation names, locations, types and duplicate header names" do+ schema = { "properties" => { "token" => { "type" => "string", "x-mcp-header" => "Token" } } }+ ["bad\r\nheader", ""].each do |name|+ schema["properties"]["token"]["x-mcp-header"] = name+ expect { tool_headers(schema) }.to raise_error(DiscourseAi::Mcp::Client::Error)+ end+ schema["properties"]["token"]["x-mcp-header"] = "Token"+ schema["properties"]["token"]["type"] = "number"+ expect { tool_headers(schema) }.to raise_error(DiscourseAi::Mcp::Client::Error)++ schema["properties"]["token"]["type"] = "string"+ schema["properties"]["other"] = { "type" => "string", "x-mcp-header" => "token" }+ expect { tool_headers(schema) }.to raise_error(DiscourseAi::Mcp::Client::Error)+ expect { tool_headers("x-mcp-header" => "Token", "type" => "string") }.to raise_error(+ DiscourseAi::Mcp::Client::Error,+ )+ end++ it "rejects invalid annotated arguments and encodes unsafe header values" do+ schema = {+ "properties" => {+ "count" => {+ "type" => "integer",+ "x-mcp-header" => "Count",+ },+ "region" => {+ "type" => "string",+ "x-mcp-header" => "Region",+ },+ },+ }+ expect(tool_headers(schema, count: 1, region: "Hello, 世界")).to eq(+ "Mcp-Method" => "tools/call",+ "Mcp-Name" => "search",+ "Mcp-Param-Count" => "1",+ "Mcp-Param-Region" => "=?base64?SGVsbG8sIOS4lueVjA==?=",+ )+ expect { tool_headers(schema, count: 2**53) }.to raise_error(+ described_class::InvalidArgumentError,+ "Invalid MCP annotated tool argument",+ )+ expect { tool_headers(schema, count: "1") }.to raise_error(+ described_class::InvalidArgumentError,+ )+ 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.rbindex 8a11a307a62..6484305b3c8 100644--- a/plugins/discourse-ai/spec/lib/mcp/tool_registry_spec.rb+++ b/plugins/discourse-ai/spec/lib/mcp/tool_registry_spec.rb@@ -3,6 +3,33 @@RSpec.describe DiscourseAi::Mcp::ToolRegistry dobefore { enable_current_plugin }+ describe ".refresh!" do+ it "discovers and caches tools from a modern-only server" do+ server = Fabricate(:ai_mcp_server, url: "https://mcp.example.com")+ AiMcpServer.stubs(:validate_hostname_public!).returns(true)+ stub_request(:post, server.url).to_return do |request|+ result =+ if JSON.parse(request.body)["method"] == "server/discover"+ { supportedVersions: ["2026-07-28"], capabilities: { tools: {} } }+ else+ { tools: [{ name: "search", inputSchema: { type: "object" } }] }+ end+ { status: 200, body: { jsonrpc: "2.0", result: result }.to_json }+ end++ definitions = described_class.refresh!(server, raise_on_error: true)++ expect(definitions.pluck("name")).to eq(["search"])+ expect(server.reload.protocol_version).to eq("2026-07-28")+ expect(server.last_health_status).to eq("healthy")+ expect(+ a_request(:post, server.url).with do |request|+ JSON.parse(request.body)["method"] == "initialize"+ end,+ ).not_to have_been_made+ end+ end+describe ".cache_key" doit "namespaces the cache by current multisite database" doRailsMultisite::ConnectionManagement.stubs(:current_db).returns("second")