The UK soldier, of 28 Engineer Regiment, attached to 21 Engineer Regiment, died at Patrol Base Hazrat, in Helmand's Nahr-e Saraj district.
The gunman fired at Afghan troops and then British soldiers before being killed. Afghan officials dispute Taliban claims he was acting for them.
The male soldier's next of kin have been informed of Monday's attack.
Prime Minister David Cameron's spokesman described it as a "tragic incident", adding: "The PM's thoughts are very much with the family and friends of the soldier who was killed."
The spokesman said the military had stepped up counter-intelligence efforts and the vetting and screening of new Afghan National Army recruits.
The attack comes as President Hamid Karzai is due in the US for a visit seen as key to the future of the American presence in Afghanistan.
Spokesman for Task Force Helmand, Major Laurence Roche, said: "This is an extremely sad day for the Corps of Royal Engineers and everyone serving with Task Force Helmand. Our thoughts are with the soldier's family and friends at this time."