UN sources said those killed included one foreign staff member, one local worker, two South African contractors and two Somali security guards.
South Africa’s state-owned military equipment manufacturer Denel confirmed that two of its South African employees had been killed alongside a Somali employee.
The nationality of the other foreigner 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 Shabaab wrote on Twitter.
The UN Assistance Mission in Somalia (UNSOM) said the compound housed UN humanitarian agencies. UN staff elsewhere in the city were temporarily pulled back to the secure airport zone, it added.
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.
Security warnings of an attack had been in place for weeks, and UN staff regularly practise sheltering in a secure bunker inside the central Mogadishu compound.
Somalia’s capital has been hit by a series of attacks including suicide and car bombings, mortar attacks and shootings, although in recent weeks the city has been relatively calm.
Islamist Shabaab militants used to control most of the seaside capital until they abandoned fixed positions in August 2011.
Their last major attack was in April, when a nine-man suicide commando unit blasted its way into Mogadishu’s main court complex, killing 34 people. The attack on the UN compound used similar tactics.
The 17,000-strong AU force, fighting alongside Somali government troops, has forced the Shabaab from a series of key towns.
While riven by infighting and hunted by US drones, Shabaab extremists remain powerful in rural areas as well as reportedly having infiltrated the security forces.