Merge "Fix authentication via gitcookie file"
diff --git a/gerrit_mcp_server/gerrit_auth.py b/gerrit_mcp_server/gerrit_auth.py
index 9ce4f6a..a37af16 100644
--- a/gerrit_mcp_server/gerrit_auth.py
+++ b/gerrit_mcp_server/gerrit_auth.py
@@ -48,6 +48,8 @@
         raise ValueError("Authentication method requires 'gitcookies_path' to be set.")
 
     gitcookies_path = os.path.expanduser(gitcookies_path_str)
+
+    last_found_cookie = None
     if os.path.exists(gitcookies_path):
         domain = (
             gerrit_base_url.replace("https://", "").replace("http://", "").split("/")[0]
@@ -57,8 +59,10 @@
                 if domain in line:
                     parts = line.strip().split("\t")
                     if len(parts) == 7:
-                        cookie = f"{parts[5]}={parts[6]}"
-                        return ["curl", "-b", cookie, "-L"]
+                        last_found_cookie = f"{parts[5]}={parts[6]}"
+
+        if last_found_cookie:
+            return ["curl", "-b", last_found_cookie, "-L"]
 
     # Fallback for when the cookie file doesn't exist or has no matching cookie.
     return ["curl", "-s", "-L"]
\ No newline at end of file
diff --git a/tests/unit/test_gerrit_auth.py b/tests/unit/test_gerrit_auth.py
index cadd9a9..a9d0cb5 100644
--- a/tests/unit/test_gerrit_auth.py
+++ b/tests/unit/test_gerrit_auth.py
@@ -68,6 +68,22 @@
         with self.assertRaisesRegex(ValueError, "requires 'gitcookies_path'"):
             gerrit_auth._get_auth_for_gitcookies("https://a.com", {})
 
+    @patch("os.path.exists", return_value=True)
+    def test_get_auth_for_gitcookies_selects_last_entry(self, mock_exists):
+        """Tests that _get_auth_for_gitcookies selects the last matching cookie entry."""
+        config = {"gitcookies_path": "~/.gitcookies"}
+        url = "https://my-gerrit.com"
+        multi_cookie_content = (
+            "other-gerrit.com\tFALSE\t/\tTRUE\t2147483647\to\tgit-oldtoken\n"
+            "my-gerrit.com\tFALSE\t/\tTRUE\t2147483647\to\tgit-firsttoken\n"
+            "another-gerrit.com\tFALSE\t/\tTRUE\t2147483647\to\tgit-anothertoken\n"
+            "my-gerrit.com\tFALSE\t/\tTRUE\t2147483647\to\tgit-lasttoken"
+        )
+        m = mock_open(read_data=multi_cookie_content)
+        with patch("builtins.open", m):
+            command = gerrit_auth._get_auth_for_gitcookies(url, config)
+        self.assertEqual(command, ["curl", "-b", "o=git-lasttoken", "-L"])
+
 
 if __name__ == "__main__":
     unittest.main()