Somali troops retook the presidential palace in the capital of Mogadishu after militants forced their way in and exchanged heavy gunfire with troops and guards.
The new attack underscored the threat posed by Islamic extremist group al-Shabab in east Africa.
Smoke billowed from inside the heavily-fortified presidential compound, and loud explosions and gunfire could be heard as troops tried to repel the intruders. After more than two hours of fighting, Somalia's presidency said in a Twitter update 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 Capt Mohamed Hussein, a senior police official.
The presidency said both President Mohamud and Prime Minister Abdiweli Sheikh Ahmed were safe.
The presidential compound, which also houses several government offices, has been the subject of many attacks by al Qaida-linked militants 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 has since been secured, but gave no details about any casualties or what happened to the militants.
The attack was the second assault on the presidential palace this year, and it marked the first time militants have been able to breach the compound and take offensive positions inside. The palace is protected by government troops and African Union peacekeepers who helped to drive the al-Shabab militants out of their bases in Mogadishu in 2011.
Tuesday's attack started when a car bomb exploded outside the presidential compound. Gunmen then entered the palace.
Police said the militants, who were armed with grenades, split up into groups once inside and tried to take control of different buildings in the compound.
Al-Shabab, which has links with al Qaida, has vowed to step up attacks during the Muslim holy month of Ramadan.
Al-Shabab militants have previously carried out deadly attacks against politicians, UN staff and government officials. Last year the group attacked an upmarket mall in Nairobi, the capital of neighbouring Kenya, which has sent troops to fight the militants under the African Union banner.
Al-Shabab militants killed four people on Saturday when a car laden with explosives blew up near the parliamentary building in Mogadishu.
Somali Defense Minister Mohamed Sheikh Mohamud told a local radio station in the aftermath of the latest attack that the Horn of Africa nation faces a "complicated" fight against al-Shabab, and urged the public to co-operate with the authorities to defeat the militants.
Somalia has been trying to rebuild following years of political instability and civil strife since 1991, when the dictator Siad Barre was ousted from power.