Magnesium-assisted formation of metal carbides and nitrides from metal oxides