This punishment is not for those who spy for you, but it is for those who spy against you. It is a reciprocal system, a fight, and the spying in Islam is permitted during a war or a battle, during a national struggle. Muhammad Mustafa Sallallahu Alaihi Wasallam himself employed it. And in the battles, both the sections, both the parties tried to kill each other.
And whoever succeeds, kills. So this is why if some spy is caught from the enemy camp, he should be treated severely. If your spy is caught by the enemy tent, he is also treated severely. So this is a time of war, a life or death of nation, and the rules applicable there are quite different from the normal times of peace.