The first time Donald Trump talked privately about shooting missiles into Mexico to take out drug labs, as far as his former aides can recall, was in early 2020.

And the first time those comments became public was when his second defense secretary, Mark T. Esper, wrote in his memoir that Mr. Trump had raised it with him and asked if the United States could make it look as if some other country was responsible. Mr. Esper portrayed the idea as ludicrous.

Yet instead of condemning the idea, some Republicans publicly welcomed word that Mr. Trump had wanted to use military force against the drug cartels on Mexican soil — and without the consent of Mexico’s government. Mr. Trump’s notion of a military intervention south of the border has swiftly evolved from an Oval Office fantasy to something approaching Republican Party doctrine.

On the presidential campaign trail and on the G.O.P. debate stage in California last week, nearly every Republican candidate has been advocating versions of a plan to send U.S. Special Operations troops into Mexican territory to kill or capture drug cartel members and destroy their labs and distribution centers.

On Capitol Hill, Republican lawmakers have drafted a broad authorization for the use of military force against cartels — echoing the war powers Congress gave former President George W. Bush before the invasions of Afghanistan and Iraq. They have also pushed for designating Mexican cartels as foreign terrorist organizations — a related idea Mr. Trump flirted with as president but backed off after Mexico hotly objected. Now, if Mr. Trump returns to the White House in 2025, he has vowed to push for the designations and to deploy Special Operations troops and naval forces to, as he put it, declare war on the cartels.

The Republican Party’s attraction to seeking a military solution to the drug problem is a reminder that the G.O.P. — despite its populist shift toward anti-interventionism in the Trump years and the growth of a faction that opposes arming Ukraine against Russia’s invasion — still reaches for armed force to address some complex and intractable problems. Mr. Trump himself has been something of a walking contradiction when it comes to the use of force abroad, alternately wanting to pull back U.S. involvement overseas and threatening to drop bombs on enemies such as Iran.

The plans have angered officials in Mexico. Its president, Andrés Manuel López Obrador, has denounced the proposals as outrageous and unacceptable. It has been more than a century since the United States sent military personnel into Mexico without the Mexican government’s assent.

Mexico has a bitter history with American interference: Much of the southwestern United States was part of Mexico before the United States took it by force in the middle of the 19th century. To this day, Mexico generally does not allow U.S. agents with guns to carry out operations on its soil, in contrast to other Latin American countries that have agreed to joint operations with the Drug Enforcement Administration and invited the American government to help train, equip and assist their own security forces.

Analysts have also warned about the potential for military action to cause significant economic damage. The plans could rupture the United States’ relationship with Mexico, its largest trading partner, and curtail other types of cooperation, including the arrest and extradition of criminals and Mexico’s efforts to deter migrants from trying to cross illegally into the United States. Some Republicans view the threat of sending the military into Mexico as a negotiating tool to force Mexican officials to get aggressive with the cartels.

Generally, international law forbids a country from using military force on the sovereign soil of another nation without its consent, except with the permission of the United Nations Security Council or in cases of self-defense. But the United States has taken the position that it can lawfully use force unilaterally on another nation’s territory if its government is unable or unwilling to suppress a nonstate threat emanating from it, such as a threat from a terrorist group.

Republicans have described the Mexican criminal drug-trafficking networks as a national security threat, with some calling fentanyl a weapon of mass destruction.

Americans spend many billions of dollars a year on cocaine, heroin and other illegal drugs. For decades, the black market created by that demand has been heavily supplied by criminal smuggling operations across the 2,000-mile border with Mexico. But the rise of fentanyl — a powerful and fast-acting synthetic opioid that can be made cheaply from chemicals — has created a crisis. Fentanyl has been linked to more than two-thirds of the nearly 110,000 American overdose deaths last year, and lawmakers from both parties have been desperately searching for solutions.

Frustration has also mounted with the Mexican government, whose president has advocated a “hugs not bullets” policy to deal with drug crime, after crackdowns on cartel leaders by previous administrations led to widespread violence. The cartels, which resemble high-tech paramilitary organizations, have seized control of large areas in Mexico and have corrupted many officials in Mexico’s government and law enforcement ranks.

The Biden administration — like previous administrations of both parties — has sought to partner with Mexico to stem the flow of drugs and has explicitly ruled out military action.

Chris Landau, who was Mr. Trump’s ambassador to Mexico from 2019 to 2021, said the idea of using military force in a bordering country was a bad idea that would only make things worse. He warned it could create a new “quagmire,” invoking the aftermath of military interventions in Iraq and Afghanistan.

“I understand the frustration,” Mr. Landau added. “I just think that a ‘shootout at the O.K. Corral’ model is not going to solve it and will cause a lot more problems.”

The story of how the idea of sending military force into Mexico went from Mr. Trump’s Oval Office to the center of the Republican policy conversation is complex and much more than a simple tale of lawmakers copying Mr. Trump.

Mr. Trump’s proposal to shoot missiles at Mexican drug labs was not something he concocted out of thin air. It came up during a meeting and was affirmed by a man in uniform.

That man in uniform was not in the military chain of command, however: He was a medical officer and an unlikely person to be advising the president of the United States on military operations anywhere.

By late 2019 and early 2020, as the fentanyl crisis was intensifying, large-scale meetings in the Oval Office addressed how to handle the problem. Some participants felt the meetings were of little use because officials tended to perform for Mr. Trump, and he would perform for them.

When the idea of military intervention was brought up at one such meeting, Mr. Trump turned to Brett Giroir, who was there in his role as the U.S. assistant secretary for health. Mr. Giroir was also a four-star admiral in the Commissioned Corps of the U.S. Public Health Service, and he was wearing his dress uniform. His main point was that the United States was unable to combat the crisis with treatment alone, according to a person briefed on his comments.

It was clear from the way Mr. Trump singled out Mr. Giroir that he had mistakenly thought he was in the military because of his dress uniform, according to two participants in the meeting. Mr. Giroir, in his response, suggested putting “lead to target,” the two participants recalled. Mr. Trump did not betray what he thought about the idea, and White House officials, troubled by the moment, considered asking Mr. Giroir not to wear his dress uniform to the Oval Office again.

Mr. Giroir, in a statement, did not discuss the substance of the meeting, but said that no one had suggested that military action alone would solve the fentanyl crisis. He also insisted that Mr. Trump had not mistaken him for a military officer.

“He knew exactly who I was, that I was in the Public Health Service, and I was the opioids lead under the Secretary,” Mr. Giroir said. “We had multiple meetings before that.”

Jason Miller, a senior adviser on Mr. Trump’s 2024 campaign, declined to address the Oval Office meeting or the discussion of sending missiles into Mexico.

During that same time period in late 2019, Attorney General William P. Barr had proposed to Mr. Trump the idea of using force inside Mexico, but he envisioned it as a policy they would pursue in a second term if Mr. Trump won the 2020 election. He thought the threat of unilateral action on the part of the United States would give the administration leverage to press the Mexicans to do more on their end to suppress the cartels.

Mr. Barr and Mr. Trump had a number of conversations about the issue. Mr. Barr mentioned a range of options for aggressive action, according to a person familiar with the discussions. But Mr. Barr was not advocating missiles, concerned that the wrong target might get taken out using such ordinance, the person said.

At least twice during 2020, Mr. Trump privately asked his defense secretary, Mr. Esper, about the possibility of sending “Patriot missiles” into Mexico to destroy the drug labs, and whether they could blame another country for it. Patriot missiles are not the kind that would be used — they are surface-to-air weapons — but Mr. Trump had a habit of calling all missiles “Patriot missiles,” according to two former senior administration officials. During one of the 2020 discussions, Mr. Trump made the comment quietly to Mr. Esper as they stood near the Resolute Desk, within ear shot of another cabinet official. Mr. Esper, stunned, pushed back on the idea.

After leaving office, Mr. Trump didn’t stop talking about attacking the drug cartels. Instead, he turned the idea into an official policy proposal for his 2024 campaign for president.

In January, Mr. Trump released a policy video titled “President Donald J. Trump Declares War on Cartels,” in which he explicitly endorsed the idea of treating Mexican drug cartels like the Islamic State in Iraq and Syria — rather than treating them as transnational criminal organizations to be addressed using law enforcement tools.

Mr. Trump promised to “deploy all necessary military assets, including the U.S. Navy” to impose a full naval embargo on the cartels and to “designate the major cartels as Foreign Terrorist Organizations.”

And he pledged to order the Pentagon “to make appropriate use of special forces, cyber warfare and other overt and covert actions to inflict maximum damage on cartel leadership, infrastructure and operations.”

As a matter of international law, a crucial question is whether the United States would use military force inside Mexico only with the consent of its government or whether it would do so unilaterally without consent. Mr. Trump downplayed the prospect of war with Mexico in a recent interview with Megyn Kelly, the podcast host and former Fox News star.

But in a sign of how politically potent the prospect of sending troops into Mexico has become for Republicans, the campaign of his chief rival, Gov. Ron DeSantis of Florida, highlighted Mr. Trump’s comments to Ms. Kelly and emphasized that Mr. DeSantis has promised to take aggressive military action against the cartels.

Vivek Ramaswamy has promised to “use our military to annihilate the Mexican drug cartels.” Senator Tim Scott of South Carolina has released a campaign ad vowing to “unleash” the U.S. military against the cartels. And former Gov. Nikki Haley of South Carolina has said that when it comes to drug cartels, “you tell the Mexican president, either you do it or we do it.”

Mr. Miller, the Trump adviser, said that Mr. Trump had announced a “detailed plan to eradicate the drug cartels and stop the flow of drugs into our country in the first week of January, and it’s good to see so many others now following his lead.”

The idea has taken on a life of its own on Capitol Hill.

More than 20 House Republicans have signed on to co-sponsor legislation proposed by Representative Dan Crenshaw of Texas to enact a broad authorization for the use of military force against nine named cartels. It would also authorize force against any other foreign organization that the president determines meets certain criteria, including organizations related to fentanyl trafficking.

The proposed authorization for a war would end after five years unless Congress enacted a new bill to extend it. But its otherwise loose nature resembles the broad war authorizations Congress enacted after the 2001 terrorist attacks and ahead of the 2003 Iraq War, both of which escalated into entanglements beyond what lawmakers originally envisioned.

Senator Lindsey Graham, a South Carolina Republican who is a close ally of Mr. Trump, said he thought a president could bomb fentanyl labs and distribution centers on his own constitutional authority as commander in chief, without congressional authorization. But he also argued that if Mr. Trump became president again, the mere threat that he might do something like that could induce the Mexican government to take more aggressive actions.

“As these problems go unmanaged and get bigger in scope, the solutions become more draconian,” he said. “And the one thing about Trump, I think if he does get a second term, I think you’ll see more cooperation by Mexico. I don’t think we’ll ever have to get to bombing labs — Mexico will adjust their policies based on Trump.”

The Republican rhetoric about attacking drug cartels inside Mexico is ricocheting around the halls of its government. The country’s leftist president, Andrés Manuel López Obrador, has responded furiously and taken the extraordinary step for a world leader of attacking the Republican Party.

“This initiative of the Republicans, besides being irresponsible, is an offense to the people of Mexico, a lack of respect to our independence, to our sovereignty,” Mr. López Obrador told reporters in March. “If they do not change their attitude and think that they are going to use Mexico for their propaganda, their electoral and political purposes, we are going to call for not voting for this party, because it is interventionist, inhuman, hypocritical and corrupt.”

From a Mexican perspective, it is the United States that is fueling the cartel violence — not only because American demand creates the market for the drug trade, but also because the United States makes it so easy to buy the firearms that end up in Mexico. Those firearms fuel gun violence in Mexico despite its tough gun-control laws.

Roberto Velasco Álvarez, the top North American official in Mexico’s Foreign Affairs Ministry, specifically invoked the gun comparison as he called out Mr. Ramaswamy for promising U.S. military action inside Mexico.

“If Mr. Ramaswamy is so concerned about what’s going on in Mexico, well, the best way he could help us is to take away the guns that are literally being sold to Mexican cartels,” he said in an interview.

As Mexico heads to a historic presidential election next year, when voters are expected to choose between two leading candidates who are women, whoever gets elected will most likely need to handle the tensions created by the Republican Party.

“Rather than threats, we should work in a smart way,” said Xóchitl Gálvez, a Mexican senator who has been chosen as the opposition’s candidate and has openly rejected Mr. López Obrador’s security strategy, adding that “the hugs have been for the criminals and the bullets for the Mexican citizens.”

But Ms. Gálvez also criticized the Republican proposals to invade Mexico and called for shared and responsible cooperation. “We can’t keep blaming each other,” she said.

Nicholas Nehamas contributed reporting. Kitty Bennett contributed research.