The war in Afghanistan began after terrorists attacked the Twin Towers of the World Trade Center on September 11, 2001. Prior to that in 1999, the United Nations had identified al-Qaeda and Taliban as terrorists.
The United States didn't become involved in the fight against al-Qaeda and the Taliban until after the Twin Towers were attacked. After the attack, President George W. Bush signed a resolution that provided legal rationale for the U.S. to combat terrorism by invading Afghanistan.
In June of 2013, Afghanistan forces took the lead in handling the security of the country. The American troops that were in Afghanistan shifted focus to counter-terrorism and helping train the nation's military.