Since 2010, the I.R.S.’s budget has fallen 18 percent, adjusted for inflation, and its enforcement staff has shrunk 23 percent. President Trump has proposed further cuts.

Mr. Koskinen was already enjoying retirement in 2013 when the Obama administration asked him to take the helm of the I.R.S. during a crisis fueled by allegations that it had wrongfully scrutinized Tea Party groups that had applied for tax-exempt status. He was known as a Mr. Fix-It in Washington for his work at the Office of Management and Budget during the 1990s government shutdown, for heading the team that averted the Y2K crisis at the turn of the century and for leading Freddie Mac during the financial crisis. The I.R.S. was a challenge he could not refuse.

Four years later, Mr. Koskinen has weathered a fusillade of attacks. Threatened with censure and impeachment on the grounds that he was misleading Congress about the actions of his predecessors, the commissioner refused to be pushed out of the job.

“Not a chance,” Mr. Koskinen said when asked if he ever considered quitting.

His wry sense of humor remains intact. In his waning time, he jokes with his staff about all the “fun” of their daily tasks and counts down the days to his departure by tending to a makeshift pumpkin patch decorated with gourds bearing his likeness. Soon enough, Mr. Koskinen jokes as he distributes candy to a visitor, he will turn into a pumpkin and disappear.

Mr. Koskinen is spending his remaining days defending his agency’s integrity and drumming up funding for a department that has been running on dwindling resources. Mr. Koskinen took some solace in an inspector general report released last month that showed the I.R.S. had actually been scrutinizing both liberal and conservative groups, yet he remains concerned that the coarse treatment he received from members of Congress could discourage future public servants from taking such jobs.