The agency has been under fire for spying on Catalan separatists and also failing to discover that Spanish Prime Minister Pedro Sanchez had been hacked.
The head of Spain's intelligence service (CNI) has been sacked amid allegations that the agency hacked the mobile phones of senior politicians.
Paz Esteban was dismissed as director of the CNI over the Pegasus spyware scandal, the Spanish government announced.
The agency was accused of using software from the Israeli NSO group to spy on the mobile phones of pro-independence Catalan leaders.
Fresh revelations then revealed that the phones of Prime Minister Pedro Sánchez and Defence Minister Margarita Robles had separately been hacked by an "external" power in 2021.
Interior Minister Fernando Grande-Marlaska -- the head of Spain’s police and border control agencies -- was also targeted by spyware.
"It is clear there are things that we need to improve, given that [the hacking of government officials] took a year to discover," Robles said after a Cabinet meeting.
"We are going to try to ensure that these attacks don’t happen again, even though there is no way to be completely safe."
The CNI has been under fire ever since it was accused of using Pegasus to hack more than 60 Catalan and Basque separatists between 2017 and 2020.
A report by Citizen Lab found that the regional leaders had been targeted with spyware that governments and security forces can purchase to fight crime and terrorism.
Esteban later acknowledged that the agency hacked the phones of several Catalan separatists, but legally and with judicial authority.
Robles has defended the targeting of Catalan politicians for their involvement in an unconstitutional declaration of independence in 2017.
Spain's government has often had to rely on votes in Parliament from Catalan separatist parties, which have threatened to withdraw their support if the government does not accept responsibility for the hacking.
Esteban, 64, became the first woman to head the intelligence agency in July 2019 and is now expected to be replaced by Esperanza Casteleiro.
Her predecessor had received criticism for failing in 2017 to stop preparations by Catalan separatists to hold the independence referendum.
Esteban's departure is likely to appease Catalan politicians, but NGOs have called for more transparency from Spain's government.
"The Spanish government can’t use the security of the Spanish state as an excuse to cover up possible human rights violations," said Esteban Beltrán, the head of Amnesty International in Spain.
The European Parliament has also opened an investigation into the use of Pegasus in the European Union, including against politicians in Hungary, Poland, and Catalonia.