Refactor agent and server to remove duplicate code