We present a new theory for the hierarchical clustering of dark matter (DM) halos based on stochastic differential equations, that constitutes a change of perspective with respect to existing frameworks (e.g., the excursion set approach); this work is specifically focused on the halo mass function. First, we present a stochastic differential equation that describes fluctuations in the mass growth of DM halos, as driven by a multiplicative white (Gaussian) noise dependent on the spherical collapse threshold and on the power spectrum of DM perturbations. We demonstrate that such a noise yields an average drift of the halo population toward larger masses, that quantitatively renders the standard hierarchical clustering. Then, we solve the Fokker-Planck equation associated to the stochastic dynamics, and obtain the Press & Schechter mass function as a (stationary) solution. Moreover, generalizing our treatment to a mass-dependent collapse threshold, we obtain an exact analytic solution capable of fitting remarkably well the N-body mass function over a wide range in mass and redshift. All in all, the new perspective offered by the theory presented here can contribute to better understand the gravitational dynamics leading to the formation, evolution and statistics of DM halos across cosmic times.