WASHINGTON — Senior American national security officials, seeking to prevent President Trump from upending a formal policy agreement at last month’s NATO meeting, pushed the military alliance’s ambassadors to complete it before the forum even began.

The work to preserve the North Atlantic Treaty Organization agreement, which is usually subject to intense 11th-hour negotiations, came just weeks after Mr. Trump refused to sign off on a communiqué from the June meeting of the Group of 7 in Canada.

The rushed machinations to get the policy done, as demanded by John R. Bolton, the national security adviser, have not been previously reported. Described by European diplomats and American officials, the efforts are a sign of the lengths to which the president’s top advisers will go to protect a key and longstanding international alliance from Mr. Trump’s unpredictable antipathy.

Allied ambassadors said the American officials’ plan worked — to a degree.

Mr. Trump did almost blow up the two-day meeting in Brussels that began on July 11. He issued a vague threat that the United States could go its own way if allies resisted his demands for additional military spending. After the gathering, he also questioned a pillar of the alliance: that an attack on one NATO country is an attack on all.