8. Given the function $f(x)=1-\frac{1}{2} \cos 2 x+a \sin \frac{x}{2} \cos \frac{x}{2}(a \in \mathbf{R})$ has a maximum value of 3, $a=$ $\qquad$
8. $a=3$ or $a=-3$.
$f(x)=1-\frac{1}{2}\left[1-2 \sin ^{2} x\right]+\frac{a}{2} \sin x=\sin ^{2} x+\frac{a}{2} \sin x+\frac{1}{2}$, let $\sin x=t$, then $t \in[-1$, 1], $f(x)=t^{2}+\frac{a}{2} t+\frac{1}{2}=\left[t+\frac{a}{4}\right]^{2}+\frac{1}{2}-\frac{a^{2}}{16}$.
(1) When $-\frac{a}{4} \leqslant 0$ i.e., $a \geqslant 0$, $t=1$ has the maximum value of $\frac{a}{2}+\frac{3}{2}=3, a=3$ satisfies the requirement.
(2) When $-\frac{a}{4} \geqslant 0$ i.e., $a \leqslant 0$, $t=-1$ has the maximum value of $-\frac{a}{2}+\frac{3}{2}=3, a=-3$ satisfies the requirement. Therefore, $a=3$ or $a=-3$.