WASHINGTON — Not long after Senator John McCain learned last summer that he had terminal brain cancer, he began convening meetings every Friday in his Capitol Hill office with a group of trusted aides. The subject was his funeral.

He obsessed over the music, selecting the Irish ballad “Danny Boy” and several patriotic hymns. He choreographed the movement of his coffin from Arizona, his home state, to Washington. And in April, when he knew the end was coming, he began reaching out to Republicans, Democrats and even a Russian dissident with requests that they deliver eulogies and serve as pallbearers.

By the time he died on Saturday, Mr. McCain had carefully stage-managed a four-day celebration of his life — but what was also an unmistakable rebuke to President Trump and his agenda. For years, Mr. Trump had used Twitter and the presidential bully pulpit to mock and condemn the senator. In death, Mr. McCain found a way to have the last word, even quietly making it clear through friends that Mr. Trump was not welcome at the services.

“I think it’s fair to say that they have a very different view of this country and what this country means, here and abroad,” said Mark Salter, the senator’s longtime friend and co-author who sat with Mr. McCain — often with a lump in his throat — during the many discussions about his looming death. “His overall message was: ‘It doesn’t have to be this shitty.’”