Nanoscale magnetic heat pumps and engines