Morocco and Spain are to reinforce co-operation in fighting terrorism, drug trafficking and illegal migration.
Many of the Madrid bomb suspects are Moroccan
Under the deal, a Spanish judge will be based in Rabat and a Moroccan judge in Madrid to speed up judicial procedures involving both countries.
A commission will also be set up to boost joint efforts against terrorism and organised crime.
Spain sought to improve dealings with Morocco following the Madrid bomb attacks that killed 191 people.
Fourteen of the 18 people provisionally charged in connection with the 11 March attacks on trains are Moroccans.
Six out of seven bombing suspects who died in a Madrid flat in April, in an apparent mass suicide after they were surrounded by police, were also Moroccan.
The agreement came at a meeting between the Moroccan Justice Minister, Mohammed Bouzoubaa, and his Spanish counterpart, Juan Fernando Lopez Aguilar, on Wednesday.
Mr Lopez Aguilar said: "We have to learn lessons from what happened... and share
He said investigations had shown "connections between drug trafficking and the perpetrators of the Madrid bombings - thus the need to exchange information".
He added that Spain would also help train magistrates in Morocco to help
modernise the country's legal system.
Morocco has faced its own terror attacks - about 45 people, 12 of them bombers, were killed in the suicide blasts in Casablanca last May.
The authorities have arrested about 2,000 people in cases linked to terrorism since the attacks.