Biermeier et al. use live imaging in zebrafish to show that microglia alternate between distinct morphological states that support brain surveillance and phagocytosis. By optogenetically controlling cytoskeletal contractility, they demonstrate programmable, reversible control of microglial behavior in the living brain.