Skip to content

The agent that grows with you

fix(mcp): keep the first callback result from being clobbered by browser fetches

liuhao1024a99a1034ad75
diff --git a/tests/tools/test_mcp_oauth_callback_latch.py b/tests/tools/test_mcp_oauth_callback_latch.py
new file mode 100644
index 00000000000..814cf699515
--- /dev/null
+++ b/tests/tools/test_mcp_oauth_callback_latch.py
@@ -0,0 +1,73 @@
+"""Regression tests for the loopback OAuth callback handler (#116278).
+
+A real browser follows the /callback redirect with speculative queryless
+fetches (/favicon.ico), and the CLI waiter polls the result dict only every
+500ms — so a handler that updates the result unconditionally loses the stored
+code between polls and the login times out despite the success page the user
+saw. These tests pin the two invariants that prevent that: a request without
+``code``/``error`` never mutates the result, and the first terminal result
+wins over later callbacks.
+"""
+import threading
+from http.client import HTTPConnection
+from http.server import HTTPServer
+
+import pytest
+
+pytest.importorskip("mcp.client.auth.oauth2", reason="MCP SDK 1.26.0+ required")
+
+from tools.mcp_oauth import _make_callback_handler
+
+
+def callback_server():
+ handler_cls, result = _make_callback_handler()
+ server = HTTPServer(("127.0.0.1", 0), handler_cls)
+ thread = threading.Thread(target=server.serve_forever, kwargs={"poll_interval": 0.05}, daemon=True)
+ thread.start()
+ yield server.server_address[1], result
+ server.shutdown()
+ server.server_close()
+
+
+def _get(port: int, path: str) -> int:
+ conn = HTTPConnection("127.0.0.1", port, timeout=5)
+ try:
+ conn.request("GET", path)
+ return conn.getresponse().status
+ finally:
+ conn.close()
+
+
+def test_favicon_after_callback_keeps_stored_code(callback_server):
+ port, result = callback_server
+ assert _get(port, "/callback?code=synthetic-code&state=synthetic-state&iss=synthetic-iss") == 200
+ assert _get(port, "/favicon.ico") == 404
+ assert result["auth_code"] is not None
+ assert result["state"] == "synthetic-state"
+ assert result["iss"] == "synthetic-iss"
+
+
+def test_favicon_before_callback_is_inert(callback_server):
+ port, result = callback_server
+ assert _get(port, "/favicon.ico") == 404
+ assert result["auth_code"] is None
+ assert result["error"] is None
+ assert _get(port, "/callback?code=synthetic-code&state=synthetic-state") == 200
+ assert result["auth_code"] is not None
+
+
+def test_duplicate_callback_keeps_first_result(callback_server):
+ port, result = callback_server
+ assert _get(port, "/callback?code=first-code&state=first-state") == 200
+ assert _get(port, "/callback?code=second-code&state=second-state") == 200
+ assert result["auth_code"] == "first-code"
+ assert result["state"] == "first-state"
+
+
+def test_favicon_after_error_callback_keeps_error(callback_server):
+ port, result = callback_server
+ assert _get(port, "/callback?error=access_denied&state=synthetic-state") == 200
+ assert _get(port, "/favicon.ico") == 404
+ assert result["error"] == "access_denied"
+ assert result["auth_code"] is None
diff --git a/tools/mcp_oauth.py b/tools/mcp_oauth.py
index 0c699aad2b7..641ce3a204b 100644
--- a/tools/mcp_oauth.py
+++ b/tools/mcp_oauth.py
@@ -674,6 +674,25 @@ def _make_callback_handler() -> tuple[type, dict]:
class _Handler(BaseHTTPRequestHandler):
def do_GET(self) -> None: # noqa: N802
parsed = _parse_redirect_query(urlparse(self.path).query)
+ if not parsed["code"] and not parsed["error"]:
+ # The browser follows the real /callback with queryless fetches
+ # (/favicon.ico); an unconditional update here clobbered the stored
+ # code before the 500ms waiter poll saw it (#116278).
+ self.send_response(404)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.end_headers()
+ self.wfile.write(b"<html><body><h2>Not Found</h2></body></html>")
+ return
+ if _result_taken(result):
+ # First terminal result (HTTP or paste) wins; a duplicate or
+ # page-refresh callback must not replace it.
+ self.send_response(200)
+ self.send_header("Content-Type", "text/html; charset=utf-8")
+ self.end_headers()
+ self.wfile.write(
+ b"<html><body><h2>Authorization already received</h2>"
+ b"<p>You can close this tab and return to Hermes.</p></body></html>")
+ return
result.update(auth_code=parsed["code"], state=parsed["state"], error=parsed["error"], iss=parsed["iss"])
body = ("<h2>Authorization Successful</h2><p>You can close this tab and return to Hermes.</p>" if parsed["code"]
else f"<h2>Authorization Failed</h2><p>Error: {html.escape(parsed['error'] or 'unknown')}</p>")
@@ -682,6 +701,10 @@ def _make_callback_handler() -> tuple[type, dict]:
self.end_headers()
self.wfile.write(f"<html><body>{body}</body></html>".encode())
+ def log_request(self, code: str = "-", size: str = "-") -> None: # noqa: N802
+ # The request line's query carries the auth code — log the path only.
+ logger.debug("OAuth callback: %s %s", self.command, urlparse(self.path).path)
+
def log_message(self, fmt: str, *args: Any) -> None:
logger.debug("OAuth callback: %s", fmt % args)