SAN FRANCISCO (AP)  The San Francisco Giants landed the top-tier closer they have been seeking for months, agreeing to a $62 million, four-year contract with right-hander Mark Melancon on Monday.

It’s the richest contract ever for a closer, topping Jonathan Papelbon’s $50 million, four-year deal with the Phillies from 2012-15, and the average annual value tops Mariano Rivera’s $15 million with the New York Yankees from 2011-12.

“Really excited to have Mark,” manager Bruce Bochy said in a text message. “Got to know him on a trip to Taiwan in 2011. Fills an important need for us. Great to get one of the premier closers in the game.”

Pending a physical, the pitcher receives a $20 million signing bonus, $8 million of which is deferred, then salaries of $4 million for 2017, $10 million in ’18 and $14 million in each of the ’19 and 2020 seasons. He has a full no-trade clause and the chance to opt out after the first two years.

Melancon has saved at least 30 games in each of the past three seasons, recording a majors-best 51 in 2015. He went 47 for 51 in save opportunities in 75 relief appearances last season with Pittsburgh and Washington, tied for second-most saves in baseball with Baltimore’s Zach Britton and Kenley Jansen of the Dodgers behind the Mets’ Jeurys Familia with 51.

After San Francisco tried to acquire Aroldis Chapman at the trade deadline and missed out to the Cubs, finding a reliable ninth-inning option became top of the to-do list for the offseason. Melancon was dealt to the Nationals from the Pirates.

“Adding a premier closer was our main priority this offseason,” general manager Bobby Evans said. “Mark solidifies the back end of our bullpen and fills a critical role. He brings talent, leadership and experience to our pitching staff.”

Because the 31-year-old Melancon was traded during the season, the Giants don’t have to give up their first pick in June’s amateur draft as compensation.

The Giants blew 32 saves this past season, nine in September  one fewer than Melancon had over the past three years  and the last in a 6-5 Game 4 loss to the Cubs that ended San Francisco’s season. Chicago scored four runs in the ninth as Bochy tried five relievers in the inning.

Santiago Casilla and Sergio Romo, two reliable relievers in even-year championships of 2010, ’12 and ’14, were both inconsistent.

Last offseason, the Giants made a splash by adding to their starting rotation, signing Johnny Cueto to a $130 million, six-year contract and Jeff Samardzija for $90 million over five years.

“We gave him an offer that we felt was market value and what we were comfortable giving him. You’re talking about one of the elite closers in the game and a great teammate,” Rizzo said. “Conducted himself perfectly as a Washington National. At the end of the day, the Giants offered him more, and he took the deal. That’s what free agency’s all about. …