Narrowband x-and gamma-ray sources based on the inverse Compton scattering of laser pulses suffer from a limitation of the allowed laser intensity due to the onset of nonlinear effects that increase their bandwidth. It has been suggested that laser pulses with a suitable frequency modulation could compensate this ponderomotive broadening and reduce the bandwidth of the spectral lines, which would allow to operate narrowband Compton sources in the high-intensity regime. In this paper we, therefore, present the theory of nonlinear Compton scattering in a frequency modulated intense laser pulse. We systematically derive the optimal frequency modulation of the laser pulse from the scattering matrix element of nonlinear Compton scattering, taking into account the electron spin and recoil. We show that, for some particular scattering angle, an optimized frequency modulation completely cancels the ponderomotive broadening for all harmonics of the backscattered light. We also explore how sensitive this compensation depends on the electron beam energy spread and emittance, as well as the laser focusing.