WASHINGTON — Donald F. McGahn II departed as White House counsel on Wednesday, ending a tumultuous 21-month tenure during which he spearheaded some of President Trump’s most significant political accomplishments, including two appointments to the Supreme Court, but also became a chief witness against him in the special counsel investigation.

Mr. McGahn’s departure was confirmed by two people close to him. Mr. McGahn and the president sat for a farewell chat on Wednesday, one said. Mr. Trump said this week that he would install as Mr. McGahn’s replacement the longtime Washington lawyer Pat Cipollone, calling him “a very fine man, highly respected by a lot of people.”

As White House counsel, Mr. McGahn took on a handful of often-conflicting roles: counselor to the president; protector of top law enforcement officials, including the special counsel, Robert S. Mueller III; and witness in the investigation into whether Mr. Trump obstructed justice. He has told associates that he stopped Mr. Trump from firing Mr. Mueller and from forcing Attorney General Jeff Sessions to retake control of the Russia inquiry after he recused himself from oversight of it.

A longtime fixture in Republican legal circles, Mr. McGahn led White House efforts to slash government regulations and stack the federal courts with conservative judges. He shepherded the nominations of both of Mr. Trump’s Supreme Court choices, Neil M. Gorsuch and Brett M. Kavanaugh.