The dismissal came just weeks before Odebrecht, the Brazilian construction giant, was set to reveal critical evidence against powerful former Peruvian officials.

Executives at the company have acknowledged that it distributed millions in bribes across Latin America, including $29 million in Peru, to obtain lucrative government contracts.

The prosecutor’s office is investigating all of the Peruvian presidents who governed from 2001 to 2018 over accusations of corruption and money laundering.

Mr. Chavarry’s action set off demonstrations by hundreds of people in four cities, including Lima, the capital. Protesters shouted phrases like “Out with Chavarry” as they waved Peruvian flags.

The attorney general called a news conference to announce his decision, but he then took no questions. He said the dismissal was necessary to nullify the appointment of the prosecutor heading the team of investigators.