The nature of the interaction between nucleic acids and divalent ions in solution is complex. It includes long-range electrostatic and short-range nonelectrostatic forces. Water molecules can be in an inner coordination shell that intervenes between the ion and its binding site. This work describes a method for calculating the binding free energy and applies it to a specific Mg-RNA system in the presence of monovalent salt. The approach combines high-level ab initio theory with Poisson-Boltzmann calculations and provides an accurate description of all terms of the binding free energy for magnesium ions located at the RNA surface (including nonelectrostatic interactions). Some alternative macroscopic approaches are also discussed.