We propose cotunneling as the microscopic mechanism that makes possible inelastic electron spectroscopy of magnetic atoms in surfaces for a wide range of systems, including single magnetic adatoms, molecules and molecular stacks. We describe electronic transport between the scanning tip and the conducting surface through the magnetic system (MS) with a generalized Anderson model, without making use of effective spin models. Transport and spin dynamics are described with an effective cotunneling Hamiltonian in which the correlations in the magnetic system are calculated exactly and the coupling to the electrodes is included up to second order in the tip-MS and MS-substrate. In the adequate limit our approach is equivalent to the phenomenological Kondo exchange model that successfully describe the experiments . We apply our method to study in detail inelastic transport in two systems, stacks of Cobalt Phthalocyanines and a single Mn atom on Cu$_2$N. Our method accounts both, for the large contribution of the inelastic spin exchange events to the conductance and the observed conductance asymmetry.