In Green's function theory, the total energy of an interacting many-electron system can be expressed in a variational form using the Klein or Luttinger-Ward functionals. Green's function theory also naturally addresses the case where the interacting system is embedded into a bath. The latter can then act as a dynamical (i.e., frequency-dependent) potential, providing a more general framework than that of conventional static external potentials. Notably, the Klein functional includes a term of the form Trωln{G0-1G}, where Trω is the integration in frequency of the trace operator. Here, we show that using a sum-over-poles representation for the Green's functions and the algorithmic-inversion method one can obtain, in full generality, an explicit analytical expression for Trωln{G0-1G}. Further, this allows us (1) to recover an explicit expression for the random phase approximation correlation energy in the framework of the optimized effective potential and (2) to derive a variational expression for the Klein functional valid in the presence of an embedding bath.