Late goals from the Manchester City playmaker and Barcelona star denied the home side a famous win after it had raced into a two-goal lead in the first half.
Arsenal striker Joel Campbell and midfielder Randall Brenes were on the scoresheet for the home side in the first half, before Spain fought back late on to salvage a draw thanks to strikes from David Silva and David Villa.
Goalkeeper Iker Casillas made his 127th appearance for La Roja, becoming Spain's most-capped player of all time in the process, but his uncharacteristic error shortly before halftime will no doubt tarnish his memories of the game.
A seemingly innocuous through ball found its way through to the Real Madrid custodian, who should have dealt with it comfortably. However, his poor touch allowed Brenes to gain possession, and the impressive midfielder dummied the Spanish keeper before lifting a delicate chip over Carles Puyol and into the back of the net to give his side an unexpected lead.
Spain's nightmare in international friendlies looked to be continuing as Costa Rica went on to take a 2-0 lead, Campbell setting himself on the edge of the box before firing an effort past the helpless Casillas and into the bottom corner.
On the balance of play the scoreline at halftime did not flatter the hosts, but Costa Rica goalkeeper Keylor Navas was kept busy towards the end of the half, making two good saves from Cesc Fabregas to maintain the home side's lead.
Unsurprisingly, Spain made a host of substitutions following its dismal first-half display and with its pride yet again at stake following a recent loss to England it seemed to move up through the gears.
An acrobatic Navas save from a David Villa free kick kept the score at 2-0 before the Barcelona striker appeared to have finally reduced the deficit only for his effort to be ruled out for offside.
Villa appeared on a one-man mission for Spain, going close twice more just minutes later, firing into the side netting after being played through by the substitute Silva, before shooting wide under pressure from center back Johnny Acosta.
Silva scored late on to set up a tense final 10 minutes, converting after neat buildup from Andres Iniesta. Spain's spirited comeback was completed by Villa in injury time, leaving the home side in disbelief as he headed home the leveler his efforts in the second period had deserved.
The world champion's record in friendlies since winning the World Cup last year made grim reading going into the game and at halftime showed no signs of ending. However, the introduction of Silva alongside the persistent Villa allowed La Roja to salvage the situation.