Read more:

President Ashraf Ghani said the attack at the 400-bed hospital "trampled all human values".

"In all religions, a hospital is regarded as an immune site and attacking it is attacking the whole of Afghanistan," he said.

The attack began at 09:00 local time (04:30 GMT). One hospital staff member who was able to get out saw an attacker "wearing a white coat holding a Kalashnikov and opening fire on everyone, including the guards, patients and doctors".

One employee wrote on Facebook: "Attackers are inside the hospital. Pray for us."

Change of tactic: Analysis by Inayatulhaq Yasini, BBC Afghan

Image copyrightEPAImage caption
Smoke billowed from the hospital roof during the attack

The hospital attack marks a change in approach by so-called Islamic State fighters in Afghanistan - it's the first time they have engaged directly with security forces in the capital.

Previously they have targeted civilian gatherings, mainly of Shia Muslims, as well as causing carnage at the Supreme Court last month.

But at the hospital they used an approach more commonly associated with the Taliban - blowing the gates open to allow gunmen to enter. This suggests they now have the resources and the military training to expand their attacks.

If that's the case, the security forces could face more such assaults in the coming months.

In the two years since it announced its presence in Afghanistan, IS has mainly engaged with Afghan forces - and more powerful, rival Taliban fighters - in the east, near the Pakistan border. It has failed so far to widen its base in the country - one reason, observers suggest, it may now be mounting more headline-grabbing attacks.

The government claims it has rooted out IS militants from a number of bases in the east - but has yet to dislodge them from mountainous areas they control.

TV pictures showed people hiding from the gunmen on ledges outside windows on upper floors of the building.

More than six hours after the attack began, interior ministry spokesman Sediq Sediqqi tweeted that special forces had ended their operation and all the attackers were dead.

Media playback is unsupported on your device

Media captionDoctor Abdul Qadir said he was shot at in an operating theatre

The IS-affiliated Amaq news agency shared two images via the Telegram messaging app that appeared to show one of the militants taking part in the assault and a number of dead bodies.

Afghanistan's de-facto deputy leader Abdullah Abdullah also condemned the attack on Twitter and vowed to "avenge the blood of our people".

Image copyrightEPAImage caption
Some patients were evacuated and transferred to other hospitals

IS announced it was moving into Afghanistan and Pakistan when it declared its so-called Khorasan Province in 2015 and has since carried out a number of attacks.