We propose a theoretical framework to calculate capillary stresses in complex mesoporous materials, such as moist sand, nanoporous hydrates, and drying colloidal films. Molecular simulations are mapped onto a phase-field model of the liquid-vapor mixture, whose inhomogeneous stress tensor is integrated over Voronoi polyhedra in order to calculate equal and opposite forces between each pair of neighboring grains. The method is illustrated by simulations of moisture-induced forces in small clusters and random packings of spherical grains using lattice-gas Density Functional Theory. For a nano-granular model of cement hydrates, this approach reproduces the hysteretic water sorption/desorption isotherms and predicts drying shrinkage strain isotherm in good agreement with experiments. We show that capillary stress is an effective mechanism for internal stress relaxation in colloidal random packings, which contributes to the extraordinary durability of cement paste.