Poisonous plants, animals, mushrooms: is this always a kind of defense?
Developing anything by the body takes energy so generally only useful products are conserved. If some sort of mutation caused an organism to produce some sort of by-product that also happened to be toxic to its predators, then that organism is more favored to survive. No species ever starts producing something with the intention of toxicity in a predator/consumer of said species.

These xenobiotics that the plant/animal produces then can either be selected for because they're useful in whatever pathway they are a by-product of. Or they can be conserved because then this by-product has a defense use, regardless of whether the pathway its part of is necessary. Or both could happen, it could be doubly selected for.