Running an agi script using the H template does not work in the context

This is not a good way to add dialplan to an inbound call. I suggest that you use a Custom Destination after the inbound route, or preprocess all calls from a trunk by setting the trunk context to your own dialplan and then going to the from-trunk context.

For all other cases, you want to use the internal dialplan hooks, which you can read about here: Hooking for fun and income