The short answer to this question is that Muff Potter's lawyer in his murder trial calls Tom Sawyer to the stand as a witness for the defense.
Tom Sawyer and Huck Finn both know that Muff Potter did not kill the doctor because they were there in the graveyard when the doctor was killed. They know that Injun Joe is the real murderer. But they have been afraid to tell for fear that Injun Joe will kill them.
But Tom's conscience finally gets the better of him and he tells what he knows and gets Muff Potter off.