In 1806, Ibrahim shifted his allegiance back to Iran. One of his grandchildren, Ja'far Qoli Agha, whose succession was meant to be assured by the
Treaty of Kurekchay and who had his own plans for ruling Karabakh, was frightened and angered by this action. On 2 June, Ibrahim Khalil Khan along with some of his relatives and thirty members of his retinue were killed by a group Russian soldiers under the instigation of Ja'far Qoli Agha and the commander of the Russian garrison. Although Ja'far Qoli Agha had hoped to become the new khan for helping the Russians against his grandfather's "betrayal," they ultimately appointed Mehdi Qoli Khan, due to the support he enjoyed amongst the distinguished figures of Karabakh. Mehdi Qoli Khan consented to abide by the Treaty of Kurekchay on September 22, 1806, when the Russian emperor
Alexander I () officially confirmed him as khan. Kotliarevskii, the new commander of the Russian garrison in
Shusha, was forbidden by the Russian commander
Ivan Gudovich to meddle in the internal affairs of the khanate because of his high regard for Mehdi Qoli Khan. Although Mehdi Qoli Khan held the title of khan of Karabakh, he was in reality a figurehead, the real authority being held by the Russians. Following the Iranian victory against the Russians at the
Battle of Sultanabad on 13 February 1812, Mehdi Qoli Khan escaped to Shusha. In June 1812, Mehdi Qoli Khan received a
farman (royal decree) from
Fath-Ali Shah Qajar () asking him to reaffirm his loyalty and work with him to expel the Russians from Karabakh. In addition to forgiving Mehdi Qoli Khan for his earlier transgressions, Fath-Ali Shah would also install him as Karabakh's governor and work with him to bring back the tribes of Karabakh who had sought asylum in
Azerbaijan. Mehdi Qoli Khan, who changed his alliance between Iran and Russia to his greatest advantage like the majority of the khans in the South Caucasus, made the decision to stick by Russia. In an effort to reassure his continuous allegiance to the Russian Empire, he sent Kotliarevskii the
farman. The
Russo-Persian War of 1804–1813 ended with the
Treaty of Gulistan, in which Iran agreed to cede the majority of their holdings in the eastern Caucasus to Russia, including Karabakh. The treaty was signed in
Gulistan, a village in Karabakh. On 21 November 1822, fearing to be punished by the Russians for the initiatives he had made towards the Iranians, Mehdi Qoli Khan escaped to Iran, passing via
Erivan,
Nakhchivan and
Sharur. He was given 6000
tomans of pension and received income from
Gargar province. The Khanate was subsequently abolished and transformed into a province of the
Russian Empire. ==Later life and death ==