The neural processing and experience of pain are influenced by both expectations and attention. For example, the amplitude of event-related pain responses is enhanced by both novel and unexpected pain, and by moving the focus of attention towards a painful stimulus. Under predictive coding, this congruence can be explained by appeal to a precision-weighting mechanism, which mediates bottom-up and top-down attentional processes by modulating the influence of feedforward and feedback signals throughout the cortical hierarchy. The influence of expectation and attention on pain processing can be mapped onto changes in effective connectivity between or within specific neuronal populations, using a canonical microcircuit (CMC) model of hierarchical processing. We thus implemented a CMC within dynamic causal modelling for magnetoencephalography in human subjects, to investigate how expectation violation and attention to pain modulate intrinsic (within-source) and extrinsic (between-source) connectivity in the somatosensory hierarchy. This enabled us to establish whether both expectancy and attentional processes are mediated by a similar precision-encoding mechanism within a network of somatosensory, frontal and parietal sources. We found that both unexpected and attended pain modulated the gain of superficial pyramidal cells in primary and secondary somatosensory cortex. This modulation occurred in the context of increased lateralized recurrent connectivity between somatosensory and fronto-parietal sources, driven by unexpected painful occurrences. Finally, the strength of effective connectivity parameters in S1, S2 and IFG predicted individual differences in subjective pain modulation ratings. Our findings suggest that neuromodulatory gain control in the somatosensory hierarchy underlies the influence of both expectation violation and attention on cortical processing and pain perception.