Melatonin (MT) is a crucial hormone for biological rhythms that influences sleep-wake cycles. The therapeutic value of MT in neurological disorders highlights the need for precise detection. However, challenges like low concentrations in biological samples and complex matrix interferences persist, necessitating rapid and precise analytical techniques. This study presents the novelty of designing a novel sensor that combines a molecularly imprinted polymer with polytoluidine blue O (PTBO) and multi-walled carbon nanotubes on a glassy carbon electrode for MT detection and the study of the interaction between MT and the proposed sensor using density functional theory (DFT). DFT showed that MT has a high nucleophilic character and low electrophilicity compared to TBO, which is a strong electrophile. This supports electron transfer from MT to TBO/PTBO, as indicated by the electronic chemical potentials and molecular electrostatic potentials. Scanning electron microscopy was used to see the morphology. Electrochemical measurements using differential pulse voltammetry demonstrated enhanced sensitivity and selectivity. Under optimized conditions, the sensor exhibited a linear response ranging from 1 to 1000 µM with a limit of detection and limit of quantification of 0.027 µM and 0.092 µM respectively. The performance of the sensor was evaluated in pharmaceutical tablets and human serum. Validation experiments confirmed the reliability of the sensor, with recovery rates of 97.5 % for serum and 98.0 % for pharmaceutical tablets, alongside low relative standard deviations indicating good precision. Interference studies showed minimal effects from coexisting substances, highlighting the selectivity of the proposed sensor. Comparative analysis with existing sensors showed superior performance.