The U.S. military gave control of its last detention facility in Afghanistan to Kabul on Monday, a year after the two sides initially agreed on the transfer.

The handover of Parwan Detention Facility, located near the U.S.-run Bagram military base north of Kabul, ends a bitter chapter in U.S. relations with Afghanistan President Hamid Karzai, who demanded control of the prison as a matter of sovereignty.

It took place a few hours before U.S. Secretary of State John Kerry flew into Afghanistan on an unannounced visit to meet Mr. Karzai.

The dispute over the detention facility also threw a pall over the negotiations for a security agreement that would govern the presence of U.S. forces after 2014.

U.S. commander in Afghanistan General Joseph Dunford handed over Parwan, after signing an agreement with Defence Minister Bismillah Khan Mohammadi.

The detention centre houses about 3,000 prisoners and the majority are already under Afghan control. The U.S. had not handed over about 100, and some of those under American authority do not have the right to a trial because the U.S. considers them part of a conflict.

There are also about three dozen non-Afghan detainees, including Pakistanis and other nationals who will remain in American hands. The exact number and nationality of those detainees has never been made public.

An initial agreement to hand over Parwan was signed a year ago, but efforts to follow through on it constantly stumbled over American concerns that the Afghan government would release prisoners that it considered dangerous.

A key hurdle was a ruling by an Afghan judicial panel holding that administrative detention, the practice of holding someone without formal charges, violated laws. The U.S. argued that international law allowed administrative detentions and that it could not risk turning over some high-value detainees to the notoriously corrupt Afghan court system. An initial deadline for the full handover passed last September and another earlier this month.

The formula for how the two sides resolved this dilemma has not been made public. Officials say Kabul will be able to invoke a procedure that ensures prisoners considered dangerous will not be released.

According to a U.S. official in Washington, the agreement also includes a provision that allows both to work together to resolve differences.