It is to protect diplomacy. So that diplomats can do their work without worry of being harrassed or targeted if the host country disagrees with the diplomats country.
Such as a US diplomat in Iran/Russia/China/etc could easily be targeted for just doing their job. The host country can expell the diplomat if they do not like their behavior.