The first historical document about the existence of an established settlement in Madrid dates from the Muslim age. At the second half of the 9th century, Cordobese Emir Muhammad I built a fortress on a headland near the river Manzanares, as one of the many fortresses he ordered to be built on the border between Al-Andalus and the kingdoms of León and Castile, with the objective of protecting Toledo from the Christian invasions and also as a starting point for Muslim offensives. After the disintegration of the Caliphate of Córdoba in the early 11th century, Madrid was integrated in the Taifa of Toledo.
In the context of the wider campaign for the conquest of the taifa of Toledo initiated in 1079, Madrid was seized in 1083 by Alfonso VI of León and Castile, who sought to use the town as an offensive outpost against the city of Toledo, in turn conquered in 1085.
Following the conquest, Christians occupied the center of the city, while Muslims and Jews were displaced to the suburbs. Madrid, located near Alcalá (under Muslim control until 1118), remained a borderland for a while, suffering a number of razzias during the Almoravid period and its walls were destroyed in 1110. The city was confirmed as villa de realengo (linked to the Crown) in 1123, during the reign of Alfonso VII.
The 1123 Charter of Otorgamiento established the first explicit limits between Madrid and Segovia, namely the Puerto de El Berrueco and the Puerto de Lozoya. Since 1188, Madrid won the right to be a city with representation in the courts of Castile.
In 1202, Alfonso VIII gave Madrid its first charter to regulate the municipal council, which was expanded in 1222 by Ferdinand III. The government system of the town was changed to a regimiento of 12 regidores by Alfonso XI on 6 January 1346.
Since the mid-13th century and up to the late 14th century, the concejo of Madrid vied for the control of the Real de Manzanares territory against the concejo of Segovia, a powerful town north of the Sierra de Guadarrama mountain range, characterised by its repopulating prowess and its husbandry-based economy, contrasted by the agricultural and less competent in repopulation town of Madrid.
After the decline of Sepúlveda, another concejo north of the mountain range, Segovia had become a major actor south of the Guadarrama mountains, expanding across the Lozoya and Manzanares rivers to the north of Madrid and along the Guadarrama river course to its west.