The composition of the neutral gas comas of most comets is dominated by H2O, CO and CO2, typically comprising as much as 95 per cent of the total gas density. In addition, cometary comas have been found to contain a rich array of other molecules, including sulfuric compounds and complex hydrocarbons. Molecular oxygen (O2), however, despite its detection on other icy bodies such as the moons of Jupiter and Saturn, has remained undetected in cometary comas. Here we report in situ measurement of O2 in the coma of comet 67P/Churyumov-Gerasimenko, with local abundances ranging from one per cent to ten per cent relative to H2O and with a mean value of 3.80 ± 0.85 per cent. Our observations indicate that the O2/H2O ratio is isotropic in the coma and does not change systematically with heliocentric distance. This suggests that primordial O2 was incorporated into the nucleus during the comet's formation, which is unexpected given the low upper limits from remote sensing observations. Current Solar System formation models do not predict conditions that would allow this to occur.