A 17-year-old boy was caught trying to bring a loaded gun into a Brooklyn high school Friday, cops said.

The weapon set off a metal detector as the teen entered the Frank J. Macchiarola Educational Complex, on Avenue X near Batchelder St. in Sheepshead Bay, around 2:50 p.m., police said.

The suspect, who was entering the school for sports practice, fled after school safety agents discovered the firearm inside his bookbag. He is currently being sought.

NYPD officers who responded to the school recovered a loaded .45-caliber automatic handgun, sources said.