"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(cli,mcp): keep live authorize alive through the OAuth flow (#281)
卫斯李1c897e364228
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.pyindex 110d06b9e..1804eff9b 100644--- a/agent/cli/_legacy.py+++ b/agent/cli/_legacy.py@@ -2742,6 +2742,31 @@ def cmd_provider_login(provider: str) -> int:_DEFAULT_LIVE_BROKER = "robinhood"_LIVE_AUTHORIZE_INIT_TIMEOUT_SECONDS = 300.0+_LIVE_AUTHORIZE_TIMEOUT_ENV = "VIBE_LIVE_AUTHORIZE_TIMEOUT_SECONDS"+++def _authorize_timeout_seconds() -> float:+ """Resolve the OAuth authorize handshake deadline in seconds.++ Reads ``VIBE_LIVE_AUTHORIZE_TIMEOUT_SECONDS`` and falls back to+ :data:`_LIVE_AUTHORIZE_INIT_TIMEOUT_SECONDS` (300 s) when it is unset,+ empty, non-numeric, or not strictly positive. This deadline bounds the+ interactive ``list_tools`` handshake that drives the broker OAuth flow, so+ a multi-minute human sign-in (e.g. Robinhood's face scan) has room to+ complete.++ Returns:+ The authorize deadline in seconds (a positive float).+ """+ raw = os.getenv(_LIVE_AUTHORIZE_TIMEOUT_ENV)+ if raw:+ try:+ value = float(raw)+ except ValueError:+ return _LIVE_AUTHORIZE_INIT_TIMEOUT_SECONDS+ if value > 0:+ return value+ return _LIVE_AUTHORIZE_INIT_TIMEOUT_SECONDSdef _live_api_base() -> str:@@ -2845,15 +2870,36 @@ def cmd_live_authorize(broker: str) -> int:try:from src.tools.mcp import build_mcp_tool_wrappers- configured_init_timeout = getattr(server_config, "init_timeout", None)- if (- configured_init_timeout is None- or float(configured_init_timeout) < _LIVE_AUTHORIZE_INIT_TIMEOUT_SECONDS- ) and hasattr(server_config, "model_copy"):- server_config = server_config.model_copy(- update={"init_timeout": _LIVE_AUTHORIZE_INIT_TIMEOUT_SECONDS}- )- tools = build_mcp_tool_wrappers(key, server_config)+ # The OAuth flow is driven lazily by the first request to the server —+ # the `list_tools` discovery handshake — which is bounded by the+ # per-call `tool_timeout` (default 30 s), NOT `init_timeout`. Raise both+ # to the authorize deadline so a multi-minute human sign-in (e.g.+ # Robinhood's face scan) does not trip the handshake. Raise-only: never+ # shrink an already-larger user-configured timeout.+ authorize_timeout = _authorize_timeout_seconds()+ if hasattr(server_config, "model_copy"):+ updates: dict[str, float] = {}+ configured_init_timeout = getattr(server_config, "init_timeout", None)+ if (+ configured_init_timeout is None+ or float(configured_init_timeout) < authorize_timeout+ ):+ updates["init_timeout"] = authorize_timeout+ configured_tool_timeout = getattr(server_config, "tool_timeout", None)+ if (+ configured_tool_timeout is None+ or float(configured_tool_timeout) < authorize_timeout+ ):+ updates["tool_timeout"] = authorize_timeout+ if updates:+ server_config = server_config.model_copy(update=updates)++ # Single attempt: a transient-retry would open a fresh client context+ # that starts a SECOND OAuth callback server on a new port, orphaning+ # the sign-in the user just completed against the first one (see #259).+ tools = build_mcp_tool_wrappers(+ key, server_config, max_list_tools_attempts=1+ )except Exception as exc: # noqa: BLE001 — surface any handshake failureconsole.print(f"[red]Authorization failed:[/red] {exc}")return EXIT_RUN_FAILEDdiff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.pyindex 8fd1f7a4a..0acc1261d 100644--- a/agent/src/tools/mcp.py+++ b/agent/src/tools/mcp.py@@ -108,6 +108,7 @@ def build_mcp_tool_wrappers(*,local_server_name: str | None = None,client_factory: ClientFactory | None = None,+ max_list_tools_attempts: int = 2,) -> list["MCPRemoteTool"]:"""Build local tool wrappers for a configured MCP server.@@ -119,6 +120,11 @@ def build_mcp_tool_wrappers(tool names stable when multiple raw server names sanitize to thesame local prefix.client_factory: Optional async client factory for tests.+ max_list_tools_attempts: Number of ``list_tools`` attempts during tool+ discovery. Defaults to 2 (one transient retry). Set to 1 for the+ interactive ``connector authorize`` bootstrap, where a retry would+ start a second OAuth callback server and orphan the user's+ in-progress sign-in.Returns:Local BaseTool wrappers for all enabled remote tools.@@ -132,6 +138,7 @@ def build_mcp_tool_wrappers(server_config,local_server_name=local_server_name,client_factory=client_factory,+ max_list_tools_attempts=max_list_tools_attempts,)return [MCPRemoteTool(adapter=adapter, spec=spec) for spec in adapter.discover_tools()]@@ -289,6 +296,7 @@ class MCPServerAdapter:*,local_server_name: str | None = None,client_factory: ClientFactory | None = None,+ max_list_tools_attempts: int = 2,) -> None:"""Initialize the MCP server adapter.@@ -298,11 +306,16 @@ class MCPServerAdapter:local_server_name: Optional local naming override used only for theserver portion of generated tool names.client_factory: Optional async client factory, mainly for tests.+ max_list_tools_attempts: Number of ``list_tools`` attempts (>= 1).+ Defaults to 2 (one transient retry). The authorize bootstrap+ sets this to 1 so a retry cannot start a second OAuth callback+ server and orphan an in-progress sign-in."""self.server_name = server_nameself.local_server_name = local_server_name or server_nameself.server_config = server_configself._client_factory = client_factory or self._build_client+ self._list_tools_attempts = max(1, max_list_tools_attempts)def discover_tools(self) -> list[MCPRemoteToolSpec]:"""Discover enabled tools from the remote MCP server.@@ -444,7 +457,10 @@ class MCPServerAdapter:)async def _list_tools(self) -> list[mcp_types.Tool]:- """List remote tools with a single retry on transient failures.+ """List remote tools, retrying once on transient failures by default.++ The number of attempts is governed by ``self._list_tools_attempts``+ (1 disables the retry, used by the authorize bootstrap).Returns:Remote MCP tool definitions.@@ -452,7 +468,11 @@ class MCPServerAdapter:Raises:Exception: Propagates non-transient or exhausted failures."""- return await self._run_with_retry("list_tools", self._list_tools_once)+ return await self._run_with_retry(+ "list_tools",+ self._list_tools_once,+ attempts=self._list_tools_attempts,+ )async def _list_tools_once(self) -> list[mcp_types.Tool]:"""List remote tools without retry handling.@@ -494,21 +514,26 @@ class MCPServerAdapter:self,operation_name: str,operation: Callable[[], Awaitable[ResultT]],+ *,+ attempts: int = 2,) -> ResultT:- """Run an async MCP operation with a single transient retry.+ """Run an async MCP operation with bounded transient retries.Args:operation_name: Human-readable operation label.operation: Async operation to execute.+ attempts: Maximum attempts (>= 1). Defaults to 2 (one transient+ retry). Pass 1 to disable retry — used by the authorize+ bootstrap, where a retry restarts the OAuth flow.Returns:Operation result.Raises:Exception: Re-raises the last failure when retry is not allowed or- both attempts fail.+ all attempts fail."""- attempts = 2+ attempts = max(1, attempts)for attempt in range(1, attempts + 1):try:return await operation()diff --git a/agent/tests/test_cli_live.py b/agent/tests/test_cli_live.pyindex a55a6abb2..38e7acb7e 100644--- a/agent/tests/test_cli_live.py+++ b/agent/tests/test_cli_live.py@@ -344,8 +344,13 @@ class TestLiveAuthorize:build.assert_called_once()assert build.call_args.args[0] == "robinhood"- def test_authorize_uses_long_init_budget_without_widening_tool_timeout(self) -> None:- """Old user configs without initTimeout still get enough OAuth time."""+ def test_authorize_widens_tool_timeout_to_deadline(self) -> None:+ """list_tools is bounded by tool_timeout, so authorize must widen it too.++ Regression for #259: the OAuth flow is driven by the list_tools+ handshake (per-call tool_timeout, default 30 s), not init_timeout. Both+ must reach the 300 s authorize deadline.+ """from cli._legacy import cmd_live_authorizefrom src.config.schema import MCPServerConfig@@ -363,9 +368,70 @@ class TestLiveAuthorize:assert cmd_live_authorize("robinhood") == 0passed_cfg = build.call_args.args[1]- assert cfg.init_timeout is None+ assert cfg.tool_timeout == 30 # original unchangedassert passed_cfg.init_timeout == 300- assert passed_cfg.tool_timeout == 30+ assert passed_cfg.tool_timeout == 300+ # Single attempt: no retry that would orphan the OAuth callback.+ assert build.call_args.kwargs["max_list_tools_attempts"] == 1++ def test_authorize_preserves_larger_configured_tool_timeout(self) -> None:+ """Raise-only: an already-larger configured timeout is not lowered."""+ from cli._legacy import cmd_live_authorize+ from src.config.schema import MCPServerConfig++ cfg = MCPServerConfig.model_validate(+ {+ "type": "streamableHttp",+ "url": "https://agent.robinhood.com/mcp/trading",+ "auth": {"type": "oauth", "scopes": ["trading.read"]},+ "enabledTools": ["get_account"],+ "toolTimeout": 600,+ "initTimeout": 600,+ }+ )+ with patch("cli._legacy._live_server_config", return_value=cfg), patch(+ "src.tools.mcp.build_mcp_tool_wrappers", return_value=[1]+ ) as build:+ assert cmd_live_authorize("robinhood") == 0++ passed_cfg = build.call_args.args[1]+ assert passed_cfg.tool_timeout == 600+ assert passed_cfg.init_timeout == 600++ def test_authorize_honors_timeout_env_override(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """VIBE_LIVE_AUTHORIZE_TIMEOUT_SECONDS overrides the 300 s default."""+ from cli._legacy import cmd_live_authorize+ from src.config.schema import MCPServerConfig++ monkeypatch.setenv("VIBE_LIVE_AUTHORIZE_TIMEOUT_SECONDS", "900")+ cfg = MCPServerConfig.model_validate(+ {+ "type": "streamableHttp",+ "url": "https://agent.robinhood.com/mcp/trading",+ "auth": {"type": "oauth", "scopes": ["trading.read"]},+ "enabledTools": ["get_account"],+ }+ )+ with patch("cli._legacy._live_server_config", return_value=cfg), patch(+ "src.tools.mcp.build_mcp_tool_wrappers", return_value=[1]+ ) as build:+ assert cmd_live_authorize("robinhood") == 0++ passed_cfg = build.call_args.args[1]+ assert passed_cfg.tool_timeout == 900+ assert passed_cfg.init_timeout == 900++ @pytest.mark.parametrize("raw", ["", "abc", "0", "-5"])+ def test_authorize_timeout_env_invalid_falls_back_to_default(+ self, raw: str, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ """Empty / non-numeric / non-positive env values fall back to 300 s."""+ from cli._legacy import _authorize_timeout_seconds++ monkeypatch.setenv("VIBE_LIVE_AUTHORIZE_TIMEOUT_SECONDS", raw)+ assert _authorize_timeout_seconds() == 300.0# ---------------------------------------------------------------------------diff --git a/agent/tests/test_mcp_client_adapter.py b/agent/tests/test_mcp_client_adapter.pyindex 9129d878b..af10f4367 100644--- a/agent/tests/test_mcp_client_adapter.py+++ b/agent/tests/test_mcp_client_adapter.py@@ -315,6 +315,39 @@ def test_build_mcp_tool_wrappers_retries_transient_discovery_failure() -> None:assert state["list_calls"] == 2+def test_build_mcp_tool_wrappers_single_attempt_does_not_retry_discovery() -> None:+ """max_list_tools_attempts=1 (authorize bootstrap) must not retry.++ Regression for #259: a retry opens a fresh client context that starts a+ second OAuth callback server, orphaning the user's in-progress sign-in. The+ authorize path passes max_list_tools_attempts=1 so the first transient+ failure propagates immediately and exactly one client context is opened.+ """+ transient = McpError(+ mcp_types.ErrorData(code=mcp_types.CONNECTION_CLOSED, message="Connection closed")+ )+ state = {+ "list_calls": 0,+ "call_calls": 0,+ "call_records": [],+ "list_outcomes": [+ transient,+ [mcp_types.Tool(name="quote", description="Quote", inputSchema={"type": "object"})],+ ],+ "call_outcomes": [],+ }++ with pytest.raises(McpError):+ build_mcp_tool_wrappers(+ "demo",+ _make_config(),+ client_factory=_make_factory(state),+ max_list_tools_attempts=1,+ )++ assert state["list_calls"] == 1++def test_remote_tool_execute_returns_normalized_error_payload_without_retry() -> None:state = {"list_calls": 0,@@ -494,4 +527,4 @@ def test_build_client_rejects_url_only_config_without_explicit_type() -> None:adapter = MCPServerAdapter("demo", config)with pytest.raises(ValueError, match="explicit type"):- adapter._build_client()\ No newline at end of file+ adapter._build_client()