Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(ibkr): support official MCP OAuth and reads

Yang5289f47d4b69
diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.py
index fb715fbf6..39f9881ca 100644
--- a/agent/src/tools/mcp.py
+++ b/agent/src/tools/mcp.py
@@ -9,14 +9,17 @@ import logging
import os
import re
import threading
-from collections.abc import Mapping
+import webbrowser
+from collections.abc import AsyncGenerator, Mapping
from copy import deepcopy
from dataclasses import dataclass, is_dataclass
from typing import Any, Awaitable, Callable, Coroutine, Iterable, Protocol, TypeVar
+from urllib.parse import urlparse
import httpx
from fastmcp.client import Client
from fastmcp.client.auth import OAuth
+from fastmcp.client.auth.oauth import ClientNotFoundError
from fastmcp.client.client import CallToolResult
try:
from fastmcp.client.transports.http import StreamableHttpTransport
@@ -31,6 +34,7 @@ except ModuleNotFoundError:
from fastmcp.exceptions import McpError, ToolError
from key_value.aio.stores.filetree import FileTreeStore, FileTreeV1KeySanitizationStrategy
from mcp import types as mcp_types
+from mcp.shared.auth import OAuthMetadata
from pydantic_core import PydanticSerializationError, to_jsonable_python
from 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/src/trading/connectors/ibkr/mcp.py b/agent/src/trading/connectors/ibkr/mcp.py
new file mode 100644
index 000000000..1c96be47c
--- /dev/null
+++ b/agent/src/trading/connectors/ibkr/mcp.py
@@ -0,0 +1,74 @@
+"""IBKR official MCP mapping for generic read-only trading operations."""
+
+from __future__ import annotations
+
+from typing import Any
+
+_REMOTE_TOOL_NAMES = {
+ "account": "get_account_summary",
+ "positions": "get_account_positions",
+}
+
+_ACCOUNT_TAGS = {
+ "net_liquidation": "NetLiquidation",
+ "equity_with_loan_value": "EquityWithLoanValue",
+ "buying_power": "BuyingPower",
+ "gross_position_value": "GrossPositionValue",
+ "total_cash_value": "TotalCashValue",
+ "available_funds": "AvailableFunds",
+ "initial_margin": "InitMarginReq",
+ "maintenance_margin": "MaintMarginReq",
+ "excess_liquidity": "ExcessLiquidity",
+ "dividends": "AccruedCash",
+ "leverage": "Leverage",
+}
+
+
+def remote_tool_name(operation: str) -> str | None:
+ """Return the verified IBKR public MCP tool for a generic operation."""
+ return _REMOTE_TOOL_NAMES.get(operation)
+
+
+def remote_arguments(operation: str, arguments: dict[str, Any]) -> dict[str, Any]:
+ """Return IBKR's argument-free account/position request payload."""
+ if operation in _REMOTE_TOOL_NAMES:
+ return {}
+ return dict(arguments)
+
+
+def normalize_result(operation: str, result: dict[str, Any]) -> dict[str, Any]:
+ """Translate IBKR's structured MCP result into the shared broker shapes."""
+ normalized = dict(result)
+ structured = result.get("structured_content")
+ if not isinstance(structured, dict):
+ return normalized
+
+ if operation == "account":
+ currency = str(structured.get("currency") or "USD").upper()
+ normalized["summary"] = [
+ {"tag": tag, "value": structured.get(key), "currency": currency}
+ for key, tag in _ACCOUNT_TAGS.items()
+ if structured.get(key) is not None
+ ]
+ return normalized
+
+ if operation == "positions":
+ rows = structured.get("positions")
+ if not isinstance(rows, list):
+ return normalized
+ normalized["positions"] = [
+ {
+ "contract_id": row.get("contract_id"),
+ "symbol": row.get("contract_description"),
+ "position": row.get("position"),
+ "market_price": row.get("market_price"),
+ "market_value": row.get("market_value"),
+ "currency": row.get("currency"),
+ "avg_cost": row.get("average_price"),
+ "unrealized_pnl": row.get("unrealized_pnl"),
+ "sec_type": row.get("asset_class"),
+ }
+ for row in rows
+ if isinstance(row, dict)
+ ]
+ return normalized
diff --git a/agent/src/trading/connectors/ibkr/profiles.py b/agent/src/trading/connectors/ibkr/profiles.py
index f27a377f5..72a08d16e 100644
--- a/agent/src/trading/connectors/ibkr/profiles.py
+++ b/agent/src/trading/connectors/ibkr/profiles.py
@@ -33,12 +33,12 @@ IBKR_PROFILES: tuple[TradingProfile, ...] = (
label="IBKR Live · Official MCP Read-Only",
environment="live",
transport="remote_mcp",
- capabilities=("mcp.read.discovery",),
+ capabilities=("account.read", "positions.read"),
readonly=True,
config={"server": "ibkr"},
notes=(
- "Requires IBKR official MCP OAuth approval. Generic account/position tools "
- "stay disabled until IBKR publishes stable read tool names."
+ "Requires IBKR official MCP OAuth approval. Uses the verified "
+ "get_account_summary and get_account_positions read-only tools."
),
),
)
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index 7236ea33b..6397abb4e 100644
--- a/agent/src/trading/service.py
+++ b/agent/src/trading/service.py
@@ -1310,6 +1310,7 @@ def _call_remote(
else MCPServerAdapter(server_name, server, interactive_oauth=False)
)
call_result = adapter.call_tool(remote_name, _remote_arguments(profile.connector, operation, arguments))
+ call_result = _normalize_remote_result(profile.connector, operation, call_result)
account_number = arguments.get("account_number")
if account_number:
call_result = dict(call_result)
@@ -1319,6 +1320,10 @@ def _call_remote(
def _remote_tool_name(connector: str, operation: str) -> str | None:
"""Map generic read operations to current remote MCP tool names."""
+ if connector == "ibkr":
+ from src.trading.connectors.ibkr.mcp import remote_tool_name
+
+ return remote_tool_name(operation)
if connector == "robinhood":
from src.trading.connectors.robinhood.mcp import remote_tool_name
@@ -1328,6 +1333,10 @@ def _remote_tool_name(connector: str, operation: str) -> str | None:
def _remote_arguments(connector: str, operation: str, arguments: dict[str, Any]) -> dict[str, Any]:
"""Normalize generic arguments for a remote MCP operation."""
+ if connector == "ibkr":
+ from src.trading.connectors.ibkr.mcp import remote_arguments
+
+ return remote_arguments(operation, arguments)
if connector == "robinhood":
from src.trading.connectors.robinhood.mcp import remote_arguments
@@ -1335,6 +1344,17 @@ def _remote_arguments(connector: str, operation: str, arguments: dict[str, Any])
return {}
+def _normalize_remote_result(
+ connector: str, operation: str, result: dict[str, Any]
+) -> dict[str, Any]:
+ """Map connector-specific MCP envelopes into shared read payloads."""
+ if connector == "ibkr":
+ from src.trading.connectors.ibkr.mcp import normalize_result
+
+ return normalize_result(operation, result)
+ return result
+
+
def _unsupported(profile: TradingProfile, capability: str) -> dict[str, Any]:
"""Return a standard unsupported-capability payload."""
return {
diff --git a/agent/tests/test_ibkr_mcp_mapping.py b/agent/tests/test_ibkr_mcp_mapping.py
new file mode 100644
index 000000000..03680b9c7
--- /dev/null
+++ b/agent/tests/test_ibkr_mcp_mapping.py
@@ -0,0 +1,77 @@
+"""Tests for the verified IBKR public MCP generic read mapping."""
+
+from __future__ import annotations
+
+import pytest
+
+from src.trading.connectors.ibkr.mcp import (
+ normalize_result,
+ remote_arguments,
+ remote_tool_name,
+)
+
+pytestmark = pytest.mark.unit
+
+
+def test_ibkr_remote_tools_map_only_verified_reads() -> None:
+ assert remote_tool_name("account") == "get_account_summary"
+ assert remote_tool_name("positions") == "get_account_positions"
+ assert remote_tool_name("orders") is None
+ assert remote_arguments("account", {"account_number": "ignored"}) == {}
+
+
+def test_ibkr_account_summary_normalizes_for_portfolio_totals() -> None:
+ result = normalize_result(
+ "account",
+ {
+ "status": "ok",
+ "structured_content": {
+ "currency": "USD",
+ "net_liquidation": 123.45,
+ "total_cash_value": 12.34,
+ },
+ },
+ )
+
+ assert result["summary"] == [
+ {"tag": "NetLiquidation", "value": 123.45, "currency": "USD"},
+ {"tag": "TotalCashValue", "value": 12.34, "currency": "USD"},
+ ]
+
+
+def test_ibkr_positions_normalize_for_shared_position_reader() -> None:
+ result = normalize_result(
+ "positions",
+ {
+ "status": "ok",
+ "structured_content": {
+ "positions": [
+ {
+ "contract_id": 1,
+ "contract_description": "EXAMPLE",
+ "position": 2.0,
+ "market_price": 10.0,
+ "market_value": 20.0,
+ "currency": "USD",
+ "average_price": 8.0,
+ "unrealized_pnl": 4.0,
+ "asset_class": "STK",
+ }
+ ]
+ },
+ },
+ )
+
+ assert result["positions"] == [
+ {
+ "contract_id": 1,
+ "symbol": "EXAMPLE",
+ "position": 2.0,
+ "market_price": 10.0,
+ "market_value": 20.0,
+ "currency": "USD",
+ "avg_cost": 8.0,
+ "unrealized_pnl": 4.0,
+ "sec_type": "STK",
+ }
+ ]
diff --git a/agent/tests/test_local_connections_hardening.py b/agent/tests/test_local_connections_hardening.py
index fab806b96..d29d308ad 100644
--- a/agent/tests/test_local_connections_hardening.py
+++ b/agent/tests/test_local_connections_hardening.py
@@ -22,6 +22,7 @@ from src.trading.credentials import CredentialStore
from src.trading.local_plugins import clear_plugin_cache, discover_plugins
from src.trading.plugin_scaffold import scaffold_connector
from src.trading.profiles import profile_by_id
+from src.trading.types import TradingProfile
ROOT = Path(__file__).resolve().parents[2]
AGENT_DIR = ROOT / "agent"
@@ -222,9 +223,21 @@ def test_discovery_of_a_new_plugin_invalidates_the_cached_result(tmp_path) -> No
# ---------------------------------------------------------------------------
-def test_discovery_only_profile_cannot_back_a_portfolio_connection(tmp_path) -> None:
+def test_discovery_only_profile_cannot_back_a_portfolio_connection(
+ tmp_path, monkeypatch
+) -> None:
"""A tool-discovery profile cannot serve account or position reads."""
- profile = profile_by_id("ibkr-live-official-mcp-readonly")
+ profile = TradingProfile(
+ id="discovery-only-test",
+ connector="test",
+ label="Discovery only",
+ environment="live",
+ transport="remote_mcp",
+ capabilities=("mcp.read.discovery",),
+ readonly=True,
+ config={"server": "test"},
+ )
+ monkeypatch.setattr("src.trading.connections.profile_by_id", lambda _: profile)
assert profile.readonly is True
assert profile.capabilities == ("mcp.read.discovery",)
assert is_portfolio_connection_profile(profile) is False
diff --git a/agent/tests/test_mcp_oauth_noninteractive.py b/agent/tests/test_mcp_oauth_noninteractive.py
index 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.auth
assert 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.py
index 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 httpx
import pytest
from fastmcp.client.auth import OAuth
from fastmcp.client.transports.http import StreamableHttpTransport
from fastmcp.client.transports.sse import SSETransport
from 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, ValidationError
from 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(
{
diff --git a/agent/tests/test_portfolio_config.py b/agent/tests/test_portfolio_config.py
index 8c0fe240d..d407d9d28 100644
--- a/agent/tests/test_portfolio_config.py
+++ b/agent/tests/test_portfolio_config.py
@@ -12,6 +12,7 @@ from src.portfolio.config import (
)
from src.trading.connections import ConnectionStore
from src.trading.profiles import profile_by_id
+from src.trading.types import TradingProfile
def test_portfolio_settings_round_trip_without_credentials(tmp_path):
@@ -67,14 +68,31 @@ def test_new_install_starts_with_no_selected_sources(tmp_path):
assert store.load().sources == ()
-def test_a_discovery_only_profile_cannot_back_a_portfolio_source():
+def test_a_discovery_only_profile_cannot_back_a_portfolio_source(
+ monkeypatch, tmp_path
+):
"""Tool discovery is not a holdings read, so such a profile is not eligible.
- ``ibkr-live-official-mcp-readonly`` is read-only, but it declares only
- ``mcp.read.discovery``: it can list the remote server's tools and nothing
- else. Accepting it would create a source that fails on every refresh.
+ A remote profile can be read-only yet expose discovery and no holdings
+ reads. Accepting it would create a source that fails on every refresh.
"""
- profile = profile_by_id("ibkr-live-official-mcp-readonly")
+ profile = TradingProfile(
+ id="discovery-only-test",
+ connector="test",
+ label="Discovery only",
+ environment="live",
+ transport="remote_mcp",
+ capabilities=("mcp.read.discovery",),
+ readonly=True,
+ config={"server": "test"},
+ )
+ original_profile_by_id = profile_by_id
+
+ def lookup(profile_id):
+ return profile if profile_id == profile.id else original_profile_by_id(profile_id)
+
+ monkeypatch.setattr("src.portfolio.config.profile_by_id", lookup)
+ monkeypatch.setattr("src.trading.connections.profile_by_id", lookup)
assert profile.readonly is True
assert profile.capabilities == ("mcp.read.discovery",)
assert profile not in eligible_profiles()
@@ -91,10 +109,10 @@ def test_a_discovery_only_profile_cannot_back_a_portfolio_source():
"sources": [
{
"id": "discovery-only",
- "profile_id": "ibkr-live-official-mcp-readonly",
+ "profile_id": profile.id,
"label": "Discovery only",
}
],
},
- ConnectionStore(),
+ ConnectionStore(tmp_path / "connections.json"),
)
diff --git a/agent/tests/test_trading_connections.py b/agent/tests/test_trading_connections.py
index 96c526105..ad25c6a7b 100644
--- a/agent/tests/test_trading_connections.py
+++ b/agent/tests/test_trading_connections.py
@@ -50,14 +50,48 @@ def test_remote_call_requires_cached_oauth(monkeypatch: pytest.MonkeyPatch) -> N
assert "connector authorize robinhood-live-mcp" in result["error"]
-def test_ibkr_official_profile_does_not_advertise_unknown_generic_reads() -> None:
- """IBKR official MCP stays honest until stable remote tool names are known."""
+def test_ibkr_official_profile_advertises_verified_portfolio_reads(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """The real-account-verified IBKR tools back the shared read interface."""
profile = profiles.profile_by_id("ibkr-live-official-mcp-readonly")
+ calls: list[tuple[str, dict]] = []
+ server = SimpleNamespace(
+ url="https://api.ibkr.com/v1/api/mcp-public",
+ enabled_tools=["get_account_summary", "get_account_positions"],
+ auth=SimpleNamespace(cache_dir="/tmp/vibe-token"),
+ )
- assert profile.capabilities == ("mcp.read.discovery",)
- result = service.get_account(profile.id)
- assert result["status"] == "error"
- assert "does not support" in result["error"]
+ class _Adapter:
+ def __init__(self, server_name, server_config): # noqa: ANN001
+ assert server_name == "ibkr"
+ assert server_config is server
+
+ def call_tool(self, remote_name, arguments): # noqa: ANN001
+ calls.append((remote_name, dict(arguments)))
+ return {
+ "status": "ok",
+ "structured_content": (
+ {"currency": "USD", "net_liquidation": 100}
+ if remote_name == "get_account_summary"
+ else {"positions": []}
+ ),
+ }
+
+ monkeypatch.setattr(
+ "src.config.loader.load_agent_config",
+ lambda: SimpleNamespace(mcp_servers={"ibkr": server}),
+ )
+ monkeypatch.setattr("src.live.registry.has_cached_oauth_token", lambda *_: True)
+ monkeypatch.setattr("src.tools.mcp.MCPServerAdapter", _Adapter)
+
+ assert profile.capabilities == ("account.read", "positions.read")
+ assert service.get_account(profile.id)["summary"][0]["tag"] == "NetLiquidation"
+ assert service.get_positions(profile.id)["positions"] == []
+ assert calls == [
+ ("get_account_summary", {}),
+ ("get_account_positions", {}),
+ ]
def test_connector_profile_id_for_broker_prefers_live_remote_mcp() -> None: