Lets call the gun direction a and the direction from the gun to the mouse b. On top of that lets call the gun location A and the world space location of the mouse B. I assume you already have a and A. You can get B with “get hit result under mouse” and b can be calculated with B-A, you also need to normalize this value.
Now with a and b you can calculate the dot product, that is a value between -1 and 1. Add 1 to the value of the dot product and multiply by 0.5. Now subtract this value from 1. This value is 0 if a and b are the same direction and 1 if they are the opposite direction. Multiply the value by 180.
If you need to know does the angle rotate up or down you need to do this next step. You have another direction c, that is perpendicular to the gun direction (gun forward vector). c is the up vector of the gun. You get the dot product for b and c, if this value is less than 0 you multiply the value of the previous step by -1, if it’s 0 or greater then you multiply by 1.
Assuming your function works as expected you can use the following vectors as the inputs: one that points to the mouse position from the player and one that points to the position that is at the same location as the mouse position, but with the z being swapped for the character position z.