Magnesium plays a special role in RNA function and folding. Although water is magnesium's most common first-shell ligand, the oxyanions of RNA have significant affinity for magnesium. Here we provide a quantum mechanical description of first-shell RNA-magnesium and DNA-magnesium interactions, demonstrating the unique features that characterize the energetics and geometry of magnesium complexes within large folded RNAs. Our work focuses on bidentate chelation of magnesium by RNA or DNA, where multiple phosphate oxyanions enter the first coordination shell of magnesium. These bidentate RNA clamps of magnesium occur frequently in large RNAs. The results here suggest that magnesium, compared to calcium and sodium, has an enhanced ability to form bidentate clamps with RNA. Bidentate RNA-sodium clamps, in particular, are unstable and spontaneously open. Due to magnesium's size and charge density it binds more intimately than other cations to the oxyanions of RNA, so that magnesium clamps are stabilized not only by electrostatic interactions, but also by charge transfer, polarization, and exchange interactions. These nonelectrostatic components of the binding are quite substantial with the high charge and small interatomic distances within the magnesium complexes, but are less pronounced for calcium due to its larger size, and for sodium due to its smaller charge. Additionally, bidentate RNA clamps of magnesium are more stable than those with DNA. The source of the additional stability of RNA complexes is twofold: there is a slightly attenuated energetic penalty for ring closure in the formation of RNA bidentate chelation complexes and dipole interactions between the 29-hydroxyl group and cations.