The use of nanophotonics to rapidly and precisely reconfigure light beams for the optical stimulation of neurons in vivo has remained elusive. Here we report the design and fabrication of an implantable silicon-based probe that can switch and route multiple optical beams to stimulate identified sets of neurons across cortical layers and simultaneously record the produced spike patterns. Each switch in the device consists of a silicon nitride waveguide structure that can be rapidly (<20 μs) reconfigured by electrically tuning the phase of light. By using an eight-beam probe, we show in anaesthetized mice that small groups of single neurons can be independently stimulated to produce multineuron spike patterns at sub-millisecond precision. We also show that a probe integrating co-fabricated electrical recording sites can simultaneously optically stimulate and electrically measure deep-brain neural activity. The technology is scalable, and it allows for beam focusing and steering and for structured illumination via beam shaping. The high-bandwidth optical-stimulation capacity of the device might facilitate the probing of the spatiotemporal neural codes underlying behaviour.