diff --git a/lib/mcp/server.rb b/lib/mcp/server.rb index d9e53927..8a20d125 100644 --- a/lib/mcp/server.rb +++ b/lib/mcp/server.rb @@ -858,7 +858,7 @@ def handle_request(request, method, session: nil, related_request_id: nil, auth_ end end - ->(params) { + ->(params) do reported_exception = nil instrument_call( method, @@ -990,13 +990,15 @@ def handle_request(request, method, session: nil, related_request_id: nil, auth_ wrapped = RequestHandlerError.new("Internal error handling #{method} request", request, original_error: e) reported_exception = wrapped raise wrapped - ensure - # `cancellation` is non-nil exactly when this request claimed the id above, so this also keeps `initialize` - # (which never registers) from evicting an in-flight registration under a reused id when the duplicate-`initialize` - # refusal raises out of the handler. - session&.unregister_in_flight(related_request_id, cancellation: cancellation) if related_request_id && cancellation end - } + ensure + # Outside the instrumented block, which `configuration.around_request` may never run. + # + # `cancellation` is non-nil exactly when this request claimed the id above, so this also keeps `initialize` + # (which never registers) from evicting an in-flight registration under a reused id when the duplicate-`initialize` + # refusal raises out of the handler. + session&.unregister_in_flight(related_request_id, cancellation: cancellation) if related_request_id && cancellation + end end # Whether this request belongs to the modern lifecycle, used to refuse the RPCs SEP-2575 removed from it. diff --git a/test/mcp/server/transports/streamable_http_transport_test.rb b/test/mcp/server/transports/streamable_http_transport_test.rb index 8c24dd7c..5f6dfc53 100644 --- a/test/mcp/server/transports/streamable_http_transport_test.rb +++ b/test/mcp/server/transports/streamable_http_transport_test.rb @@ -4361,6 +4361,48 @@ def close end end + test "a session whose request around_request refused expires like any other" do + configuration = MCP::Configuration.new + configuration.around_request = ->(data, &request_handler) do + raise "refused by the hook" if data[:method] == Methods::TOOLS_CALL + + request_handler.call + end + server = Server.new(name: "test", tools: [], prompts: [], resources: [], configuration: configuration) + transport = StreamableHTTPTransport.new(server, enable_json_response: true, session_idle_timeout: 60, max_sessions: 1) + server.transport = transport + initialize_request = -> do + create_rack_request( + "POST", + "/", + { "CONTENT_TYPE" => "application/json" }, + { jsonrpc: "2.0", method: "initialize", id: "init", params: initialize_params }.to_json, + ) + end + + session_id = transport.handle_request(initialize_request.call)[1]["mcp-session-id"] + refused = transport.handle_request(create_rack_request( + "POST", + "/", + { "CONTENT_TYPE" => "application/json", "HTTP_MCP_SESSION_ID" => session_id }, + { jsonrpc: "2.0", id: "call-1", method: "tools/call", params: { name: "any", arguments: {} } }.to_json, + )) + server_session = transport.instance_variable_get(:@sessions)[session_id][:server_session] + + assert_equal JsonRpcHandler::ErrorCode::INTERNAL_ERROR, JSON.parse(refused[2][0]).dig("error", "code") + assert_nil server_session.lookup_in_flight("call-1") + + # The session was last active, and its last request finished, longer ago than the timeout allows. + transport.instance_variable_get(:@sessions)[session_id][:last_active_at] -= 61 + server_session.instance_variable_set(:@last_request_finished_at, server_session.in_flight_activity.last - 61) + transport.send(:reap_expired_sessions) + + refute transport.instance_variable_get(:@sessions).key?(session_id) + assert_equal 200, transport.handle_request(initialize_request.call)[0] + ensure + transport&.close + end + test "a session with a request in flight does not expire, whichever path checks it" do session_post = ->(session_id, body) do create_rack_request("POST", "/", { "CONTENT_TYPE" => "application/json", "HTTP_MCP_SESSION_ID" => session_id }, body.to_json) diff --git a/test/mcp/server_cancellation_test.rb b/test/mcp/server_cancellation_test.rb index b33ac2a1..532199d1 100644 --- a/test/mcp/server_cancellation_test.rb +++ b/test/mcp/server_cancellation_test.rb @@ -456,6 +456,34 @@ def handle_request(request); end assert_includes @mock_transport.cancelled_request_ids, "req-9" end + test "a request that around_request stops before its handler is no longer in flight" do + ran = [] + @server.define_tool(name: "guarded") do + ran << :tool + Tool::Response.new([{ type: "text", text: "ok" }]) + end + hooks = { + "raises" => ->(_data, &_request_handler) { raise "refused by the hook" }, + "returns without calling the handler" => ->(_data, &_request_handler) { { content: [] } }, + "raises after the handler ran" => ->(_data, &request_handler) do + request_handler.call + raise "failed after the handler" + end, + } + + hooks.each_with_index do |(label, hook), index| + @server.configuration.around_request = hook + request_id = "guarded-#{index}" + + @session.handle(jsonrpc: "2.0", id: request_id, method: Methods::TOOLS_CALL, params: { name: "guarded", arguments: {} }) + + assert_nil @session.lookup_in_flight(request_id), label + assert_equal [false, @session.in_flight_activity.last], @session.in_flight_activity, label + refute_nil @session.in_flight_activity.last, label + end + assert_equal [:tool], ran + end + test "register_in_flight refuses an id that is already in flight" do first = @session.register_in_flight("req-1")