Consulates and embassies do engage in spying. Diplomats may, or may not, be privy to information damaging to their host country. If you are introduced to someone who is a military attache, you're likely meeting a spook of some sort. It goes along with the territory of having diplomatic relations.
Immunity goes back centuries to the idea of royal hostages. It used to be that treaties were backed with royal blood. If King Gloob made a peace treaty with King Adamatum, they would send one of their younger sons or daughters as a hostage to the foreign court where they would live well, but not freely. Of course, if one side broke the peace than the other would be free to kill the hostage. While this worked well in theory, in practice the hostage would frequently be a spy to the court where he or she was being held hostage. Upon freedom, they would return home to report or, if still a hostage, report to visiting family.
Immunity is essentially an extension of the autonomous status afforded an embassy or consulate. Embassies are foreign soil. They are subject to the laws of the country to which the embassy belongs. When you step into an embassy, you're in their territory and subject to their laws. Break them and the staff can arrest you and toss you in the basement. Embassies don't usually do that. It looks bad. You're more likely to be tossed out. For diplomacy to work, secret communications between an embassy and home have to be established. Electronics, diplomatic pouches which are (legally) immune to seizure or inspection, and people are the best ways to maintain this communication. All have to be respected by the host country or else diplomacy ceases to function, diplomats are sent home, and embassies closed. That's why ambassadors and their staff have peculiar immunity to laws of their host countries. As representatives of soverign nations, they have the rights of their nation extended to them.