"We have counted around nine of the attackers who have been killed by the security forces and five Somali officials, among them soldiers," Somali police official Abdirahman Mohamed said.
Al-Qaeda-linked Shebab rebels immediately claimed responsibility for the attack.
Militants exploded a huge car bomb at the perimeter of the central Mogadishu complex, and around a dozen suicide attackers breached the Villa Somalia compound.
The UN's special envoy to Somalia said the country's president, Hassan Sheikh Mohamud, had telephoned to say he was unharmed in the attack against the complex, one of the best-defended locations in the war-torn country.
Also Read
"Desperate violent terrorists have staged a failed attack," National Security Minister Abdikarim Hussein Guled told reporters, as the complex was sealed off by Somali troops and soldiers from AMISOM, the African Union force fighting the Shebab.
"Things are back to normal and the security forces are in full control of the situation," he said.
A military spokesman for Shebab told AFP that the group was behind the attack.
The group, who also carried last year's attack against the Westgate shopping mall in the Kenyan capital, once controlled most of southern and central Somalia but withdrew from fixed positions in the ruined coastal capital two years ago.