Three foreigners in the UN compound died in the attack, along with at least two Somali security guards and three civilians in the surrounding streets, officials said.
Somali Prime Minister Abdi Farah Shirdon condemned the brazen daylight raid as a "senseless and despicable attack on innocent UN civilians".
Shebab fighters, who boasted about the killings, used both a car bomb and suicide attackers to blast their way into the fortified base in central Mogadishu near the airport.
"Our commandos attacked the UN compound... We set off an explosion and entered the compound," a senior Shebab official told AFP, saying they entered to attack "the infidel forces."
More From This Section
Somali and African Union troops later moved into the complex -- despite the Islamists battling back with heavy gunfire -- to end the hour and an half seige.
"The situation is under control... Somali soldiers along with African Union forces stormed the compound and killed the attackers," said Somali police official Abdulahi Osman.
UN sources said one staff member and two contractors were killed along with at least two Somali security guards, although the nationalities of the foreigners could not be immediately confirmed.
An AFP reporter saw several bloodied bodies carried away on makeshift stretchers.
"Some of the 'white kuffar'(unbelievers) who tried to engage the mujahedeen in combat inside the offices were killed and thrown out into the compound," the Shebab wrote on Twitter.
The UN Assistance Mission in Somalia (UNSOM) said the compound -- home to UN humanitarian agencies -- had come under " complex attack".
An AFP reporter near the scene of the attack reported heavy gunfire after a series of inital explosions, as the fighters battled with security forces.
The compound -- including both residential and office areas -- is a short distance from the airport zone, the base of the African Union troops, but is guarded by its own security officers.