From c5f78bbd5c2630b7f763918017e9cc87b008eb0f Mon Sep 17 00:00:00 2001 From: chengyongru Date: Wed, 23 Sep 2026 17:35:27 +0800 Subject: [PATCH] fix(mcp): handle OAuth interruptions through Loguru --- nanobot/agent/tools/mcp_oauth.py | 41 ++++++++++----------- tests/tools/test_mcp_oauth.py | 62 ++++++++++++++------------------ 2 files changed, 44 insertions(+), 59 deletions(-) diff --git a/nanobot/agent/tools/mcp_oauth.py b/nanobot/agent/tools/mcp_oauth.py index bcb21f413..fa59f39e4 100644 --- a/nanobot/agent/tools/mcp_oauth.py +++ b/nanobot/agent/tools/mcp_oauth.py @@ -10,7 +10,6 @@ from __future__ import annotations import asyncio import hashlib import json -import logging import math import os import secrets @@ -71,24 +70,6 @@ class MCPAuthorizationRequiredError(RuntimeError): """Raised when a background MCP connection needs interactive authorization.""" -class _OAuthAuthorizationLogFilter(logging.Filter): - """Keep the SDK's expected authorization interruption out of error tracebacks.""" - - def filter(self, record: logging.LogRecord) -> bool: - if ( - record.getMessage() == "OAuth flow error" - and record.exc_info - and isinstance(record.exc_info[1], MCPAuthorizationRequiredError) - ): - record.levelno = logging.INFO - record.levelname = "INFO" - record.msg = "MCP OAuth request paused at browser authorization" - record.args = () - record.exc_info = None - record.exc_text = None - return True - - @dataclass(frozen=True) class MCPOAuthHandlers: """Browser callbacks supplied only for a user-initiated OAuth attempt.""" @@ -571,6 +552,14 @@ class _RetryOAuthWithDiscoveredMetadata(BaseException): """Restart the SDK flow after discovery without logging a false OAuth failure.""" +class _OAuthAuthorizationInterrupted(BaseException): + """Carry expected authorization state past the SDK's generic error logger.""" + + def __init__(self, error: MCPAuthorizationRequiredError) -> None: + self.error = error + super().__init__(str(error)) + + class _RetryOAuthWithStoredCredentials(BaseException): """Restart the SDK flow with credentials refreshed by another provider.""" @@ -778,7 +767,10 @@ class _RefreshingOAuthClientProvider(OAuthClientProvider): self.context.client_info = None self._token_issuer = None raise _RetryOAuthWithStoredCredentials - return await super()._perform_authorization() + try: + return await super()._perform_authorization() + except MCPAuthorizationRequiredError as exc: + raise _OAuthAuthorizationInterrupted(exc) from exc async def async_auth_flow( self, @@ -809,6 +801,12 @@ class _RefreshingOAuthClientProvider(OAuthClientProvider): outgoing = await flow.asend(response) except StopAsyncIteration: return + except _OAuthAuthorizationInterrupted as exc: + logger.info( + "MCP server '{}': OAuth request stopped at browser authorization", + self._nanobot_storage.server_name, + ) + raise exc.error from None except _RetryOAuthWithDiscoveredMetadata: # The SDK has now validated discovery metadata. Mark the token # expired so its normal pre-request branch refreshes against the @@ -834,9 +832,6 @@ async def create_mcp_oauth_auth( handlers: MCPOAuthHandlers | None = None, ) -> OAuthClientProvider: """Build the official MCP SDK OAuth provider for one configured server.""" - sdk_logger = logging.getLogger("mcp.client.auth.oauth2") - if not any(isinstance(f, _OAuthAuthorizationLogFilter) for f in sdk_logger.filters): - sdk_logger.addFilter(_OAuthAuthorizationLogFilter()) storage = MCPOAuthStorage(server_name, server_url) if handlers is not None: await storage.prepare_redirect_uri( diff --git a/tests/tools/test_mcp_oauth.py b/tests/tools/test_mcp_oauth.py index 8bc921fd6..6a36c2960 100644 --- a/tests/tools/test_mcp_oauth.py +++ b/tests/tools/test_mcp_oauth.py @@ -3,7 +3,7 @@ from __future__ import annotations import asyncio import inspect import json -import logging +from unittest.mock import MagicMock from urllib.parse import parse_qs, urlsplit import httpx @@ -264,10 +264,9 @@ async def test_background_authorization_request_clears_rejected_token( @pytest.mark.asyncio -async def test_stale_authorization_preserves_new_credentials_without_error_log( +async def test_stale_authorization_preserves_new_credentials( tmp_path, monkeypatch: pytest.MonkeyPatch, - caplog: pytest.LogCaptureFixture, ) -> None: _use_data_dir(tmp_path, monkeypatch) server_url = "https://mcp.example.com/mcp" @@ -279,33 +278,11 @@ async def test_stale_authorization_preserves_new_credentials_without_error_log( await replacement.prepare_redirect_uri("http://127.0.0.1/auth/mcp/callback") await replacement.set_tokens(OAuthToken(access_token="new-access")) - sdk_logger = logging.getLogger("mcp.client.auth.oauth2") - with caplog.at_level(logging.INFO, logger=sdk_logger.name): - # The SDK logs and rethrows exceptions from the authorization callback. - with pytest.raises(MCPAuthorizationRequiredError): - try: - await auth.context.redirect_handler("https://auth.example.com/authorize") - except MCPAuthorizationRequiredError: - sdk_logger.exception("OAuth flow error") - raise + with pytest.raises(MCPAuthorizationRequiredError): + await auth.context.redirect_handler("https://auth.example.com/authorize") tokens = await MCPOAuthStorage("linear", server_url).get_tokens() assert tokens is not None and tokens.access_token == "new-access" - records = [record for record in caplog.records if record.name == sdk_logger.name] - assert len(records) == 1 - assert records[0].levelno == logging.INFO - assert records[0].exc_info is None - assert "OAuth flow error" not in caplog.text - - caplog.clear() - with pytest.raises(ValueError): - try: - raise ValueError("invalid OAuth response") - except ValueError: - sdk_logger.exception("OAuth flow error") - raise - assert caplog.records[0].levelno == logging.ERROR - assert caplog.records[0].exc_info is not None @pytest.mark.asyncio @@ -627,15 +604,19 @@ async def test_stale_token_endpoint_is_rediscovered_once( ("error", "clears_client"), [("invalid_grant", False), ("invalid_client", True)], ) +@pytest.mark.parametrize("unexpected_failure", [False, True]) async def test_unrecoverable_refresh_error_requires_authorization( tmp_path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, error: str, clears_client: bool, + unexpected_failure: bool, ) -> None: _use_data_dir(tmp_path, monkeypatch) - caplog.set_level(logging.INFO, logger="mcp.client.auth.oauth2") + caplog.set_level("INFO", logger="mcp.client.auth.oauth2") + log = MagicMock() + monkeypatch.setattr("nanobot.agent.tools.mcp_oauth.logger", log) server_url = "https://mcp.example.com/mcp" storage = MCPOAuthStorage("linear", server_url) await storage.set_oauth_metadata(_oauth_metadata()) @@ -650,6 +631,12 @@ async def test_unrecoverable_refresh_error_requires_authorization( )) auth = await create_mcp_oauth_auth("linear", server_url) + if unexpected_failure: + async def fail_redirect(_url: str) -> None: + raise ValueError("invalid OAuth response") + + auth.context.redirect_handler = fail_redirect + async def respond(request: httpx.Request) -> httpx.Response: if request.url.path == "/oauth/token": return httpx.Response(400, json={"error": error}) @@ -675,21 +662,24 @@ async def test_unrecoverable_refresh_error_requires_authorization( }) return httpx.Response(404) - with pytest.raises(MCPAuthorizationRequiredError): + with pytest.raises(ValueError if unexpected_failure else MCPAuthorizationRequiredError): async with httpx.AsyncClient( transport=httpx.MockTransport(respond), auth=auth, ) as client: await client.get(server_url) + if unexpected_failure: + errors = [record for record in caplog.records if record.getMessage() == "OAuth flow error"] + assert errors and errors[0].levelname == "ERROR" + assert errors[0].exc_info is not None + assert isinstance(errors[0].exc_info[1], ValueError) + return + reloaded = MCPOAuthStorage("linear", server_url) - interruptions = [ - record for record in caplog.records - if record.getMessage() == "MCP OAuth request paused at browser authorization" - ] - assert interruptions - assert all(record.levelno == logging.INFO and record.exc_info is None - for record in interruptions) + log.info.assert_any_call( + "MCP server '{}': OAuth request stopped at browser authorization", "linear", + ) assert "OAuth flow error" not in caplog.text assert await reloaded.get_tokens() is None client_info = await reloaded.get_client_info()