Somali troops have retaken the presidential palace in the capital Mogadishu after al-Shabab fighters forced their way in and exchanged heavy gunfire with soldiers and guards.
Al Jazeera's correspondent said loud explosions and gunfire could be heard as troops tried to repel the intruders on Tuesday evening.
After more than two hours of fighting, Somalia's presidency said on Twitter that "the shameful attack" had been foiled by Somalia's armed forces fighting alongside African Union peacekeepers.
Al-Shabab claimed responsibility for the attack.
Somali President Hassan Sheikh Mohamud was not inside the palace at the time of the attack, but the prime minister and the speaker of parliament were, said Captain Mohamed Hussein, a senior police official.
The presidency said President Mohamud and Prime Minister Abdiweli Sheikh Ahmed were safe.
Tuesday's attack started when a car bomb exploded outside the presidential compound. Gunmen then entered the palace, police officer Mohamed Abdi told the AP news agency.
Police said the fighters, who were armed with grenades, split up into groups once inside and tried to take control of different buildings in the compound.
In a statement Jen Psaki, spokesperson for the US State Department, said: "Incidents such as this further demonstrate that insecurity in Mogadishu persists, including very real threats from al-Shabab.
"This is why we continue to support the efforts of the Somali Forces and the African Union to expand security and stability ... These forces stopped today's attackers and prevented further harm."
Target for attacks
The presidential compound, which also houses several government offices, has been the subject of many attacks by al-Qaeda-linked fighters over the years.
It is considered one of the safest places in Mogadishu because of the tight security presence.
The presidency said that the compound had since been secured, but gave no details about any casualties or what happened to the intruders.
Hussein, the police official, said he counted at least nine bodies.
Some of members of the armed group involved in the attack were dressed as government troops, confusing guards who let them in, said Yusuf Nor, a Somali military official at the scene of the attack.
Amid the confusion, he said, some soldiers fired at their comrades.
Al-Shabab has vowed to step up attacks during the Muslim fasting month of Ramadan.
The attack was the second assault on the presidential palace this year, and marked the first time al-Shabab fighters have been able to breach the compound and take offensive positions inside.