"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix: support IBKR public MCP OAuth
SYKuangced2108cf867
diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.pyindex fb715fbf6..39f9881ca 100644--- a/agent/src/tools/mcp.py+++ b/agent/src/tools/mcp.py@@ -9,14 +9,17 @@ import loggingimport osimport reimport threading-from collections.abc import Mapping+import webbrowser+from collections.abc import AsyncGenerator, Mappingfrom copy import deepcopyfrom dataclasses import dataclass, is_dataclassfrom typing import Any, Awaitable, Callable, Coroutine, Iterable, Protocol, TypeVar+from urllib.parse import urlparseimport httpxfrom fastmcp.client import Clientfrom fastmcp.client.auth import OAuth+from fastmcp.client.auth.oauth import ClientNotFoundErrorfrom fastmcp.client.client import CallToolResulttry:from fastmcp.client.transports.http import StreamableHttpTransport@@ -31,6 +34,7 @@ except ModuleNotFoundError:from fastmcp.exceptions import McpError, ToolErrorfrom key_value.aio.stores.filetree import FileTreeStore, FileTreeV1KeySanitizationStrategyfrom mcp import types as mcp_types+from mcp.shared.auth import OAuthMetadatafrom pydantic_core import PydanticSerializationError, to_jsonable_pythonfrom src.agent.tools import BaseTool@@ -139,6 +143,82 @@ class _GuardedOAuth(OAuth):await super().redirect_handler(authorization_url)+class _IBKROAuth(_GuardedOAuth):+ """Add the browser headers required by IBKR's OAuth WAF."""++ async def _refresh_token(self) -> httpx.Request:+ if self.context.oauth_metadata is None:+ self.context.oauth_metadata = OAuthMetadata(+ issuer="https://api.ibkr.com",+ authorization_endpoint="https://api.ibkr.com/oauth2/authorize",+ token_endpoint="https://api.ibkr.com/oauth2/api/v1/token",+ registration_endpoint="https://api.ibkr.com/oauth2/register",+ )+ return await super()._refresh_token()++ async def _initialize(self) -> None:+ await super()._initialize()+ client_info = self.context.client_info+ registered_redirects = {+ str(uri) for uri in (getattr(client_info, "redirect_uris", None) or [])+ }+ current_redirect = str(self.context.client_metadata.redirect_uris[0])+ if (+ client_info is not None+ and self._static_client_info is None+ and registered_redirects+ and current_redirect not in registered_redirects+ ):+ await self.token_storage_adapter.clear()+ self.context.client_info = None+ self.context.current_tokens = None+ self.context.token_expiry_time = None++ async def async_auth_flow(+ self, request: httpx.Request+ ) -> AsyncGenerator[httpx.Request, httpx.Response]:+ flow = super().async_auth_flow(request)+ response = None+ try:+ while True:+ try:+ oauth_request = await flow.asend(response)+ except StopAsyncIteration:+ break+ if oauth_request.url.host == "api.ibkr.com":+ oauth_request.headers["User-Agent"] = "Mozilla/5.0"+ if not oauth_request.url.path.startswith("/v1/api/mcp"):+ oauth_request.headers["Accept"] = "application/json"+ if oauth_request.url.path == "/oauth2/register":+ oauth_request.headers["Origin"] = "https://api.ibkr.com"+ response = yield oauth_request+ finally:+ await flow.aclose()++ async def redirect_handler(self, authorization_url: str) -> None:+ if not self._allow_interactive:+ await super().redirect_handler(authorization_url)+ return+ async with self.httpx_client_factory() as client:+ response = await client.get(+ authorization_url,+ headers={+ "User-Agent": "Mozilla/5.0",+ "Accept": "application/json",+ },+ follow_redirects=False,+ )+ if response.status_code == 400:+ raise ClientNotFoundError(+ "OAuth client not found - cached credentials may be stale"+ )+ if response.status_code not in (200, 301, 302, 303, 307, 308):+ raise RuntimeError(+ f"Unexpected authorization response: {response.status_code}"+ )+ webbrowser.open(authorization_url)++def _make_cache_key(server_name: str, server_config: "MCPServerConfig") -> tuple[str, ...]:"""Build a content-based cache key for MCP tool discovery results.@@ -617,11 +697,19 @@ class MCPServerAdapter:# transport. Token cache is persistent (FileTreeStore), so the# channel stays authorized across CLI invocations and refresh is# handled inside the MCP lib's OAuthClientProvider.- auth = _GuardedOAuth(+ is_ibkr = urlparse(self.server_config.url).hostname == "api.ibkr.com"+ oauth_type = _IBKROAuth if is_ibkr else _GuardedOAuth+ auth = oauth_type(scopes=list(oauth_config.scopes) or None,client_name=oauth_config.client_name,token_storage=_build_token_store(oauth_config.cache_dir),- callback_port=oauth_config.callback_port,+ additional_client_metadata=(+ {"token_endpoint_auth_method": "none"} if is_ibkr else None+ ),+ callback_port=(+ oauth_config.callback_port+ or (8765 if is_ibkr else None)+ ),client_id=oauth_config.client_id,client_secret=oauth_config.client_secret,client_metadata_url=oauth_config.client_metadata_url,diff --git a/agent/tests/test_mcp_oauth_noninteractive.py b/agent/tests/test_mcp_oauth_noninteractive.pyindex ad0afcc57..eaa5aa92c 100644--- a/agent/tests/test_mcp_oauth_noninteractive.py+++ b/agent/tests/test_mcp_oauth_noninteractive.py@@ -93,7 +93,13 @@ class _ExplodingHTTPClient:return None-def _oauth_provider(tmp_path, *, interactive: bool) -> OAuth:+def _oauth_provider(+ tmp_path,+ *,+ interactive: bool,+ server_name: str = "robinhood",+ url: str = "https://agent.robinhood.com/mcp/trading",+) -> OAuth:"""Build the OAuth provider an adapter would attach to its transport.Args:@@ -108,7 +114,7 @@ def _oauth_provider(tmp_path, *, interactive: bool) -> OAuth:cfg = MCPServerConfig.model_validate({"type": "streamableHttp",- "url": "https://agent.robinhood.com/mcp/trading",+ "url": url,"auth": {"type": "oauth","scopes": ["trading.read"],@@ -118,7 +124,7 @@ def _oauth_provider(tmp_path, *, interactive: bool) -> OAuth:},})- adapter = MCPServerAdapter("robinhood", cfg, interactive_oauth=interactive)+ adapter = MCPServerAdapter(server_name, cfg, interactive_oauth=interactive)auth = adapter._build_client().transport.authassert isinstance(auth, OAuth)return auth@@ -137,6 +143,19 @@ def test_noninteractive_adapter_refuses_to_open_a_browser(tmp_path, monkeypatch)asyncio.run(auth.redirect_handler("https://agent.robinhood.com/oauth2/authorize?x=1"))+def test_noninteractive_ibkr_adapter_refuses_to_open_a_browser(tmp_path) -> None:+ auth = _oauth_provider(+ tmp_path,+ interactive=False,+ server_name="ibkr",+ url="https://api.ibkr.com/v1/api/mcp-public",+ )+ auth.httpx_client_factory = _ExplodingHTTPClient++ with pytest.raises(RuntimeError, match="connect/reconnect"):+ asyncio.run(auth.redirect_handler("https://api.ibkr.com/oauth2/authorize?x=1"))++def test_interactive_adapter_keeps_default_browser_flow(tmp_path, monkeypatch) -> None:opened: list[str] = []monkeypatch.setattr(webbrowser, "open", opened.append)diff --git a/agent/tests/test_mcp_oauth_schema.py b/agent/tests/test_mcp_oauth_schema.pyindex 29272ead2..c8118b122 100644--- a/agent/tests/test_mcp_oauth_schema.py+++ b/agent/tests/test_mcp_oauth_schema.py@@ -15,12 +15,19 @@ Covers:from __future__ import annotations+import asyncio+import json+from unittest.mock import patch++import httpximport pytestfrom fastmcp.client.auth import OAuthfrom fastmcp.client.transports.http import StreamableHttpTransportfrom fastmcp.client.transports.sse import SSETransportfrom fastmcp.client.transports.stdio import StdioTransport-from pydantic import ValidationError+from mcp.client.auth.exceptions import OAuthRegistrationError+from mcp.shared.auth import OAuthClientInformationFull, OAuthToken+from pydantic import AnyHttpUrl, ValidationErrorfrom src.config.schema import (IBKR_MCP_SERVER_SEED,@@ -258,6 +265,191 @@ def test_build_client_yields_oauth_streamable_transport() -> None:assert transport.auth._client_metadata_url == "https://example.com/oauth/client.json"+def test_ibkr_oauth_registration_uses_browser_headers(tmp_path) -> None:+ cfg = MCPServerConfig.model_validate(+ {+ "type": "streamableHttp",+ "url": "https://api.ibkr.com/v1/api/mcp-public",+ "auth": {+ "type": "oauth",+ "scopes": ["mcp.read"],+ "cacheDir": str(tmp_path),+ },+ "enabledTools": ["*"],+ }+ )+ transport = MCPServerAdapter("ibkr", cfg)._build_client().transport+ assert transport.auth.redirect_port == 8765+ seen: dict[str, str | None] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ url = str(request.url)+ if url == cfg.url:+ seen["mcp-accept"] = request.headers.get("accept")+ return httpx.Response(+ 401,+ headers={+ "WWW-Authenticate": (+ 'Bearer resource_metadata="'+ f'{cfg.url}/.well-known/oauth-protected-resource"'+ )+ },+ request=request,+ )+ if url == f"{cfg.url}/.well-known/oauth-protected-resource":+ return httpx.Response(+ 200,+ json={+ "resource": cfg.url,+ "authorization_servers": ["https://api.ibkr.com/oauth2"],+ "scopes_supported": ["mcp.read"],+ },+ request=request,+ )+ if url in {+ "https://api.ibkr.com/.well-known/oauth-authorization-server/oauth2",+ "https://api.ibkr.com/oauth2/.well-known/oauth-authorization-server",+ }:+ return httpx.Response(+ 200,+ json={+ "issuer": "https://api.ibkr.com",+ "authorization_endpoint": "https://api.ibkr.com/oauth2/authorize",+ "token_endpoint": "https://api.ibkr.com/oauth2/api/v1/token",+ "registration_endpoint": "https://api.ibkr.com/oauth2/register",+ "code_challenge_methods_supported": ["S256"],+ },+ request=request,+ )+ if url == "https://api.ibkr.com/oauth2/register":+ seen["user-agent"] = request.headers.get("user-agent")+ seen["origin"] = request.headers.get("origin")+ seen["accept"] = request.headers.get("accept")+ seen["token-endpoint-auth-method"] = json.loads(request.content).get(+ "token_endpoint_auth_method"+ )+ return httpx.Response(403, text="stop", request=request)+ return httpx.Response(404, request=request)++ async def run() -> None:+ async with httpx.AsyncClient(+ auth=transport.auth,+ transport=httpx.MockTransport(handler),+ ) as client:+ await client.get(+ cfg.url,+ headers={"Accept": "application/json, text/event-stream"},+ )++ with pytest.raises(OAuthRegistrationError):+ asyncio.run(run())++ assert seen == {+ "user-agent": "Mozilla/5.0",+ "origin": "https://api.ibkr.com",+ "accept": "application/json",+ "mcp-accept": "application/json, text/event-stream",+ "token-endpoint-auth-method": "none",+ }+++def test_ibkr_oauth_accepts_authorization_redirect(tmp_path) -> None:+ cfg = MCPServerConfig.model_validate(+ {+ "type": "streamableHttp",+ "url": "https://api.ibkr.com/v1/api/mcp-public",+ "auth": {+ "type": "oauth",+ "scopes": ["mcp.read"],+ "cacheDir": str(tmp_path),+ },+ "enabledTools": ["*"],+ }+ )+ auth = MCPServerAdapter("ibkr", cfg)._build_client().transport.auth++ def client_factory(**kwargs):+ return httpx.AsyncClient(+ transport=httpx.MockTransport(+ lambda request: httpx.Response(+ 301,+ headers={"Location": "https://api.ibkr.com/login"},+ request=request,+ )+ ),+ **kwargs,+ )++ auth.httpx_client_factory = client_factory+ with patch("webbrowser.open") as open_browser:+ asyncio.run(auth.redirect_handler("https://api.ibkr.com/oauth2/authorize"))++ open_browser.assert_called_once()+++def test_ibkr_oauth_refresh_uses_real_token_endpoint(tmp_path) -> None:+ cfg = MCPServerConfig.model_validate(+ {+ "type": "streamableHttp",+ "url": "https://api.ibkr.com/v1/api/mcp-public",+ "auth": {+ "type": "oauth",+ "scopes": ["mcp.read"],+ "cacheDir": str(tmp_path),+ },+ "enabledTools": ["*"],+ }+ )+ auth = MCPServerAdapter("ibkr", cfg)._build_client().transport.auth+ auth.context.client_info = OAuthClientInformationFull(+ client_id="client",+ redirect_uris=[AnyHttpUrl("http://localhost:8765/callback")],+ grant_types=["authorization_code", "refresh_token"],+ response_types=["code"],+ token_endpoint_auth_method="none",+ )+ auth.context.current_tokens = OAuthToken(+ access_token="expired",+ token_type="bearer",+ refresh_token="refresh",+ )++ request = asyncio.run(auth._refresh_token())++ assert str(request.url) == "https://api.ibkr.com/oauth2/api/v1/token"+++def test_ibkr_oauth_discards_registration_for_old_callback(tmp_path) -> None:+ cfg = MCPServerConfig.model_validate(+ {+ "type": "streamableHttp",+ "url": "https://api.ibkr.com/v1/api/mcp-public",+ "auth": {+ "type": "oauth",+ "scopes": ["mcp.read"],+ "cacheDir": str(tmp_path),+ },+ "enabledTools": ["*"],+ }+ )+ auth = MCPServerAdapter("ibkr", cfg)._build_client().transport.auth++ async def initialize():+ await auth.context.storage.set_client_info(+ OAuthClientInformationFull(+ client_id="stale-client",+ redirect_uris=[AnyHttpUrl("http://localhost:59999/callback")],+ grant_types=["authorization_code", "refresh_token"],+ response_types=["code"],+ token_endpoint_auth_method="none",+ )+ )+ await auth._initialize()+ return auth.context.client_info, await auth.context.storage.get_client_info()++ assert asyncio.run(initialize()) == (None, None)++def test_build_client_uses_explicit_init_timeout_without_widening_tool_timeout() -> None:cfg = MCPServerConfig.model_validate({