At least two senior officials and nine attackers are reported dead but the security minister told the BBC the situation was "under control".
President Hassan Sheikh Mohamud has told the UN envoy to Somalia he was not harmed, envoy Nick Kay has tweeted.
The al-Qaeda-linked group al-Shabab has said it carried out the attack.
'Scattered human flesh'
BBC Somalia analyst Mohamed Mohamed says this is the first time that al-Shabab fighters have entered the presidential palace, known as Villa Somalia.
The heavily guarded complex is home to the president, prime minister, speaker of parliament, other ministers and a mosque, which was hit during the attack.
The president was preparing for Friday prayers at the mosque, senior police officer Abdikadir Ahmed told Reuters news agency.
Some of the attackers were wearing suicide vests, police sources have told the BBC.
Another police officer, Hussein Farah, told Reuters there were about 10 assailants, wearing uniforms similar to that of the presidential guards.
"All the Shabab fighters perished, some blew up themselves while others were shot dead. Several government guards also died," he said.
"Now the fighting is over, and scattered on the scene is human flesh and blood."
Security Minister Abdi Karim Hussein told the BBC Somali service that all of the country's leaders were safe.
Senior officials in the prime minister's office and security services are said to have been killed.
Al-Shabab military spokesman Sheikh Abdul Aziz Abu Musab said militants were still in control of some buildings inside the presidential compound.
"Our commandos have attacked the so-called presidential palace in order to kill or arrest those who who are inside," he told the AFP news agency.
Mr Kay said the attack on Villa Somalia had "failed".
"Sadly some lives lost. I condemn strongly this terrorism," he said.
Al-Shabab was driven out of Mogadishu in 2011 but it still controls many smaller towns and rural areas of the country and stages periodic attacks in Mogadishu.
Some 22,000 African Union troops are helping the government battle al-Shabab.