Energy deposition by active galactic nuclei jets into the ambient medium can affect galaxy formation and evolution, the cooling of gas flows at the centres of galaxy clusters, and the growth of the supermassive black holes. However, the processes that couple jet power to the ambient medium and determine jet morphology are poorly understood. For instance, there is no agreement on the cause of the well-known Fanaroff-Riley (FR) morphological dichotomy of jets, with FRI jets being shorter and less stable than FRII jets. We carry out global 3D magnetohydrodynamic simulations of relativistic jets propagating through the ambient medium. We show that the flat density profiles of galactic cores slow down and collimate the jets, making them susceptible to the 3D magnetic kink instability. We obtain a critical power, which depends on the galaxy core mass and radius, below which jets become kink-unstable within the core, stall, and inflate cavities filled with relativistically-hot plasma. Jets above the critical power stably escape the core and form powerful backflows. Thus, the kink instability controls the jet morphology and can lead to the FR dichotomy. The model-predicted dependence of the critical power on the galaxy optical luminosity agrees well with observations.