The Ismaili branch of the Shi’a had pretty much gone into hiding and emigrated westward to escape persecution by the Abbasid Caliphs. They had a network of agents who spread the word about their Mahdi in waiting (Muhammad ibn Ismail ibn Jafar, grandson of the 6th Imam). The agents were called da’wa, a word that starts to be more important with the rise of this branch of Shi’ites to power in North Africa. The chief of these agents ruled their adherents in the name of the hidden Mahdi. Some of the agents were related to the Ismaili line
In 899, a chief da’wa proclaimed that he was the Imam, and more than that, he was the Mahdi, returned. He is known to history as al-Mahdi Billah (or Abd Allah). The Qarmatian branch of the Ismaili movement rejected him, so he fled to Morocco. He began preaching to the Berbers and was imprisoned by the semi-independent Aghlabid Emir of Ifriqiyah. But another da’wa leader raised the Berbers in revolt, and in 909 they overthrew the Emir and released al-Mahdi Billah.
Imam Al-Mahdi Billah became the ruler of western North Africa. He founded a city named al-Mahdiyah on the coast of Tunisia. By 920, the new Emir was living in his capital, although his kingdom at this point was made up of Berber tribes and a lot of hype. But his son al-Qaim inherited power in al-Mahdiyah as Caliph, and the territory kept growing.