Interactions between the prefrontal cortex (PFC) and mediodorsal thalamus are critical for cognitive flexibility, yet the underlying computations are unknown. To investigate frontothalamic substrates of cognitive flexibility, we developed a behavioral task in which mice switched between different sets of learned cues that guided attention toward either visual or auditory targets. We found that PFC responses reflected both the individual cues and their meaning as task rules, indicating a hierarchical cue-to-rule transformation. Conversely, mediodorsal thalamus responses reflected the statistical regularity of cue presentation and were required for switching between such experimentally specified cueing contexts. A subset of these thalamic responses sustained context-relevant PFC representations, while another suppressed the context-irrelevant ones. Through modeling and experimental validation, we find that thalamic-mediated suppression may not only reduce PFC representational interference but could also preserve unused cortical traces for future use. Overall, our study provides a computational foundation for thalamic engagement in cognitive flexibility.