Iran and its allies have been firing on Saudi Arabia and other Gulf states, and blockading their energy shipments, since the US and Israel attacked it on February 28 in a major escalation of years of regional tumult.
The agreement was intended to strengthen collective deterrence against any act of aggression and stipulates that an armed attack against any of the three would be regarded as an attack on all, they said in a joint statement on Friday.
While the statement did not give specifics on the commitments or obligations each had accepted under what it called the Mecca Joint Defence Agreement, it said the pact was aimed at strengthening their collective security and promoting peace, security and stability in the region and beyond.
A Turkish official said the agreement was defensive in nature, was not directed against any specific actor, was open to other regional countries, and did not abrogate or replace any existing bilateral or multilateral arrangements.
However, the three nations are particularly concerned by the increasingly aggressive military stances of both Israel and revolutionary Shi'ite Iran even as their longtime US ally struggles to contain regional upheaval.
Turkey has NATO's second-largest military.
Saudi Arabia, the strongest Gulf state, is home to Islam's holiest sites and one of the world's top oil exporters, while Pakistan is the only nuclear-armed Muslim country.
Pakistani Prime Minister Shehbaz Sharif, accompanied by powerful army chief Asim Munir, performed the Umrah pilgrimage in Mecca before Turkish President Recep Tayyip Erdogan's arrival.
They met Saudi Crown Prince Mohammed bin Salman, whose country has been repeatedly struck by Iran, as well as by Tehran's Houthi allies in Yemen and Shi'ite militia in Iraq, since the war began on February 28.
The conflict has also upended the security of Riyadh's Gulf allies and shut down most shipping in the Strait of Hormuz, the route for about a fifth of global energy supplies before the war.
The Middle East has been in flames for nearly three years since the October 7, 2023, Hamas attack on Israel, with nearly every country in the region experiencing cross-border attacks or missile or drone fire.
Israel has waged war in Gaza, invaded southern Lebanon and seized territory in Syria as well as launching two air campaigns against Iran. Tehran has attacked US bases and civilian infrastructure in Saudi Arabia, Kuwait, Bahrain, Qatar, the United Arab Emirates, Oman, Jordan and Israel.
While Turkey and Pakistan, on the borders of the Middle East, have avoided significant direct attacks, both are anxious to calm conflicts that threaten their own security and economic health.
For Saudi Arabia, the consequences of three years of Middle East conflicts have been more severe - imperilling its oil exports and ambitious development plans and drawing big questions over the reliability of its longstanding US security umbrella.