Weakly magnetic, millisecond spinning neutron stars attain their very fast rotation through a 1E8-1E9 yr long phase during which they undergo disk-accretion of matter from a low mass companion star. They can be detected as accretion-powered millisecond X-ray pulsars if towards the end of this phase their magnetic field is still strong enough to channel the accreting matter towards the magnetic poles. When mass transfer is much reduced or ceases altogether, pulsed emission generated by particle acceleration in the magnetosphere and powered by the rotation of the neutron star is observed, preferentially in the radio and gamma-ray bands. A few transitional millisecond pulsars that swing between an accretion-powered X-ray pulsar regime and a rotationally-powered radio pulsar regime in response to variations of the mass in-flow rate have been recently identified. Here we report the detection of optical pulsations from a transitional pulsar, the first ever from a millisecond spinning neutron star. The pulsations were observed when the pulsar was surrounded by an accretion disk and originated inside the magnetosphere or within a few hundreds of kilometres from it. Energy arguments rule out reprocessing of accretion-powered X-ray emission and argue against a process related to accretion onto the pulsar polar caps; synchrotron emission of electrons in a rotation-powered pulsar magnetosphere seems more likely.