"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
refactor(mcp): keep the non-interactive OAuth guard, drop the IBKR-specific OAuth hacks from #1072
Haozhe Wu6e3a300d2b17
diff --git a/agent/src/config/schema.py b/agent/src/config/schema.pyindex 9442e85c5..8062dadeb 100644--- a/agent/src/config/schema.py+++ b/agent/src/config/schema.py@@ -226,8 +226,7 @@ ROBINHOOD_MCP_SERVER_SEED: dict[str, object] = {# config must pin an explicit tool allowlist plus pass the live order gate.IBKR_MCP_SERVER_SEED: dict[str, object] = {"type": "streamableHttp",- "url": "https://api.ibkr.com/v1/api/mcp-public",- "init_timeout": 300.0,+ "url": "https://api.ibkr.com/v1/api/mcp","auth": {"type": "oauth","scopes": ["mcp.read"],diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.pyindex 309d7a8b3..fb715fbf6 100644--- a/agent/src/tools/mcp.py+++ b/agent/src/tools/mcp.py@@ -4,18 +4,15 @@ from __future__ import annotationsimport asyncioimport hashlib-import httpximport jsonimport loggingimport osimport reimport threading-import webbrowserfrom collections.abc import Mappingfrom copy import deepcopyfrom dataclasses import dataclass, is_dataclassfrom typing import Any, Awaitable, Callable, Coroutine, Iterable, Protocol, TypeVar-from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplitimport httpxfrom fastmcp.client import Client@@ -34,7 +31,6 @@ 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@@ -98,95 +94,49 @@ def _fingerprint_auth(auth: MCPOAuthConfig | None) -> str:return _fingerprint(canonical)-class _RedirectCompatibleOAuth(OAuth):- """FastMCP OAuth with support for standard HTTP 301 authorization redirects."""+class _GuardedOAuth(OAuth):+ """FastMCP OAuth that can refuse to start a browser-based authorization flow.- _IBKR_USER_AGENT = (- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "- "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"- )+ Non-interactive callers (background pollers, API request handlers, scheduled+ jobs) must never have a browser window opened on the host on their behalf.+ Constructing this provider with ``allow_interactive=False`` turns the+ browser step into a loud ``RuntimeError`` so the caller can tell the user to+ run the explicit connect/reconnect step instead. With+ ``allow_interactive=True`` the provider behaves exactly like+ :class:`fastmcp.client.auth.OAuth`.+ """def __init__(self, *args: Any, allow_interactive: bool = True, **kwargs: Any) -> None:- super().__init__(*args, **kwargs)+ """Initialize the OAuth provider.++ Args:+ *args: Positional arguments forwarded to ``fastmcp``'s ``OAuth``.+ allow_interactive: When False, ``redirect_handler`` raises instead of+ opening a browser for user consent.+ **kwargs: Keyword arguments forwarded to ``fastmcp``'s ``OAuth``.+ """self._allow_interactive = allow_interactive+ super().__init__(*args, **kwargs)- def _pin_ibkr_oauth_metadata(self) -> None:- """Pin IBKR metadata before token refresh as well as initial consent."""- if (urlsplit(self.mcp_url).hostname or "").lower() != "api.ibkr.com":- return- self.context.auth_server_url = "https://api.ibkr.com/oauth2"- self.context.oauth_metadata = OAuthMetadata.model_validate(- {- "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",- "scopes_supported": ["mcp.read", "mcp.write"],- "response_types_supported": ["code"],- "grant_types_supported": ["authorization_code", "refresh_token"],- "token_endpoint_auth_methods_supported": ["none"],- "code_challenge_methods_supported": ["S256"],- }- )+ async def redirect_handler(self, authorization_url: str) -> None:+ """Hand the authorization URL to the user's browser, or refuse to.- async def _initialize(self) -> None:- await super()._initialize()- self._pin_ibkr_oauth_metadata()+ Args:+ authorization_url: Authorization endpoint URL built by the OAuth+ client for user consent.- async def async_auth_flow(self, request: httpx.Request):- """Add WAF-compatible headers to every request generated by OAuth."""- flow = super().async_auth_flow(request)- try:- outgoing = await flow.__anext__()- while True:- if (outgoing.url.host or "").lower() == "api.ibkr.com":- outgoing.headers["User-Agent"] = self._IBKR_USER_AGENT- outgoing.headers.setdefault("Accept", "application/json, text/html;q=0.9, */*;q=0.8")- incoming = yield outgoing- outgoing = await flow.asend(incoming)- except StopAsyncIteration:- return- finally:- await flow.aclose()+ Returns:+ None.- async def redirect_handler(self, authorization_url: str) -> None:+ Raises:+ RuntimeError: If this provider was built with+ ``allow_interactive=False``.+ """if not self._allow_interactive:- raise RuntimeError("OAuth reauthorization required; use the explicit reconnect action")- parsed = urlsplit(authorization_url)- if (parsed.hostname or "").lower() == "api.ibkr.com":- requested_scopes = (- list(self._scopes)- if isinstance(self._scopes, list)- else str(self._scopes or "").split()+ raise RuntimeError(+ "OAuth authorization required; run the interactive connect/reconnect step")- if requested_scopes != ["mcp.read"]:- raise RuntimeError("IBKR OAuth must request exactly the mcp.read scope")- params = dict(parse_qsl(parsed.query, keep_blank_values=True))- params["scope"] = "mcp.read"- authorization_url = urlunsplit(- (- parsed.scheme,- parsed.netloc,- "/oauth2/authorize",- urlencode(params),- "",- )- )- # IBKR's protected-resource discovery currently causes some MCP- # clients to fall back to root /authorize and /token endpoints.- # Pin the server's published OAuth2 metadata after discovery so the- # subsequent code exchange also uses the official token endpoint.- self._pin_ibkr_oauth_metadata()- async with self.httpx_client_factory() as client:- response = await client.get(authorization_url, follow_redirects=False)- if response.status_code == 400:- raise RuntimeError("OAuth client not found; re-register the client")- if response.status_code not in (200, 301, 302, 303, 307, 308):- raise RuntimeError(- f"Unexpected authorization response: {response.status_code}"- )- logger.info("OAuth authorization URL: %s", authorization_url)- webbrowser.open(authorization_url)+ await super().redirect_handler(authorization_url)def _make_cache_key(server_name: str, server_config: "MCPServerConfig") -> tuple[str, ...]:@@ -531,6 +481,9 @@ class MCPServerAdapter:Defaults to 2 (one transient retry). The authorize bootstrapsets this to 1 so a retry cannot start a second OAuth callbackserver and orphan an in-progress sign-in.+ interactive_oauth: When False, an OAuth flow that needs fresh user+ consent raises instead of opening a browser on the host. Callers+ that run without a user in front of them pass False."""self.server_name = server_nameself.local_server_name = local_server_name or server_name@@ -650,6 +603,10 @@ class MCPServerAdapter:auth = Noneif self.server_config.auth is not None:oauth_config = self.server_config.auth+ # fastmcp's OAuth pre-flights the authorization URL with a+ # client built by `httpx_client_factory`; httpx defaults that to+ # a 5 s deadline, which is short for a consent endpoint. Reuse+ # the server's configured init_timeout instead.oauth_http_timeout = (self.server_config.init_timeoutif self.server_config.init_timeout is not None@@ -660,7 +617,7 @@ 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 = _RedirectCompatibleOAuth(+ auth = _GuardedOAuth(scopes=list(oauth_config.scopes) or None,client_name=oauth_config.client_name,token_storage=_build_token_store(oauth_config.cache_dir),diff --git a/agent/src/trading/connectors/ibkr/mcp.py b/agent/src/trading/connectors/ibkr/mcp.pydeleted file mode 100644index a83a6e13c..000000000--- a/agent/src/trading/connectors/ibkr/mcp.py+++ /dev/null@@ -1,82 +0,0 @@-"""IBKR official MCP mappings for the generic read-only trading service."""--from __future__ import annotations--from typing import Any--_REMOTE_TOOL_NAMES = {- "account": "get_account_summary",- "positions": "get_account_positions",- "orders": "get_account_orders",-}---def remote_tool_name(operation: str) -> str | None:- """Return the official IBKR tool for a generic read operation."""- return _REMOTE_TOOL_NAMES.get(operation)---def remote_arguments(operation: str, arguments: dict[str, Any]) -> dict[str, Any]:- """IBKR's account read tools operate on the authorized account implicitly."""- return {}---def normalize_result(operation: str, result: dict[str, Any]) -> dict[str, Any]:- """Convert official IBKR MCP responses to Vibe-Trading's read shapes."""- status = str(result.get("status") or "ok").lower()- if status in {"error", "failed", "not_authorized"}:- return result-- payload = result.get("data")- if not isinstance(payload, dict):- payload = result.get("structured_content")- if not isinstance(payload, dict):- payload = {}-- if operation == "account":- currency = str(payload.get("currency") or "USD").upper()- tags = {- "NetLiquidation": "net_liquidation",- "EquityWithLoanValue": "equity_with_loan_value",- "BuyingPower": "buying_power",- "GrossPositionValue": "gross_position_value",- "TotalCashValue": "total_cash_value",- "AvailableFunds": "available_funds",- "InitialMarginReq": "initial_margin",- "MaintMarginReq": "maintenance_margin",- "ExcessLiquidity": "excess_liquidity",- }- summary = [- {"tag": tag, "value": payload[key], "currency": currency}- for tag, key in tags.items()- if payload.get(key) is not None- ]- return {"status": "ok", "summary": summary, **payload}-- if operation == "positions":- positions = []- for item in payload.get("positions") or []:- if not isinstance(item, dict):- continue- description = str(item.get("contract_description") or "").strip()- positions.append(- {- "contract_id": item.get("contract_id"),- "symbol": description,- "local_symbol": description,- "position": item.get("position"),- "market_price": item.get("market_price"),- "market_value": item.get("market_value"),- "currency": item.get("currency") or "USD",- "avg_cost": item.get("average_price"),- "unrealized_pnl": item.get("unrealized_pnl"),- "sec_type": item.get("asset_class") or "STK",- "asset_class": item.get("asset_class"),- }- )- return {"status": "ok", "positions": positions}-- if operation == "orders":- return {"status": "ok", "orders": payload.get("orders") or []}-- return resultdiff --git a/agent/src/trading/connectors/ibkr/profiles.py b/agent/src/trading/connectors/ibkr/profiles.pyindex b73cc4576..f27a377f5 100644--- a/agent/src/trading/connectors/ibkr/profiles.py+++ b/agent/src/trading/connectors/ibkr/profiles.py@@ -37,8 +37,8 @@ IBKR_PROFILES: tuple[TradingProfile, ...] = (readonly=True,config={"server": "ibkr"},notes=(- "Uses IBKR's official public MCP endpoint with OAuth mcp.read scope only. "- "No TWS or IB Gateway process is required."+ "Requires IBKR official MCP OAuth approval. Generic account/position tools "+ "stay disabled until IBKR publishes stable read tool names."),),)diff --git a/agent/src/trading/service.py b/agent/src/trading/service.pyindex 626bb290e..7236ea33b 100644--- a/agent/src/trading/service.py+++ b/agent/src/trading/service.py@@ -1230,7 +1230,23 @@ def _call_remote(*,interactive_oauth: bool = True,) -> dict[str, Any]:- """Call a known read operation on a remote MCP connector profile."""+ """Call a known read operation on a remote MCP connector profile.++ Args:+ profile: Connector profile whose ``transport`` is a remote MCP server.+ operation: Logical read operation ("account", "positions", "orders",+ "quote"); mapped to a connector-specific remote tool name.+ arguments: Logical arguments for the operation, before the+ connector-specific wire mapping is applied.+ interactive_oauth: When False, an expired or missing OAuth grant raises+ instead of opening a browser on the host. Callers that run without a+ user in front of them (API handlers, schedulers, portfolio refresh)+ pass False.++ Returns:+ The remote tool envelope with profile metadata attached, or an error /+ ``not_authorized`` envelope when the profile cannot be called.+ """from src.config.loader import load_agent_configfrom src.live.registry import has_cached_oauth_tokenfrom src.tools.mcp import MCPServerAdapter@@ -1286,16 +1302,14 @@ def _call_remote(),}+ # The interactive default is left implicit so the common path keeps the+ # two-positional-argument construction that adapter substitutes rely on.adapter = (MCPServerAdapter(server_name, server)if interactive_oauthelse MCPServerAdapter(server_name, server, interactive_oauth=False))call_result = adapter.call_tool(remote_name, _remote_arguments(profile.connector, operation, arguments))- if profile.connector == "ibkr":- from src.trading.connectors.ibkr.mcp import normalize_result-- call_result = normalize_result(operation, call_result)account_number = arguments.get("account_number")if account_number:call_result = dict(call_result)@@ -1308,10 +1322,6 @@ def _remote_tool_name(connector: str, operation: str) -> str | None:if connector == "robinhood":from src.trading.connectors.robinhood.mcp import remote_tool_name- return remote_tool_name(operation)- if connector == "ibkr":- from src.trading.connectors.ibkr.mcp import remote_tool_name-return remote_tool_name(operation)return None@@ -1321,10 +1331,6 @@ def _remote_arguments(connector: str, operation: str, arguments: dict[str, Any])if connector == "robinhood":from src.trading.connectors.robinhood.mcp import remote_arguments- return remote_arguments(operation, arguments)- if connector == "ibkr":- from src.trading.connectors.ibkr.mcp import remote_arguments-return remote_arguments(operation, arguments)return {}diff --git a/agent/tests/test_ibkr_mcp_adapter.py b/agent/tests/test_ibkr_mcp_adapter.pydeleted file mode 100644index 9fc043638..000000000--- a/agent/tests/test_ibkr_mcp_adapter.py+++ /dev/null@@ -1,57 +0,0 @@-from src.trading.connectors.ibkr.mcp import (- normalize_result,- remote_arguments,- remote_tool_name,-)---def test_ibkr_read_tool_mapping_has_no_write_tools():- assert remote_tool_name("account") == "get_account_summary"- assert remote_tool_name("positions") == "get_account_positions"- assert remote_tool_name("orders") == "get_account_orders"- assert remote_tool_name("quote") is None- assert remote_tool_name("submit_order") is None- assert remote_arguments("positions", {"account_number": "ignored"}) == {}---def test_normalizes_account_summary_and_positions():- account = normalize_result(- "account",- {- "status": "ok",- "data": {- "currency": "USD",- "net_liquidation": 1234.5,- "buying_power": 100,- },- },- )- assert account["summary"][0] == {- "tag": "NetLiquidation",- "value": 1234.5,- "currency": "USD",- }-- positions = normalize_result(- "positions",- {- "status": "ok",- "data": {- "positions": [- {- "contract_id": 42,- "contract_description": "AAPL",- "position": 2,- "market_price": 150,- "market_value": 300,- "currency": "USD",- "average_price": 100,- "unrealized_pnl": 100,- "asset_class": "STK",- }- ]- },- },- )- assert positions["positions"][0]["symbol"] == "AAPL"- assert positions["positions"][0]["market_price"] == 150diff --git a/agent/tests/test_ibkr_mcp_seed.py b/agent/tests/test_ibkr_mcp_seed.pyindex bb5d0861c..4e3d8f27a 100644--- a/agent/tests/test_ibkr_mcp_seed.py+++ b/agent/tests/test_ibkr_mcp_seed.py@@ -65,8 +65,7 @@ def test_ibkr_seed_validates_as_readonly_probe() -> None:cfg = AgentConfig.model_validate({"mcpServers": {"ibkr": IBKR_MCP_SERVER_SEED}})server = cfg.mcp_servers["ibkr"]- assert server.url == "https://api.ibkr.com/v1/api/mcp-public"- assert server.init_timeout == 300.0+ assert server.url == "https://api.ibkr.com/v1/api/mcp"assert server.auth is not Noneassert server.auth.scopes == ["mcp.read"]assert server.enabled_tools == ["*"]@@ -89,4 +88,4 @@ def test_ibkr_alias_url_resolves_to_live_broker_and_wraps_writes() -> None:def test_ibkr_lookalike_host_is_not_live_broker() -> None:- assert not is_live_broker("ib", "https://api.ibkr.com.evil.test/v1/api/mcp-public")+ assert not is_live_broker("ib", "https://api.ibkr.com.evil.test/v1/api/mcp")diff --git a/agent/tests/test_mcp_oauth_noninteractive.py b/agent/tests/test_mcp_oauth_noninteractive.pynew file mode 100644index 000000000..ad0afcc57--- /dev/null+++ b/agent/tests/test_mcp_oauth_noninteractive.py@@ -0,0 +1,153 @@+"""Unit tests for the non-interactive OAuth guard on ``MCPServerAdapter``.++Covers:++* ``MCPServerAdapter(..., interactive_oauth=False)`` builds an OAuth provider+ whose ``redirect_handler`` raises instead of opening a browser, and never+ performs the pre-flight HTTP probe either.+* The default (``interactive_oauth=True``) keeps ``fastmcp``'s own behaviour:+ pre-flight the authorization URL, then hand it to the browser.+"""++from __future__ import annotations++import asyncio+import webbrowser++import pytest+from fastmcp.client.auth import OAuth++from src.config.schema import MCPServerConfig++pytestmark = pytest.mark.unit+++class _StubResponse:+ """Minimal stand-in for the pre-flight authorization response."""++ status_code = 302+++class _StubHTTPClient:+ """Async-context httpx stand-in that records the pre-flight request."""++ requests: list[str] = []++ async def __aenter__(self) -> "_StubHTTPClient":+ """Enter the async context.++ Returns:+ This client.+ """+ return self++ async def __aexit__(self, exc_type, exc, tb) -> None:+ """Leave the async context.++ Args:+ exc_type: Exception type raised inside the block, if any.+ exc: Exception instance raised inside the block, if any.+ tb: Traceback for the raised exception, if any.++ Returns:+ None.+ """+ return None++ async def get(self, url: str, follow_redirects: bool = False) -> _StubResponse:+ """Record the pre-flight GET and return a redirect response.++ Args:+ url: Authorization URL being probed.+ follow_redirects: Whether the caller wants redirects followed.++ Returns:+ A stub response carrying HTTP 302.+ """+ _StubHTTPClient.requests.append(url)+ return _StubResponse()+++class _ExplodingHTTPClient:+ """httpx stand-in that fails loudly if any HTTP call is attempted."""++ async def __aenter__(self) -> "_ExplodingHTTPClient":+ """Fail as soon as an HTTP client is opened.++ Raises:+ AssertionError: Always.+ """+ raise AssertionError("non-interactive OAuth must not make HTTP requests")++ async def __aexit__(self, exc_type, exc, tb) -> None:+ """Unreachable; the context is never entered successfully.++ Args:+ exc_type: Exception type raised inside the block, if any.+ exc: Exception instance raised inside the block, if any.+ tb: Traceback for the raised exception, if any.++ Returns:+ None.+ """+ return None+++def _oauth_provider(tmp_path, *, interactive: bool) -> OAuth:+ """Build the OAuth provider an adapter would attach to its transport.++ Args:+ tmp_path: Pytest tmp dir used as the OAuth token cache root.+ interactive: Value for the adapter's ``interactive_oauth`` flag.++ Returns:+ The ``OAuth`` instance wired onto the streamable-HTTP transport.+ """+ from src.tools.mcp import MCPServerAdapter++ cfg = MCPServerConfig.model_validate(+ {+ "type": "streamableHttp",+ "url": "https://agent.robinhood.com/mcp/trading",+ "auth": {+ "type": "oauth",+ "scopes": ["trading.read"],+ "client_name": "Vibe-Trading",+ "cache_dir": str(tmp_path / "oauth"),+ "client_id": "client-id",+ },+ }+ )+ adapter = MCPServerAdapter("robinhood", cfg, interactive_oauth=interactive)+ auth = adapter._build_client().transport.auth+ assert isinstance(auth, OAuth)+ return auth+++def test_noninteractive_adapter_refuses_to_open_a_browser(tmp_path, monkeypatch) -> None:+ def _boom(url: str) -> bool:+ raise AssertionError(f"webbrowser.open must not be called, got {url}")++ monkeypatch.setattr(webbrowser, "open", _boom)++ auth = _oauth_provider(tmp_path, interactive=False)+ auth.httpx_client_factory = _ExplodingHTTPClient++ with pytest.raises(RuntimeError, match="connect/reconnect"):+ asyncio.run(auth.redirect_handler("https://agent.robinhood.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)+ _StubHTTPClient.requests = []++ auth = _oauth_provider(tmp_path, interactive=True)+ auth.httpx_client_factory = _StubHTTPClient++ url = "https://agent.robinhood.com/oauth2/authorize?x=1"+ asyncio.run(auth.redirect_handler(url))++ # The URL is passed through untouched: no provider-specific rewriting.+ assert opened == [url]+ assert _StubHTTPClient.requests == [url]diff --git a/agent/tests/test_mcp_oauth_schema.py b/agent/tests/test_mcp_oauth_schema.pyindex 82b3391e8..d2a812d5d 100644--- a/agent/tests/test_mcp_oauth_schema.py+++ b/agent/tests/test_mcp_oauth_schema.py@@ -15,9 +15,6 @@ Covers:from __future__ import annotations-import asyncio-from urllib.parse import parse_qs, urlsplit-import pytestfrom fastmcp.client.auth import OAuthfrom fastmcp.client.transports.http import StreamableHttpTransport@@ -34,8 +31,7 @@ from src.config.schema import (MCPServerConfig,MCPServerConfigOverride,)-from src.tools import mcp as mcp_module-from src.tools.mcp import MCPServerAdapter, _RedirectCompatibleOAuth+from src.tools.mcp import MCPServerAdapterpytestmark = pytest.mark.unit@@ -131,8 +127,7 @@ def test_ibkr_seed_is_official_readonly_oauth_probe() -> None:cfg = AgentConfig.model_validate({"mcpServers": {"ibkr": IBKR_MCP_SERVER_SEED}})ibkr = cfg.mcp_servers["ibkr"]assert ibkr.resolved_transport() == "streamableHttp"- assert ibkr.url == "https://api.ibkr.com/v1/api/mcp-public"- assert ibkr.init_timeout == 300.0+ assert ibkr.url == "https://api.ibkr.com/v1/api/mcp"assert ibkr.auth is not None and ibkr.auth.type == "oauth"assert ibkr.auth.scopes == ["mcp.read"]assert ibkr.auth.cache_dir == "~/.vibe-trading/live/ibkr/oauth"@@ -140,62 +135,6 @@ def test_ibkr_seed_is_official_readonly_oauth_probe() -> None:assert "ibkr" in LIVE_BROKER_SERVER_KEYS-def test_ibkr_oauth_redirect_pins_official_endpoint_and_read_scope(monkeypatch) -> None:- opened: list[str] = []-- class Response:- status_code = 302-- class Client:- async def __aenter__(self):- return self-- async def __aexit__(self, exc_type, exc, tb):- return None-- async def get(self, url, follow_redirects=False):- assert follow_redirects is False- return Response()-- oauth = _RedirectCompatibleOAuth(- mcp_url="https://api.ibkr.com/v1/api/mcp-public",- scopes=["mcp.read"],- client_id="client-id",- callback_port=8765,- httpx_client_factory=Client,- )- monkeypatch.setattr(mcp_module.webbrowser, "open", opened.append)-- asyncio.run(- oauth.redirect_handler(- "https://api.ibkr.com/authorize/?response_type=code&scope=mcp.read%20mcp.write"- )- )-- parsed = urlsplit(opened[0])- assert parsed.path == "/oauth2/authorize"- assert parse_qs(parsed.query)["scope"] == ["mcp.read"]- assert str(oauth.context.oauth_metadata.token_endpoint) == (- "https://api.ibkr.com/oauth2/api/v1/token"- )---def test_noninteractive_oauth_refuses_browser_reauthorization(monkeypatch) -> None:- opened: list[str] = []- oauth = _RedirectCompatibleOAuth(- mcp_url="https://api.ibkr.com/v1/api/mcp-public",- scopes=["mcp.read"],- client_id="client-id",- allow_interactive=False,- )- monkeypatch.setattr(mcp_module.webbrowser, "open", opened.append)-- with pytest.raises(RuntimeError, match="explicit reconnect"):- asyncio.run(oauth.redirect_handler("https://api.ibkr.com/oauth2/authorize"))-- assert opened == []--# --------------------------------------------------------------------------- ## Validator rejections# --------------------------------------------------------------------------- #diff --git a/agent/tests/test_trading_connections.py b/agent/tests/test_trading_connections.pyindex 8e808c029..96c526105 100644--- a/agent/tests/test_trading_connections.py+++ b/agent/tests/test_trading_connections.py@@ -50,14 +50,14 @@ def test_remote_call_requires_cached_oauth(monkeypatch: pytest.MonkeyPatch) -> Nassert "connector authorize robinhood-live-mcp" in result["error"]-def test_ibkr_official_profile_maps_verified_reads_without_write_tools() -> None:- """IBKR official MCP maps only the read tools verified by the adapter."""+def test_ibkr_official_profile_does_not_advertise_unknown_generic_reads() -> None:+ """IBKR official MCP stays honest until stable remote tool names are known."""profile = profiles.profile_by_id("ibkr-live-official-mcp-readonly")assert profile.capabilities == ("mcp.read.discovery",)- assert service._remote_tool_name("ibkr", "account") == "get_account_summary"- assert service._remote_tool_name("ibkr", "positions") == "get_account_positions"- assert service._remote_tool_name("ibkr", "place_order") is None+ result = service.get_account(profile.id)+ assert result["status"] == "error"+ assert "does not support" in result["error"]def test_connector_profile_id_for_broker_prefers_live_remote_mcp() -> None: