fix(mcp): handle OAuth interruptions through Loguru
This commit is contained in:
1 parent
422033af7d
commit
c5f78bbd5c
2 files changed
+44
-59
No files matched your search
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user