Politicians were meeting inside to vote on the appointment of a new defence minister.
Afghan security forces managed to repel the attack, killing all seven gunmen and ensuring no MPs were harmed.
The assault came as the Taleban captured two districts in as many days in the country’s north, displaying its ability to operate on multiple fronts.
An interior ministry spokesman said the attack began with a car bomb explosion near the entrance to parliament. Gunmen then attempted to storm the compound but were pushed back by security forces and eventually corralled into a nearby building that was under construction.
He added that all seven attackers were killed by police. The spokesman said: “It is over now.”
A health ministry spokesman said 31 civilians were wounded in the parliament attack, including two women and two children.
MP Sidiqa Mubarez said the building was rocked by the large explosion and some people were wounded by flying glass.
She said the explosion happened shortly after Masoom Stanekzai had arrived to be confirmed as defence minister, a post that has been vacant for nine months. The vote was delayed.
The Taleban claimed responsibility for the attack.
An eyewitness to part of the assault heard heavy gunfire outside parliament and saw black smoke billowing from the entrance as ambulances raced to the scene. They later heard sporadic shooting from the building where the militants were said to be holed up.
Just down the street, hundreds of children were evacuated from a school. Parents could be seen racing toward the building, shouting out the names of their children.
Afghan president Ashraf Ghani strongly condemned the assault. “Targeting innocent people in the holy month of Ramadan is a clear act of hostility against the religion of Islam,” his office said, adding that the perpetrators “are criminals who are bound by no creed or religion”.
The attack on parliament came hours after the Taleban seized a second district in the northern Kunduz province, which has borne the brunt of its annual warm-weather offensive.
Mohammad Yusuf Ayubi, head of the provincial council, said the insurgents attacked the district of Dashti Archi from four sides and took full control of the area yesterday morning.
He said local forces suffered some casualties, adding that about 150,000 residents of the district were trapped by the fighting.