The home side dictated play at Stade Rabemananjara and could have won more convincingly, having missed a second-half penalty before the visitors snatched a potentially crucial away goal from a stoppage-time spot-kick.
Faneva Andriatsima converted an early penalty for Madagascar and Carolus Andriamatsinoro doubled the advantage midway through the opening period. Andriatsima missed from 12 yards on the second occasion, and Hamis Kiiza scored from another spot-kick two minutes into additional time.
Uganda host the 31 May return fixture and remain favourites to reach the final qualifying round, where seven group-stage places will be up for grabs; they last played at the Cup of Nations 36 years ago, while their opponents have never competed at the African football showcase.
It took a spectacular outside-the-box shot from John Omollo on 34 minutes to break the deadlock, but there were no further goals and they now face a tougher than expected task in Moroni.
Josimar Machaisse triggered the rout with a goal after 12 minutes, while Edson Sitoe and Apson Manjate also netted during the opening half. The latter struck again after the break and Isac Carvalho completed a big victory for the Mozambicans six minutes from time.
An early John Bocco goal earned Tanzania a 1-0 win over Zimbabwe in Dar es Salaam and captain Anthony Laffor was on target as Liberia edged Lesotho 1-0 in Monrovia. Meanwhile, Botswana held Burundi 0-0 in Bujumbura after having defender Oscar Ncenga sent off ten minutes from time.