As you guessed, tryptamine alkaloid biosynthesis is generally associated with herbivore deterrence in plants (see e.g. paper 1, paper 2, paper 3), as these compounds can be toxic to animals. I wasn't able to find a reference specifically related to DMT, as it is only one of a family of tryptamine derivatives. For example, the papers just linked to shows that expression of an enzyme catalyzing the creation of the tryptamine precursor of DMT is associated with lower herbivory by insects and nematodes. The second paper also shows that this seems to have little to do with plant morphogenesis via the auxin pathway, which was an alternate hypothesis for herbivory deterrence.
The papers also include a little speculation about the mechanism by which DMT inhibits herbivory on the animal side; it seems to come down again to animal toxicity and behavioral alteration.
So, as with other cases, likely the reason that plants express many secondary metabolic compounds is the same reason that humans use them, namely that they can have strong physiological effects on animals. But I wasn't able to find literature specifically about DMT in plants.
Hope that is helpful.
Update: found an entomology paper that goes into more detail about the effects of a variety of tryptamine derivatives on leaf-cutter ants. The compounds are toxic, but also there are some interesting insights about effects on insect behavior.
Update 2: Looking at question again, realized that I didn't address immune system response.
What's important to note is that plants don't have something homologous to animal immune systems, e.g. antibodies and so forth. They instead substitute various chemical responses, many of which are mediated by signaling factors such as jasmonate and salicylate, that have strong effects and sometimes e.g. kill off pieces of infected tissue (sort of a scorched-earth strategy). This part of plant biology is quite complex and bears further reading.
So in this sense, yeah, sure, tryptamines could be thought of as an immune system, in that their production facilitates resistance to their biotic environment. But that mechanism is completely different from any immunomodulatory effect of DMT or similar compounds in humans.