The personal finance app for everyone (by everyone)
Ruby
feat(mcp): support Streamable HTTP transport (protocol 2025-06-18) (#2631)
Luke Blankenship3a50846cc751
diff --git a/app/controllers/mcp_controller.rb b/app/controllers/mcp_controller.rbindex 159fdcc75b..b883493954 100644--- a/app/controllers/mcp_controller.rb+++ b/app/controllers/mcp_controller.rb@@ -1,7 +1,9 @@class McpController < ApplicationControllerinclude OauthBase- PROTOCOL_VERSION = "2025-03-26"+ PROTOCOL_VERSION = "2025-06-18"+ SUPPORTED_PROTOCOL_VERSIONS = [ "2025-03-26", PROTOCOL_VERSION ].freeze+ MCP_SESSION_TTL = 1.day# Skip session-based auth and CSRF — this is a token-authenticated APIskip_authentication@@ -11,6 +13,7 @@ class McpController < ApplicationControllerskip_before_action :detect_osbefore_action :authenticate_mcp_token!+ after_action :set_mcp_response_headersdef handlebody = parse_request_body@@ -48,9 +51,11 @@ class McpController < ApplicationControllerenddef dispatch_jsonrpc(request_id, method, params)+ return unless prepare_mcp_request_context(request_id, method, params)+case methodwhen "initialize"- handle_initialize+ handle_initialize(params)when "tools/list"handle_tools_listwhen "tools/call"@@ -61,11 +66,16 @@ class McpController < ApplicationControllerendend- def handle_initialize+ def handle_initialize(params)+ @mcp_protocol_version = negotiated_protocol_version(params)+ @mcp_session_id = SecureRandom.uuid+ Rails.cache.write(mcp_session_cache_key(@mcp_session_id), mcp_user.id, expires_in: MCP_SESSION_TTL)+{- protocolVersion: PROTOCOL_VERSION,+ protocolVersion: @mcp_protocol_version,capabilities: { tools: {} },- serverInfo: { name: "sure", version: "1.0" }+ serverInfo: { name: "sure", version: "1.0" },+ sessionId: @mcp_session_id}end@@ -161,6 +171,48 @@ class McpController < ApplicationController@mcp_userend+ def prepare_mcp_request_context(request_id, method, params)+ return true if method == "initialize"++ @mcp_protocol_version = mcp_request_header("Mcp-Protocol-Version").presence || PROTOCOL_VERSION++ unless SUPPORTED_PROTOCOL_VERSIONS.include?(@mcp_protocol_version)+ render_jsonrpc_error(+ request_id,+ -32600,+ t("mcp.errors.unsupported_protocol_version", version: @mcp_protocol_version),+ status: :bad_request+ )+ return false+ end++ session_id = mcp_request_header("Mcp-Session-Id").presence+ return true unless session_id++ unless Rails.cache.read(mcp_session_cache_key(session_id)) == mcp_user.id+ render_jsonrpc_error(request_id, -32600, t("mcp.errors.invalid_session_id"), status: :not_found)+ return false+ end++ @mcp_session_id = session_id+ true+ end++ def negotiated_protocol_version(params)+ requested_version = params&.dig("protocolVersion").presence || PROTOCOL_VERSION+ return requested_version if SUPPORTED_PROTOCOL_VERSIONS.include?(requested_version)++ PROTOCOL_VERSION+ end++ def mcp_session_cache_key(session_id)+ "mcp:session:#{session_id}"+ end++ def mcp_request_header(name)+ request.headers[name] || request.get_header("HTTP_#{name.upcase.tr('-', '_')}")+ end+def render_mcp_unauthorizedresponse.set_header("WWW-Authenticate",@@ -169,11 +221,19 @@ class McpController < ApplicationControllerrender json: { error: "unauthorized" }, status: :unauthorizedend- def render_jsonrpc_error(id, code, message)+ def render_jsonrpc_error(id, code, message, status: :ok, data: nil)+ error = { code: code, message: message }+ error[:data] = data if data+render json: {jsonrpc: "2.0",id: id,- error: { code: code, message: message }- }+ error: error+ }, status: status+ end++ def set_mcp_response_headers+ response.set_header("Mcp-Protocol-Version", @mcp_protocol_version || PROTOCOL_VERSION)+ response.set_header("Mcp-Session-Id", @mcp_session_id) if @mcp_session_id.present?endenddiff --git a/config/locales/defaults/en.yml b/config/locales/defaults/en.ymlindex 609c459d95..5cc24030db 100644--- a/config/locales/defaults/en.yml+++ b/config/locales/defaults/en.yml@@ -7,6 +7,10 @@ en:close: "Close"global:expand: "Expand"+ mcp:+ errors:+ invalid_session_id: "Invalid MCP session id"+ unsupported_protocol_version: "Unsupported MCP protocol version: %{version}"activerecord:errors:messages:diff --git a/test/controllers/mcp_controller_test.rb b/test/controllers/mcp_controller_test.rbindex aec44a8c8a..bc4eb7cb7e 100644--- a/test/controllers/mcp_controller_test.rb+++ b/test/controllers/mcp_controller_test.rb@@ -1,6 +1,8 @@require "test_helper"class McpControllerTest < ActionDispatch::IntegrationTest+ MCP_PROTOCOL_VERSION = "2025-06-18"+setup do@user = users(:family_admin)@token = "test-mcp-token-#{SecureRandom.hex(8)}"@@ -44,7 +46,7 @@ class McpControllerTest < ActionDispatch::IntegrationTestassert_response :okresult = JSON.parse(response.body)["result"]- assert_equal "2025-03-26", result["protocolVersion"]+ assert_mcp_initialize_response(result)endtest "authenticates a token issued to a dynamically registered MCP client" do@@ -94,7 +96,7 @@ class McpControllerTest < ActionDispatch::IntegrationTestheaders: mcp_headers(token_response["access_token"])assert_response :ok- assert_equal "2025-03-26", JSON.parse(response.body).dig("result", "protocolVersion")+ assert_mcp_initialize_response(JSON.parse(response.body)["result"])endtest "rejects token with read-only scope" do@@ -253,7 +255,7 @@ class McpControllerTest < ActionDispatch::IntegrationTesttest "initialize returns server info and capabilities" dowith_mcp_env do- post "/mcp", params: jsonrpc_request("initialize", { protocolVersion: "2025-03-26" }).to_json,+ post "/mcp", params: jsonrpc_request("initialize", { protocolVersion: MCP_PROTOCOL_VERSION }).to_json,headers: mcp_headers(@token)assert_response :ok@@ -262,12 +264,38 @@ class McpControllerTest < ActionDispatch::IntegrationTestassert_equal "2.0", body["jsonrpc"]assert_equal 1, body["id"]- assert_equal "2025-03-26", result["protocolVersion"]+ assert_mcp_initialize_response(result)assert_equal "sure", result["serverInfo"]["name"]assert result["capabilities"].key?("tools")endend+ test "initialize echoes a supported legacy protocol version" do+ with_mcp_env do+ post "/mcp", params: jsonrpc_request("initialize", { protocolVersion: "2025-03-26" }).to_json,+ headers: mcp_headers(@token)++ assert_response :ok+ result = JSON.parse(response.body)["result"]+ assert_equal "2025-03-26", result["protocolVersion"]+ assert_equal "2025-03-26", response.headers["Mcp-Protocol-Version"]+ assert_match(/\A[0-9a-f-]{36}\z/, result["sessionId"])+ end+ end++ test "initialize negotiates unsupported protocol versions to the default version" do+ with_mcp_env do+ post "/mcp", params: jsonrpc_request("initialize", { protocolVersion: "2099-01-01" }, id: 24).to_json,+ headers: mcp_headers(@token)++ assert_response :ok+ body = JSON.parse(response.body)+ assert_equal 24, body["id"]+ assert_equal MCP_PROTOCOL_VERSION, body.dig("result", "protocolVersion")+ assert_equal MCP_PROTOCOL_VERSION, response.headers["Mcp-Protocol-Version"]+ end+ end+# -- tools/list --test "tools/list returns all assistant function tools" do@@ -301,6 +329,59 @@ class McpControllerTest < ActionDispatch::IntegrationTestendend+ test "tools/list accepts and echoes a valid MCP session id" do+ with_mcp_cache do+ with_mcp_env do+ post "/mcp", params: jsonrpc_request("initialize").to_json,+ headers: mcp_headers(@token)++ assert_response :ok+ session_id = response.headers["Mcp-Session-Id"]+ assert session_id.present?, "initialize should return an MCP session id"++ post "/mcp", params: jsonrpc_request("tools/list").to_json,+ headers: mcp_headers(@token).merge(+ "Mcp-Protocol-Version" => MCP_PROTOCOL_VERSION,+ "Mcp-Session-Id" => session_id+ )++ assert_response :ok+ assert_equal MCP_PROTOCOL_VERSION, response.headers["Mcp-Protocol-Version"]+ assert_equal session_id, response.headers["Mcp-Session-Id"]+ assert_kind_of Array, JSON.parse(response.body).dig("result", "tools")+ end+ end+ end++ test "tools/list rejects an invalid MCP session id" do+ with_mcp_env do+ post "/mcp", params: jsonrpc_request("tools/list", {}, id: 25).to_json,+ headers: mcp_headers(@token).merge(+ "Mcp-Protocol-Version" => MCP_PROTOCOL_VERSION,+ "Mcp-Session-Id" => SecureRandom.uuid+ )++ assert_response :not_found+ body = JSON.parse(response.body)+ assert_equal 25, body["id"]+ assert_equal(-32600, body["error"]["code"])+ assert_includes body["error"]["message"], "Invalid MCP session id"+ end+ end++ test "tools/list rejects unsupported MCP protocol version headers" do+ with_mcp_env do+ post "/mcp", params: jsonrpc_request("tools/list", {}, id: 26).to_json,+ headers: mcp_headers(@token).merge("Mcp-Protocol-Version" => "2099-01-01")++ assert_response :bad_request+ body = JSON.parse(response.body)+ assert_equal 26, body["id"]+ assert_equal(-32600, body["error"]["code"])+ assert_includes body["error"]["message"], "2099-01-01"+ end+ end+test "tools/list omits preview tools for a user without preview features" do@user.update!(preferences: (@user.preferences || {}).merge("preview_features_enabled" => false))@@ -551,6 +632,14 @@ class McpControllerTest < ActionDispatch::IntegrationTestwith_env_overrides("MCP_API_TOKEN" => @token, "MCP_USER_EMAIL" => @user.email, &block) # pipelock:ignoreend+ def with_mcp_cache+ original_cache = Rails.cache+ Rails.cache = ActiveSupport::Cache::MemoryStore.new+ yield+ ensure+ Rails.cache = original_cache+ end+def mcp_headers(token){"Content-Type" => "application/json",@@ -565,4 +654,11 @@ class McpControllerTest < ActionDispatch::IntegrationTestdef jsonrpc_notification(method, params = {}){ jsonrpc: "2.0", method: method, params: params }end++ def assert_mcp_initialize_response(result)+ assert_equal MCP_PROTOCOL_VERSION, result["protocolVersion"]+ assert_match(/\A[0-9a-f-]{36}\z/, result["sessionId"])+ assert_equal MCP_PROTOCOL_VERSION, response.headers["Mcp-Protocol-Version"]+ assert_equal result["sessionId"], response.headers["Mcp-Session-Id"]+ endend