The Florida-based side opened the scoring after just 35 seconds when Maximiliano Falcon headed home from Jordi Alba's cross following a corner.
However, the visitors' joy was short-lived as the hosts equalised immediately: Cristian Arango scored in the third minute after a quick counter-attack and a precise pass from Espinoza.
San Jose then took the lead again in the 37th minute through Beau Leroux, but Tadeo Allende restored parity before half-time in the 44th minute after a swift Miami move.
In first-half injury time, the Earthquakes struck again as Ian Harkes scored with a powerful shot from distance, assisted by Leroux, to make it 3-2 to the hosts at half-time.
Allende completed his brace in the 52nd minute, following a team move in which Messi contributed to the build-up and Baltasar Rodriguez played the decisive pass.
The finale was intense, with Messi almost scoring the winner in extra time, but goalkeeper Daniel de Sousa Britto spectacularly blocked from close range.
As a result, Inter Miami have conceded at least three goals in three of their last four games. San Jose, meanwhile, remain unbeaten in their last three MLS outings.