Advances in microbiome science require a better understanding of how beneficial microbes adapt to hosts. We tested whether hosts select for more-cooperative microbial strains with a year-long evolution experiment and a cross-inoculation experiment designed to explore how nitrogen-fixing bacteria (rhizobia) adapt to legumes. We paired the bacterium Ensifer meliloti with one of five Medicago truncatula genotypes that vary in how strongly they "choose" bacterial symbionts. Independent of host choice, E. meliloti rapidly adapted to its local host genotype, and derived microbes were more beneficial when they shared evolutionary history with their host. This local adaptation was mostly limited to the symbiosis plasmids, with mutations in putative signaling genes. Thus, cooperation depends on the match between partner genotypes and increases as bacteria adapt to their local host.