"Stuart is, in my opinion, the best manager I have worked with since coming to the club," said Northampton Chairman David Cardoza.
"Continuity in football is all important, if anybody can get us into the Championship, Stuart can."
Gray arrived at Sixfields 16 months ago when the club were hovering just above the League One relegation zone.
He steered Northampton to safety in his first season and this campaign his team has just missed out on the Play-Offs.
"We have a very good personal relationship and I have the up most faith in his coaching and managerial capabilities," said Cardoza.
"When Stuart arrived we looked like a team that could easily be relegated, 15 months later we were being tipped for the play offs.
"My father and I wanted Stuart in place for at least the next 2 years, and with potential positive news on the horizon regarding the ground redevelopment, we wanted him with us to take us on to the next level."