In general, the mass of a system of particles (e.g. the proton which is a system of three quarks) is not the sum of the masses of the constituent particles.
The total energy of the system equals the sum of (a) the rest-energies E0 of the constituent particles (which correspond to their individual masses via E0 = mc2), (b) their kinetic energies, and (c) the potential energy of the system. The total energy corresponds to the mass of the system via E = mc2, if the system "as a whole" is at rest, i.e. if the total (vector) momentum is zero.
(By "mass" I always mean what is often called "rest mass.")
Most of the proton REST mass is energy anyway. So how does that work?
This doesn't make any sense.
A photon has energy, yet it has no rest mass! So having energy does NOT automatically equate to having rest mass.
A rest mass has an EQUIVALENT energy content. But an object such as a proton does NOT just have "energy content". It may have other properties as well, such as charge, spin... and yes, rest mass.