You must use the ready action to prepare to cast a spell with the trigger of "When he/she/it casts a spell"
If the target casts a spell you get a free action spellcraft check to identify the spell. If you succeed and can cast the spell(have it prepared or know it as apropriate for your class) you can cast it as a counterspell.
its all in the Magic chapter of the PHB