The president’s intervention came at a time when his White House has been racked by turmoil and turnover. The abrupt departures of his chief of staff, press secretary and communications director, coupled with Mr. Trump’s own criticism of Attorney General Jeff Sessions, have left the president’s team deeply unsettled.

But the president seemed intent on calming the waters, at least momentarily. That does not mean General McMaster’s job is secure in the long run, but White House officials said no one should expect him to leave anytime soon, especially now that his position has been fortified by the arrival of John F. Kelly, a retired four-star Marine general who took over as chief of staff.

Mr. Trump and General McMaster have been something of an odd couple since the president tapped him in February after pushing out Michael T. Flynn, his first national security adviser, for not being forthright about a conversation with Russia’s ambassador. Mr. Trump did not know General McMaster before interviewing him and they have not always had good chemistry, according to White House officials. General McMaster is a serious, somber briefer who prefers an orderly process and does not respond particularly well to Mr. Trump’s looser style.

Some advisers to Mr. Trump had floated a scenario in which Mr. Trump might assign General McMaster to take over as commander in Afghanistan, presumably giving him a fourth star and replacing him with Mike Pompeo, the C.I.A. director. Speculation was fueled by an NBC News report that Mr. Trump last month broached firing Gen. John W. Nicholson Jr., the current commander in Afghanistan.

But White House officials said it was just a thought expressed out loud and the president backed off after Defense Secretary Jim Mattis and Gen. Joseph F. Dunford Jr., chairman of the Joint Chiefs of Staff, defended General Nicholson. The two agreed that the United States is losing the low-grade war in Afghanistan but said the fault was the poor strategy they inherited, not the commander in the field.