Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix: clearer Robinhood agent.json validation and safe seed config surfacing

Matt Van Horn9a9e4da5b2f2
diff --git a/agent/cli/_legacy.py b/agent/cli/_legacy.py
index 5d9524fd4..b2c0c626b 100644
--- a/agent/cli/_legacy.py
+++ b/agent/cli/_legacy.py
@@ -2779,6 +2779,66 @@ def _live_server_config(broker: str):
return servers.get(broker.strip().lower())
+def _raw_live_server_config_entry(broker: str) -> dict[str, Any] | None:
+ """Best-effort raw lookup used only to explain invalid live config."""
+ from src.config.loader import _read_config_file
+ from src.config.paths import get_config_path
+ from src.config.schema import live_broker_key_for_url
+
+ try:
+ path = get_config_path()
+ if not path.exists():
+ return None
+ raw = _read_config_file(path)
+ except Exception: # noqa: BLE001 — diagnostics must not mask the real CLI error
+ return None
+
+ servers = raw.get("mcpServers")
+ if not isinstance(servers, dict):
+ servers = raw.get("mcp_servers")
+ if not isinstance(servers, dict):
+ return None
+
+ key = broker.strip().lower()
+ for server_key, server in servers.items():
+ if isinstance(server, dict) and str(server_key).strip().lower() == key:
+ return server
+
+ if key != "robinhood":
+ return None
+
+ for server in servers.values():
+ if isinstance(server, dict) and live_broker_key_for_url(str(server.get("url") or "")) == key:
+ return server
+ return None
+
+
+def _raw_server_entry_uses_wildcard(entry: dict[str, Any] | None) -> bool:
+ """Return whether a raw MCP server entry uses a wildcard enabledTools list."""
+ if entry is None:
+ return False
+ enabled_tools = entry.get("enabledTools", entry.get("enabled_tools"))
+ if not isinstance(enabled_tools, list):
+ return False
+ return "*" in {str(tool).strip() for tool in enabled_tools}
+
+
+def _print_missing_live_channel_config(key: str) -> None:
+ """Print actionable guidance when a live broker config cannot be loaded."""
+ if key == "robinhood":
+ from src.config.schema import format_robinhood_mcp_config_guidance
+
+ reason = "wildcard" if _raw_server_entry_uses_wildcard(_raw_live_server_config_entry(key)) else "missing"
+ console.print("[red]Robinhood live channel is not configured safely.[/red]")
+ console.print(format_robinhood_mcp_config_guidance(reason=reason), markup=False, soft_wrap=True)
+ return
+
+ console.print(
+ f"[red]No live channel configured for '{key}'.[/red] "
+ "Add the broker's mcpServers entry to ~/.vibe-trading/agent.json first."
+ )
+
+
def cmd_live_authorize(broker: str) -> int:
"""Bootstrap the OAuth handshake for a live broker channel (desktop only).
@@ -2796,10 +2856,7 @@ def cmd_live_authorize(broker: str) -> int:
key = broker.strip().lower()
server_config = _live_server_config(key)
if server_config is None:
- console.print(
- f"[red]No live channel configured for '{key}'.[/red] "
- "Add the broker's mcpServers entry to ~/.vibe-trading/agent.json first."
- )
+ _print_missing_live_channel_config(key)
return EXIT_USAGE_ERROR
if getattr(server_config, "auth", None) is None:
console.print(
diff --git a/agent/src/config/schema.py b/agent/src/config/schema.py
index 09f5578c0..c2dac4d8d 100644
--- a/agent/src/config/schema.py
+++ b/agent/src/config/schema.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import json
from typing import Literal
from urllib.parse import urlsplit
@@ -43,6 +44,10 @@ LIVE_BROKER_READONLY_WILDCARD_ALLOWED_EXTRA_SCOPES: dict[str, frozenset[str]] =
LIVE_BROKER_WRITE_SCOPES: dict[str, frozenset[str]] = {
"ibkr": frozenset({"mcp.write"}),
}
+ROBINHOOD_AGENT_CONFIG_PATH = "~/.vibe-trading/agent.json"
+LIVE_BROKER_WILDCARD_ALLOWLIST_ERROR = (
+ "enabledTools allowlist ('*'); pin an explicit read-only tool list"
+)
def _url_host(url: str) -> str:
@@ -238,6 +243,54 @@ def _to_camel(name: str) -> str:
return parts[0] + "".join(part.capitalize() for part in parts[1:])
+def _to_wire_config_value(value: object) -> object:
+ """Convert internal snake_case seed keys to external config aliases."""
+ if isinstance(value, dict):
+ return {_to_camel(str(key)): _to_wire_config_value(child) for key, child in value.items()}
+ if isinstance(value, list):
+ return [_to_wire_config_value(child) for child in value]
+ return value
+
+
+def robinhood_readonly_enabled_tools() -> tuple[str, ...]:
+ """Return the canonical Robinhood read-only tool allowlist."""
+ enabled_tools = ROBINHOOD_MCP_SERVER_SEED["enabled_tools"]
+ if not isinstance(enabled_tools, list):
+ return ()
+ return tuple(str(tool) for tool in enabled_tools)
+
+
+def robinhood_mcp_server_seed_config() -> dict[str, object]:
+ """Return the copy-pasteable Robinhood ``mcpServers`` config seed."""
+ return {
+ "mcpServers": {
+ "robinhood": _to_wire_config_value(ROBINHOOD_MCP_SERVER_SEED),
+ }
+ }
+
+
+def format_robinhood_mcp_server_seed_json() -> str:
+ """Format the canonical Robinhood read-only ``mcpServers`` seed as JSON."""
+ return json.dumps(robinhood_mcp_server_seed_config(), indent=2)
+
+
+def format_robinhood_mcp_config_guidance(*, reason: str = "missing") -> str:
+ """Build operator-facing guidance for enabling Robinhood MCP safely."""
+ tools = ", ".join(robinhood_readonly_enabled_tools())
+ if reason == "wildcard":
+ lead = (
+ 'Robinhood MCP config uses enabledTools: ["*"], which is not allowed for '
+ "live brokers."
+ )
+ else:
+ lead = "Robinhood MCP server is missing from mcpServers."
+ return (
+ f"{lead} Add the safe read-only Robinhood seed to {ROBINHOOD_AGENT_CONFIG_PATH} "
+ f"with explicit enabledTools: {tools}.\n"
+ f"{format_robinhood_mcp_server_seed_json()}"
+ )
+
+
class ConfigBase(BaseModel):
"""Base config model accepting both snake_case and camelCase keys."""
@@ -392,9 +445,16 @@ class AgentConfig(ConfigBase):
if is_live_broker_entry(server_key, server) and "*" in server.enabled_tools:
if _allows_readonly_wildcard_probe(server_key, server):
continue
+ broker = live_broker_key_for_entry(server_key, server)
+ if broker == "robinhood":
+ detail = (
+ f"{LIVE_BROKER_WILDCARD_ALLOWLIST_ERROR}. "
+ f"{format_robinhood_mcp_config_guidance(reason='wildcard')}"
+ )
+ else:
+ detail = LIVE_BROKER_WILDCARD_ALLOWLIST_ERROR
raise ValueError(
- f"Live-broker MCP server '{server_key}' may not use a wildcard "
- "enabledTools allowlist ('*'); pin an explicit read-only tool list"
+ f"Live-broker MCP server '{server_key}' may not use a wildcard {detail}"
)
return self
diff --git a/agent/src/tools/mcp.py b/agent/src/tools/mcp.py
index 807c9d8a4..565568605 100644
--- a/agent/src/tools/mcp.py
+++ b/agent/src/tools/mcp.py
@@ -24,7 +24,12 @@ from key_value.aio.stores.filetree import FileTreeStore
from mcp import types as mcp_types
from src.agent.tools import BaseTool
-from src.config.schema import MCPServerConfig
+from src.config.schema import (
+ ROBINHOOD_AGENT_CONFIG_PATH,
+ MCPServerConfig,
+ live_broker_key_for_entry,
+ robinhood_readonly_enabled_tools,
+)
logger = logging.getLogger(__name__)
@@ -254,6 +259,19 @@ def normalize_mcp_tool_schema(schema: dict[str, Any] | None) -> dict[str, Any]:
return normalized
+def _format_zero_enabled_tools_warning(server_name: str, server_config: MCPServerConfig) -> str:
+ """Build a warning when discovery yields no locally enabled tools."""
+ enabled_tools = list(getattr(server_config, "enabled_tools", []) or [])
+ if "*" in enabled_tools and live_broker_key_for_entry(server_name, server_config) == "robinhood":
+ tools = ", ".join(robinhood_readonly_enabled_tools())
+ return (
+ f"Server '{server_name}' produced 0 enabled tools with wildcard enabledTools ['*']. "
+ "Robinhood live MCP must use the safe read-only allowlist "
+ f"({tools}); copy the safe seed into {ROBINHOOD_AGENT_CONFIG_PATH}."
+ )
+ return f"Server '{server_name}' produced 0 enabled tools — check the enabledTools allowlist in agent config."
+
+
def _build_token_store(cache_dir: str) -> FileTreeStore:
"""Build a persistent OAuth token store rooted at ``cache_dir``.
@@ -338,10 +356,7 @@ class MCPServerAdapter:
)
if not specs:
- logger.warning(
- "Server '%s' produced 0 enabled tools — check the enabledTools allowlist in agent config.",
- self.server_name,
- )
+ logger.warning(_format_zero_enabled_tools_warning(self.server_name, self.server_config))
return specs
diff --git a/agent/tests/test_agent_config.py b/agent/tests/test_agent_config.py
index 4a8a3ec79..99bc2138b 100644
--- a/agent/tests/test_agent_config.py
+++ b/agent/tests/test_agent_config.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import json
import logging
from pathlib import Path
@@ -10,6 +11,7 @@ from pydantic import ValidationError
from src.config import (
AgentConfig,
+ MCPServerConfig,
get_config_path,
get_data_dir,
get_runtime_root,
@@ -17,6 +19,44 @@ from src.config import (
load_runtime_agent_config,
sanitize_session_overrides,
)
+from src.config.schema import (
+ ROBINHOOD_AGENT_CONFIG_PATH,
+ ROBINHOOD_MCP_SERVER_SEED,
+ format_robinhood_mcp_server_seed_json,
+)
+
+
+class _FakeMCPTool:
+ def __init__(self, name: str) -> None:
+ self.name = name
+ self.description = f"remote {name}"
+ self.inputSchema = {"type": "object"}
+ self.annotations = None
+
+
+class _FakeMCPClient:
+ def __init__(self, tool_names: tuple[str, ...]) -> None:
+ self._tool_names = tool_names
+
+ async def __aenter__(self) -> "_FakeMCPClient":
+ return self
+
+ async def __aexit__(self, exc_type, exc, tb) -> None:
+ return None
+
+ async def list_tools(self) -> list[_FakeMCPTool]:
+ return [_FakeMCPTool(name) for name in self._tool_names]
+
+ async def call_tool(self, name: str, arguments=None, *, timeout=None, raise_on_error=False): # noqa: D401
+ raise AssertionError("config tests must not call remote MCP tools")
+
+
+def _fake_mcp_factory(tool_names: tuple[str, ...]):
+ return lambda: _FakeMCPClient(tool_names)
+
+
+def _robinhood_seed_config() -> dict[str, object]:
+ return json.loads(format_robinhood_mcp_server_seed_json())
def test_load_agent_config_returns_defaults_when_file_missing(tmp_path: Path) -> None:
@@ -284,6 +324,137 @@ def test_get_data_dir_uses_explicit_config_parent(tmp_path: Path) -> None:
assert config_path.parent.exists()
+# ---------------------------------------------------------------------------
+# Robinhood live MCP seed + validation guidance
+# ---------------------------------------------------------------------------
+
+def test_robinhood_safe_seed_loads_and_discovers_enabled_tools_without_warnings(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ mcp = pytest.importorskip("src.tools.mcp")
+ config = AgentConfig.model_validate(_robinhood_seed_config())
+ server = config.mcp_servers["robinhood"]
+ seed_tools = tuple(ROBINHOOD_MCP_SERVER_SEED["enabled_tools"])
+
+ with caplog.at_level(logging.WARNING, logger="src.tools.mcp"):
+ tools = mcp.build_mcp_tool_wrappers(
+ "robinhood",
+ server,
+ client_factory=_fake_mcp_factory(seed_tools),
+ )
+
+ assert [tool._spec.remote_name for tool in tools] == list(seed_tools)
+ assert "produced 0 enabled tools" not in caplog.text
+
+
+def test_robinhood_wildcard_validation_names_safe_seed_and_config_path() -> None:
+ with pytest.raises(ValidationError) as excinfo:
+ AgentConfig.model_validate(
+ {
+ "mcpServers": {
+ "robinhood": {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth", "scopes": ["trading.read"]},
+ "enabledTools": ["*"],
+ }
+ }
+ }
+ )
+
+ message = str(excinfo.value)
+ assert "enabledTools allowlist ('*'); pin an explicit read-only tool list" in message
+ assert "safe read-only Robinhood seed" in message
+ assert ROBINHOOD_AGENT_CONFIG_PATH in message
+ assert '"mcpServers"' in message
+ assert '"enabledTools"' in message
+ assert '"get_account"' in message
+ assert "No live channel configured" not in message
+
+
+def test_live_authorize_missing_robinhood_config_prints_safe_seed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ from cli._legacy import EXIT_USAGE_ERROR, cmd_live_authorize
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+
+ assert cmd_live_authorize("robinhood") == EXIT_USAGE_ERROR
+
+ out = capsys.readouterr().out
+ assert "Robinhood MCP server is missing from mcpServers" in out
+ assert "safe read-only Robinhood seed" in out
+ assert ROBINHOOD_AGENT_CONFIG_PATH in out
+ assert '"mcpServers"' in out
+ assert '"enabledTools"' in out
+ assert "No live channel configured" not in out
+
+
+def test_live_authorize_wildcard_robinhood_config_prints_safe_seed(
+ tmp_path: Path,
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+) -> None:
+ from cli._legacy import EXIT_USAGE_ERROR, cmd_live_authorize
+
+ monkeypatch.setattr(Path, "home", lambda: tmp_path)
+ config_path = tmp_path / ".vibe-trading" / "agent.json"
+ config_path.parent.mkdir(parents=True)
+ config_path.write_text(
+ json.dumps(
+ {
+ "mcpServers": {
+ "robinhood": {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth", "scopes": ["trading.read"]},
+ "enabledTools": ["*"],
+ }
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ assert cmd_live_authorize("robinhood") == EXIT_USAGE_ERROR
+
+ out = capsys.readouterr().out
+ assert 'Robinhood MCP config uses enabledTools: ["*"]' in out
+ assert "safe read-only Robinhood seed" in out
+ assert ROBINHOOD_AGENT_CONFIG_PATH in out
+ assert '"get_account"' in out
+ assert "No live channel configured" not in out
+
+
+def test_mcp_robinhood_wildcard_zero_tools_warning_names_safe_allowlist(
+ caplog: pytest.LogCaptureFixture,
+) -> None:
+ mcp = pytest.importorskip("src.tools.mcp")
+ server = MCPServerConfig.model_validate(
+ {
+ "type": "streamableHttp",
+ "url": "https://agent.robinhood.com/mcp/trading",
+ "auth": {"type": "oauth", "scopes": ["trading.read"]},
+ "enabledTools": ["*"],
+ }
+ )
+
+ with caplog.at_level(logging.WARNING, logger="src.tools.mcp"):
+ tools = mcp.build_mcp_tool_wrappers(
+ "robinhood",
+ server,
+ client_factory=_fake_mcp_factory(()),
+ )
+
+ assert tools == []
+ assert "wildcard enabledTools" in caplog.text
+ assert "safe read-only allowlist" in caplog.text
+ assert "get_account" in caplog.text
+ assert ROBINHOOD_AGENT_CONFIG_PATH in caplog.text
+
+
# ---------------------------------------------------------------------------
# sanitize_session_overrides – security gate for mcpServers
# ---------------------------------------------------------------------------
@@ -401,4 +572,4 @@ def test_runtime_load_preserves_mcp_servers_when_opted_in_with_unknown_keys(
assert set(merged.mcp_servers.keys()) == {"base", "session"}
assert merged.mcp_servers["session"].command == "uvx"
- assert merged.mcp_servers["session"].args == ["session-mcp"]
\ No newline at end of file
+ assert merged.mcp_servers["session"].args == ["session-mcp"]