There are two parts to this, and usually they are done by separate agencies. The first part is to collect information (to "spy") on other countries. The other side is to watch people in the home country who might cause problems. A third activity is to defend against foreign intelligence agencies in the home country. This is called counter-intelligence, and is often done by a separate agency.