Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(portfolio): support Robinhood MCP source with account selection for portfolio reads (#1428)

Jackzigenc05c28d17201
diff --git a/agent/src/portfolio/compatibility.py b/agent/src/portfolio/compatibility.py
index d14bc6f5e..2f04180be 100644
--- a/agent/src/portfolio/compatibility.py
+++ b/agent/src/portfolio/compatibility.py
@@ -102,7 +102,7 @@ _CONNECTOR_COMPATIBILITY: dict[str, PortfolioCompatibility] = {
"experimental",
1,
"stocks_etfs",
- "Equity positions for one selected account, unpriced until the quote reply is mapped.",
+ "Equity positions for one selected account, priced through get_equity_quotes.",
),
# No "scalable" entry: its profile does not declare account.read /
# positions.read, so it is not a portfolio-eligible connection. The
diff --git a/agent/src/portfolio/service.py b/agent/src/portfolio/service.py
index 8911c64f0..804b0b328 100644
--- a/agent/src/portfolio/service.py
+++ b/agent/src/portfolio/service.py
@@ -1080,6 +1080,10 @@ class PortfolioService:
exchange=normalized.get("exchange") or "SMART",
currency=normalized["currency"],
sec_type="STK",
+ # Same rule as the reads above: a dashboard refresh
+ # must never open a browser (reconnect_source() is the
+ # one explicit interactive path).
+ interactive_oauth=False,
**(
{"connection_id": connection.id}
if profile.transport == "local_plugin"
@@ -1090,6 +1094,11 @@ class PortfolioService:
price = _quote_price(quote)
normalized["market_price"] = _number(price) if price else None
normalized["price_currency"] = normalized["currency"]
+ if isinstance(quote, dict) and quote.get("mapping_error"):
+ # The broker answered but the reply did not match its
+ # mapped shape: the row stays unpriced with the reason
+ # on it, never silently.
+ normalized["price_error"] = str(quote["mapping_error"])[:160]
except Exception as exc:
normalized["price_error"] = str(exc)[:160]
rows.append(normalized)
diff --git a/agent/src/trading/connectors/robinhood/mcp.py b/agent/src/trading/connectors/robinhood/mcp.py
index 27a19f817..c9e745151 100644
--- a/agent/src/trading/connectors/robinhood/mcp.py
+++ b/agent/src/trading/connectors/robinhood/mcp.py
@@ -15,17 +15,33 @@ What the shapes are built from, and nothing else:
#1428 (2026-09-16). ``data`` allows exactly ``positions`` and ``next``. An item
carries ``symbol``, ``quantity`` and an optional ``average_buy_price``, and no
price or currency.
-
-Still unobserved: ``get_equity_quotes``, ``get_equity_orders``, the argument that
-fetches a further page, and what an item's ``type`` means. So a reply with
-more than one page is an error rather than a first page read as the whole
-account, and ``type`` is carried through without being interpreted.
+* ``get_equity_quotes``, the paginated tools' argument schemas and the ``type``
+ / ``next`` descriptions: the server's advertised ``tools/list`` metadata,
+ transcribed in the third-party ``kevin1chun/robinhood-for-agents`` repo
+ (``docs/official-mcp-tools.json``, live capture 2026-10-12, refreshed by an
+ authenticated login and checked verbatim by that repo's parity tests). Every
+ claim of that transcription that can be cross-checked against an independent
+ capture matches: its ``get_equity_positions`` ``outputSchema`` equals the
+ schema posted on #1428 field for field, and its quote fields match two other
+ third-party captures (``gordil/robin-python-SDK`` docs, real responses parsed
+ by ``Oft3r/agentic-trading-desk``).
+
+The descriptions this mapping relies on: a position item's ``type`` is the
+position direction — ``'long' (positive quantity), 'short' (negative),
+'boxed' (both, rare), or 'empty' (zero)`` — carried through, never interpreted.
+``next`` is "an opaque cursor for the next page — NOT a URL ... call this tool
+again with ``cursor`` set to this value verbatim, leaving the other arguments
+unchanged. Empty on the last page." Quotes reply as ``data.results``, one
+entry per requested symbol, each required to carry a ``quote`` whose ``bid``
+/ ``ask`` are "Zero when the book is closed or unavailable" and whose
+``has_traded=False`` means the price fields are meaningless, plus an optional
+official settled ``close``.
"""
from __future__ import annotations
from decimal import Decimal, InvalidOperation
-from typing import Any
+from typing import Any, Callable
_REMOTE_TOOL_NAMES = {
"accounts": "get_accounts",
@@ -56,9 +72,40 @@ NON_EQUITY_VALUE_FIELDS = (
"fixed_income_value",
)
+#: Every ``get_equity_quotes`` ``quote`` field. The advertised outputSchema
+#: marks all fourteen required with ``additionalProperties: false``; the
+#: mapping validates the object against exactly these names.
+QUOTE_FIELDS = frozenset(
+ {
+ "symbol",
+ "last_trade_price",
+ "venue_last_trade_time",
+ "last_non_reg_trade_price",
+ "venue_last_non_reg_trade_time",
+ "adjusted_previous_close",
+ "previous_close",
+ "previous_close_date",
+ "bid_price",
+ "venue_bid_time",
+ "ask_price",
+ "venue_ask_time",
+ "has_traded",
+ "state",
+ }
+)
+
+#: The optional official settled ``close`` object of a quote result.
+CLOSE_FIELDS = frozenset({"symbol", "date", "price", "interpolated", "source"})
+
#: Operations whose remote tool takes the selected account as ``account_number``.
ACCOUNT_SCOPED_OPERATIONS = frozenset({"account", "positions", "orders"})
+#: Operations whose remote tool takes a pagination ``cursor``. The transcribed
+#: input schemas carry it on ``get_equity_positions`` and ``get_equity_orders``;
+#: ``get_portfolio`` and ``get_accounts`` take no arguments beyond (for
+#: ``get_portfolio``) the account, and a cursor sent there would be refused.
+PAGINATED_OPERATIONS = frozenset({"positions", "orders"})
+
class RobinhoodShapeError(ValueError):
"""A Robinhood reply that does not match the shape this mapping was built from."""
@@ -84,11 +131,18 @@ def remote_arguments(operation: str, arguments: dict[str, Any]) -> dict[str, Any
# Robinhood's get_portfolio / get_equity_positions / get_equity_orders
# MCP tools require account_number. The generic trading service passes
# the CLI/agent-supplied account code in under the "account" key; map
- # it to the field name Robinhood's schema actually expects.
+ # it to the field name Robinhood's schema actually expects. A cursor
+ # goes through only for the tools whose advertised input schema has
+ # one, passed verbatim as the schema's description directs.
+ wire: dict[str, Any] = {}
account_number = arguments.get("account_number") or arguments.get("account")
if account_number:
- return {"account_number": account_number}
- return {}
+ wire["account_number"] = account_number
+ if operation in PAGINATED_OPERATIONS:
+ cursor = arguments.get("cursor")
+ if isinstance(cursor, str) and cursor:
+ wire["cursor"] = cursor
+ return wire
return {}
@@ -118,9 +172,45 @@ def broker_data(envelope: Any, tool: str) -> dict[str, Any]:
return payload["data"]
+#: Upper bound on pages one complete read may follow. The cursor is opaque and
+#: the server advertises no page count, so a cursor that has not reached an
+#: empty ``next`` within this many pages is treated as a loop, not a big
+#: account — and a partial read is never passed off as complete.
+_MAX_PAGES = 100
+
+
+def _page(envelope: Any, key: str, tool: str) -> tuple[list[dict[str, Any]], str]:
+ """Validate one reply page and split it into records and the next cursor.
+
+ Raises:
+ RobinhoodShapeError: If the list is missing or null, holds a null or
+ non-object item, ``data`` carries a key other than ``key`` and
+ ``next``, or ``next`` is not the advertised optional string.
+ """
+ data = broker_data(envelope, tool)
+ unexpected = sorted(set(data) - {key, "next"})
+ if unexpected:
+ raise RobinhoodShapeError(f"{tool} reply has unmapped data keys: {', '.join(unexpected)}")
+ next_value = data.get("next")
+ if next_value is not None and not isinstance(next_value, str):
+ raise RobinhoodShapeError(f"{tool} reply has a non-string next")
+ rows = data.get(key)
+ if not isinstance(rows, list):
+ raise RobinhoodShapeError(f"{tool} reply has no {key} list")
+ for index, row in enumerate(rows):
+ if not isinstance(row, dict):
+ raise RobinhoodShapeError(f"{tool} {key}[{index}] is not an object")
+ return rows, next_value or ""
+
+
def records(envelope: Any, key: str, tool: str) -> list[dict[str, Any]]:
"""Return the complete record list a Robinhood list read carries.
+ This is the single-page contract: a reply that advertises a further page
+ is refused, because the first page is not the whole account. Readers that
+ follow cursors go through :func:`with_all_pages` first and hand it the
+ merged reply.
+
Args:
envelope: ``MCPServerAdapter.call_tool`` result.
key: The list field inside ``data`` (``positions``, ``orders``,
@@ -128,7 +218,7 @@ def records(envelope: Any, key: str, tool: str) -> list[dict[str, Any]]:
tool: Remote tool name, for error messages.
Returns:
- Every record, each an object.
+ Every record on the page, each an object.
Raises:
RobinhoodShapeError: If the list is missing or null, holds a null or
@@ -136,24 +226,79 @@ def records(envelope: Any, key: str, tool: str) -> list[dict[str, Any]]:
``next``, or a non-empty ``next`` says the reply is one page of
several.
"""
- data = broker_data(envelope, tool)
- unexpected = sorted(set(data) - {key, "next"})
- if unexpected:
- raise RobinhoodShapeError(f"{tool} reply has unmapped data keys: {', '.join(unexpected)}")
- if data.get("next") not in (None, ""):
+ rows, next_cursor = _page(envelope, key, tool)
+ if next_cursor:
raise RobinhoodShapeError(
- f"{tool} returned more than one page; reading further pages is not mapped yet, "
- "and the first page is not the whole account"
+ f"{tool} returned more than one page and this read does not follow cursors; "
+ "the first page is not the whole account"
)
- rows = data.get(key)
- if not isinstance(rows, list):
- raise RobinhoodShapeError(f"{tool} reply has no {key} list")
- for index, row in enumerate(rows):
- if not isinstance(row, dict):
- raise RobinhoodShapeError(f"{tool} {key}[{index}] is not an object")
return rows
+def with_all_pages(envelope: Any, key: str, tool: str, refetch: Callable[[str], Any]) -> Any:
+ """Follow the reply's advertised ``next`` cursor and merge every page.
+
+ This implements the contract the server's own schema states: ``next`` is
+ an opaque cursor, not a URL, and the next page is fetched by calling the
+ tool again with ``cursor`` set to that value verbatim, other arguments
+ unchanged, until a reply carries an empty ``next``. ``refetch`` must do
+ exactly that and return the follow-up call's envelope.
+
+ Args:
+ envelope: The first page's ``MCPServerAdapter.call_tool`` result.
+ key: The list field inside ``data`` (``positions``, ``orders``).
+ tool: Remote tool name, for error messages.
+ refetch: Callable taking the verbatim cursor and returning the next
+ page's envelope.
+
+ Returns:
+ The first envelope unchanged when the call failed or its ``next`` is
+ empty. Otherwise a shallow copy of the first envelope whose
+ ``data`` / ``structured_content`` hold every page's records under
+ ``key`` with an empty ``next`` — one complete read in the shape the
+ single-page mappers already validate.
+
+ Raises:
+ RobinhoodShapeError: If a follow-up call fails or breaks the page
+ shape, or the cursor does not reach a last page within
+ :data:`_MAX_PAGES` pages. A partial multi-page read is never
+ returned: the pages fetched so far are dropped with the error.
+ """
+ if str(envelope.get("status") or "").lower() != "ok":
+ return envelope
+ try:
+ rows, next_cursor = _page(envelope, key, tool)
+ except RobinhoodShapeError:
+ # No readable page means no cursor to follow: leave the envelope for
+ # the mappers, whose mapping_error names what is actually wrong with
+ # it instead of a pagination failure that did not happen.
+ return envelope
+ if not next_cursor:
+ return envelope
+ payload = envelope.get("structured_content")
+ if payload is None:
+ payload = envelope.get("data")
+ guide = payload.get("guide") if isinstance(payload, dict) else None
+ all_rows = list(rows)
+ for _ in range(_MAX_PAGES):
+ try:
+ page = refetch(next_cursor)
+ except Exception as exc:
+ raise RobinhoodShapeError(f"{tool} next-page call failed: {exc}") from None
+ page_rows, next_cursor = _page(page, key, tool)
+ all_rows.extend(page_rows)
+ if not next_cursor:
+ structured = {"data": {key: all_rows, "next": ""}, "guide": guide}
+ merged = dict(envelope)
+ merged["data"] = structured
+ merged["structured_content"] = structured
+ return merged
+ raise RobinhoodShapeError(
+ f"{tool} did not reach a last page within {_MAX_PAGES} pages; "
+ "the pages read so far are dropped rather than shown as the whole account"
+ )
+
+
def _decimal_text(value: Any, field: str, tool: str) -> str:
"""Return ``value`` when it is a finite decimal string, else raise."""
if isinstance(value, bool) or value is None:
@@ -209,6 +354,102 @@ def portfolio_summary(envelope: Any) -> dict[str, Any]:
}
+def quote_summary(envelope: Any) -> dict[str, Any] | None:
+ """Map a ``get_equity_quotes`` reply to the quote view the portfolio prices with.
+
+ The generic read asks for one symbol, so the reply must carry exactly one
+ ``results`` entry. The mapping hands the reply's prices to the shared quote
+ reader under its own names: ``last_trade_price`` — the regular-hours print,
+ which the server describes as staying frozen at the closing price after the
+ close — becomes ``last``; the official settled ``close.price`` becomes
+ ``close``; ``bid_price`` / ``ask_price`` become ``bid`` / ``ask``. A closed
+ book reports those as ``"0"``, which the shared reader treats as no price.
+ ``has_traded=False`` means the price fields are meaningless, so they are
+ mapped as absent instead of passed on as prices; the listing ``state`` is
+ carried through for consumers that need to qualify the quote.
+
+ Args:
+ envelope: ``MCPServerAdapter.call_tool`` result for
+ ``get_equity_quotes``.
+
+ Returns:
+ ``None`` when the reply advertises no result rows (the symbol resolved
+ to nothing, or its ``quote`` is null), else the quote mapping with
+ decimal-string values and ``None`` for absent prices.
+
+ Raises:
+ RobinhoodShapeError: If the reply does not match the advertised
+ schema, or carries more than one result for a one-symbol read.
+ """
+ tool = "get_equity_quotes"
+ data = broker_data(envelope, tool)
+ unexpected = sorted(set(data) - {"results", "closes_error"})
+ if unexpected:
+ raise RobinhoodShapeError(f"{tool} reply has unmapped data keys: {', '.join(unexpected)}")
+ results = data.get("results")
+ if results is None:
+ return None
+ if not isinstance(results, list):
+ raise RobinhoodShapeError(f"{tool} results is not a list")
+ if len(results) > 1:
+ raise RobinhoodShapeError(f"{tool} returned {len(results)} quote rows for a one-symbol read")
+ if not results:
+ return None
+ entry = results[0]
+ if not isinstance(entry, dict):
+ raise RobinhoodShapeError(f"{tool} results[0] is not an object")
+ unexpected = sorted(set(entry) - {"quote", "close"})
+ if unexpected:
+ raise RobinhoodShapeError(f"{tool} results[0] has unmapped keys: {', '.join(unexpected)}")
+ if "quote" not in entry:
+ # The schema marks quote required; a missing key is a broken reply,
+ # while an explicitly null one means the symbol resolved to nothing.
+ raise RobinhoodShapeError(f"{tool} results[0] has no quote")
+ quote = entry.get("quote")
+ if quote is None:
+ return None
+ if not isinstance(quote, dict):
+ raise RobinhoodShapeError(f"{tool} results[0].quote is not an object")
+ missing = sorted(QUOTE_FIELDS - set(quote))
+ if missing:
+ raise RobinhoodShapeError(f"{tool} quote is missing {', '.join(missing)}")
+ unexpected = sorted(set(quote) - QUOTE_FIELDS)
+ if unexpected:
+ raise RobinhoodShapeError(f"{tool} quote has unmapped fields: {', '.join(unexpected)}")
+ has_traded = quote.get("has_traded")
+ if not isinstance(has_traded, bool):
+ raise RobinhoodShapeError(f"{tool} quote has_traded is not a boolean")
+ state = quote.get("state")
+ if not isinstance(state, str) or not state.strip():
+ raise RobinhoodShapeError(f"{tool} quote state is missing")
+ prices: dict[str, str | None] = {"last": None, "bid": None, "ask": None}
+ if has_traded:
+ for field, name in (("last_trade_price", "last"), ("bid_price", "bid"), ("ask_price", "ask")):
+ prices[name] = _decimal_text(quote.get(field), f"quote.{field}", tool)
+ close_price = None
+ close = entry.get("close")
+ if close is not None:
+ if not isinstance(close, dict):
+ raise RobinhoodShapeError(f"{tool} results[0].close is not an object")
+ missing = sorted(CLOSE_FIELDS - set(close))
+ if missing:
+ raise RobinhoodShapeError(f"{tool} close is missing {', '.join(missing)}")
+ unexpected = sorted(set(close) - CLOSE_FIELDS)
+ if unexpected:
+ raise RobinhoodShapeError(f"{tool} close has unmapped fields: {', '.join(unexpected)}")
+ if close.get("price") is not None:
+ close_price = _decimal_text(close.get("price"), "close.price", tool)
+ return {
+ "symbol": quote.get("symbol"),
+ "last": prices["last"],
+ "close": close_price,
+ "bid": prices["bid"],
+ "ask": prices["ask"],
+ "has_traded": has_traded,
+ "state": state.strip(),
+ }
+
+
def position_rows(envelope: Any) -> list[dict[str, Any]]:
"""Map a ``get_equity_positions`` reply to generic position rows.
@@ -220,11 +461,16 @@ def position_rows(envelope: Any) -> list[dict[str, Any]]:
One ``{"symbol", "quantity", "average_cost", "broker_type"}`` row per
position. ``average_cost`` is ``None`` when Robinhood omitted
``average_buy_price`` (it does while a position reconciles); it is
- never read as zero.
+ never read as zero. ``broker_type`` carries the row's ``type``
+ verbatim — the schema describes it as the position direction
+ (``'long' (positive quantity), 'short' (negative), 'boxed' (both,
+ rare), or 'empty' (zero)``) — it is not an enum constraint and is
+ never interpreted here.
Raises:
RobinhoodShapeError: If the reply is not a complete, single-page
- position list, or a row has no symbol or a non-numeric quantity.
+ position list, or a row has no symbol, no ``type``, or a
+ non-numeric quantity.
"""
tool = "get_equity_positions"
rows = []
@@ -232,6 +478,9 @@ def position_rows(envelope: Any) -> list[dict[str, Any]]:
symbol = row.get("symbol")
if not isinstance(symbol, str) or not symbol.strip():
raise RobinhoodShapeError(f"{tool} positions[{index}] has no symbol")
+ broker_type = row.get("type")
+ if not isinstance(broker_type, str) or not broker_type.strip():
+ raise RobinhoodShapeError(f"{tool} positions[{index}] has no type")
average = row.get("average_buy_price")
rows.append(
{
@@ -242,7 +491,7 @@ def position_rows(envelope: Any) -> list[dict[str, Any]]:
if average is not None
else None
),
- "broker_type": row.get("type"),
+ "broker_type": broker_type,
}
)
return rows
@@ -293,7 +542,7 @@ def account_choices(envelope: Any) -> list[dict[str, Any]]:
def normalize_result(operation: str, envelope: dict[str, Any]) -> dict[str, Any]:
- """Add the generic account / positions / accounts view to a Robinhood reply.
+ """Add the generic account / positions / accounts / quote view to a Robinhood reply.
The broker reply is kept as it came. A reply that does not match the mapped
shape is not turned into an error here, because an agent reading the
@@ -312,6 +561,7 @@ def normalize_result(operation: str, envelope: dict[str, Any]) -> dict[str, Any]
"account": ("account", portfolio_summary),
"positions": ("positions", position_rows),
"accounts": ("accounts", account_choices),
+ "quote": ("quote", quote_summary),
}
if operation not in mappers or str(envelope.get("status") or "").lower() != "ok":
return envelope
diff --git a/agent/src/trading/connectors/robinhood/profiles.py b/agent/src/trading/connectors/robinhood/profiles.py
index ec7435109..a1fe08a5e 100644
--- a/agent/src/trading/connectors/robinhood/profiles.py
+++ b/agent/src/trading/connectors/robinhood/profiles.py
@@ -26,23 +26,23 @@ ROBINHOOD_PROFILES: tuple[TradingProfile, ...] = (
"Robinhood's options order and required review schemas are not mapped into the mandate gate."
),
),
- # The portfolio view of the same MCP server and OAuth grant. It declares no
- # quotes.read: the get_equity_quotes reply shape has not been observed, so
- # positions are listed unpriced rather than priced off a guessed field.
+ # The portfolio view of the same MCP server and OAuth grant. Positions are
+ # priced through get_equity_quotes, mapped from the server's advertised
+ # outputSchema (see connectors/robinhood/mcp.py for the evidence trail).
TradingProfile(
id="robinhood-live-mcp-readonly",
connector="robinhood",
label="Robinhood Live · Agentic MCP Read-Only",
environment="live",
transport="remote_mcp",
- capabilities=("account.read", "positions.read"),
+ capabilities=("account.read", "positions.read", "quotes.read"),
readonly=True,
config={"server": "robinhood", "account_selection": "required"},
notes=(
- "Reads get_portfolio and get_equity_positions for one selected account. "
- "Positions are unpriced until the quote reply is mapped; an account holding "
- "options, crypto, futures, event contracts, mutual funds or fixed income is "
- "reported as an error instead of an equity-only view."
+ "Reads get_portfolio, get_equity_positions and get_equity_quotes for one "
+ "selected account. Positions are priced from the quote read; an account "
+ "holding options, crypto, futures, event contracts, mutual funds or fixed "
+ "income is reported as an error instead of an equity-only view."
),
),
)
diff --git a/agent/src/trading/service.py b/agent/src/trading/service.py
index a4216bd8b..c76693b16 100644
--- a/agent/src/trading/service.py
+++ b/agent/src/trading/service.py
@@ -330,7 +330,17 @@ def get_quote(
sec_type: str = "STK",
**overrides: Any,
) -> dict[str, Any]:
- """Read a quote for a connector profile."""
+ """Read a quote for a connector profile.
+
+ Args:
+ symbol: Instrument symbol to quote.
+ profile_id: Connector profile to read through.
+ exchange: IBKR exchange, ignored off the local TWS transport.
+ currency: Quote currency, ignored off the local TWS transport.
+ sec_type: IBKR security type, ignored off the local TWS transport.
+ **overrides: ``interactive_oauth=False`` keeps an expired grant from
+ opening a browser, matching the other remote MCP reads.
+ """
profile = profile_by_id(profile_id)
if profile.transport == "local_tws":
from src.trading.connectors.ibkr.local import get_quote as _get_quote
@@ -353,7 +363,12 @@ def get_quote(
profile,
_local_plugin_call(profile, "get_quote", overrides, symbol),
)
- return _call_remote(profile, "quote", {"symbols": [symbol], "symbol": symbol})
+ return _call_remote(
+ profile,
+ "quote",
+ {"symbols": [symbol], "symbol": symbol},
+ interactive_oauth=bool(overrides.get("interactive_oauth", True)),
+ )
def search_instruments(
@@ -1573,6 +1588,9 @@ 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 = _complete_paginated_reply(
+ profile.connector, operation, call_result, adapter, remote_name, arguments
+ )
call_result = _normalize_remote_result(profile.connector, operation, call_result)
account_number = arguments.get("account_number")
if account_number:
@@ -1581,6 +1599,55 @@ def _call_remote(
return _with_profile(profile, call_result)
+def _complete_paginated_reply(
+ connector: str,
+ operation: str,
+ envelope: dict[str, Any],
+ adapter: Any,
+ remote_name: str,
+ arguments: dict[str, Any],
+) -> dict[str, Any]:
+ """Follow a connector's advertised pagination cursor to the last page.
+
+ Robinhood's list reads answer one page at a time: the reply's ``next`` is
+ an opaque cursor the schema directs callers to pass back verbatim as the
+ tool's ``cursor`` argument, other arguments unchanged, until it comes back
+ empty. The portfolio needs the whole account, so the generic read follows
+ the cursor here, before any mapping runs, and hands the mappers one
+ complete reply. A connector or operation without a mapped cursor keeps the
+ single-page reply, and its mapping refuses a non-empty ``next`` as before.
+
+ Args:
+ connector: Broker key the profile selects.
+ operation: Generic read operation that produced the reply.
+ envelope: The first page's ``MCPServerAdapter.call_tool`` result.
+ adapter: The MCP adapter the first call went through.
+ remote_name: Remote tool name the first call used.
+ arguments: Wire arguments of the first call, re-sent unchanged (plus
+ the cursor) on every follow-up page.
+
+ Returns:
+ The first envelope unchanged when there is nothing to follow, else
+ the connector's merged whole-account reply.
+
+ Raises:
+ ValueError: If a follow-up page fails or breaks shape, per the
+ connector's pagination helper. A partial multi-page read is never
+ returned.
+ """
+ if connector != "robinhood" or operation not in ("positions", "orders"):
+ return envelope
+ from src.trading.connectors.robinhood import mcp
+
+ def refetch(cursor: str) -> dict[str, Any]:
+ return adapter.call_tool(
+ remote_name, _remote_arguments(connector, operation, {**arguments, "cursor": cursor})
+ )
+
+ list_key = "positions" if operation == "positions" else "orders"
+ return mcp.with_all_pages(envelope, list_key, remote_name, refetch)
+
+
def _remote_tool_name(connector: str, operation: str) -> str | None:
"""Map generic read operations to current remote MCP tool names."""
if connector == "ibkr":
diff --git a/agent/tests/robinhood_mcp_helpers.py b/agent/tests/robinhood_mcp_helpers.py
index 319aeec20..66ac21058 100644
--- a/agent/tests/robinhood_mcp_helpers.py
+++ b/agent/tests/robinhood_mcp_helpers.py
@@ -8,7 +8,10 @@ the ``data.positions`` the live path used to read (#1442).
Field names and types come from balu1866's posts: observed ``get_accounts`` and
``get_portfolio`` replies (2026-09-14) and the advertised
-``get_equity_positions`` ``outputSchema`` (2026-09-16). Values are invented.
+``get_equity_positions`` ``outputSchema`` (2026-09-16), plus the server's
+advertised ``tools/list`` metadata for ``get_equity_quotes`` and the paginated
+tools' argument schemas (transcribed in ``kevin1chun/robinhood-for-agents``,
+live capture 2026-10-12). Values are invented.
"""
from __future__ import annotations
@@ -40,10 +43,18 @@ def envelope(tool: str, data: Any, *, guide: str = "Values are strings.") -> dic
}
-def position(symbol: str, quantity: str, *, average_buy_price: str | None = "100.00") -> dict[str, Any]:
+def position(
+ symbol: str,
+ quantity: str,
+ *,
+ average_buy_price: str | None = "100.00",
+ type: str = "long", # noqa: A002 - the remote field's own name
+) -> dict[str, Any]:
"""Return one ``get_equity_positions`` item with every required field."""
- # The meaning and values of `type` are unobserved, so tests never depend on it.
- row: dict[str, Any] = {"symbol": symbol, "quantity": quantity, "type": "unobserved"}
+ # `type` is the server-documented position direction ('long', 'short',
+ # 'boxed', 'empty'); positive fixtures are 'long', matching the schema's
+ # "positive quantity" description.
+ row: dict[str, Any] = {"symbol": symbol, "quantity": quantity, "type": type}
row.update({field: "0" for field in _POSITION_SHARE_FIELDS})
row["shares_available_for_sells"] = quantity
if average_buy_price is not None:
@@ -123,3 +134,58 @@ def account(
def accounts(rows: list[dict[str, Any]]) -> dict[str, Any]:
"""Return a ``get_accounts`` envelope."""
return envelope("get_accounts", {"accounts": rows})
+
+
+def quote(
+ symbol: str,
+ *,
+ last_trade_price: str = "100.00",
+ bid_price: str = "99.50",
+ ask_price: str = "100.50",
+ has_traded: bool = True,
+ state: str = "active",
+) -> dict[str, Any]:
+ """Return one ``get_equity_quotes`` ``quote`` object with every required field."""
+ return {
+ "symbol": symbol,
+ "last_trade_price": last_trade_price,
+ "venue_last_trade_time": "2026-10-12T15:59:00Z",
+ "last_non_reg_trade_price": None,
+ "venue_last_non_reg_trade_time": None,
+ "adjusted_previous_close": "99.00",
+ "previous_close": "99.00",
+ "previous_close_date": "2026-10-11",
+ "bid_price": bid_price,
+ "venue_bid_time": "2026-10-12T15:59:00Z",
+ "ask_price": ask_price,
+ "venue_ask_time": "2026-10-12T15:59:00Z",
+ "has_traded": has_traded,
+ "state": state,
+ }
+
+
+def settled_close(symbol: str, *, price: str | None = "98.50") -> dict[str, Any]:
+ """Return one ``get_equity_quotes`` official settled ``close`` object."""
+ return {
+ "symbol": symbol,
+ "date": "2026-10-11",
+ "price": price,
+ "interpolated": False,
+ "source": "sip-close",
+ }
+
+
+def quote_result(quote_row: dict[str, Any], *, close_row: dict[str, Any] | None = None) -> dict[str, Any]:
+ """Return one ``get_equity_quotes`` ``results`` entry."""
+ entry: dict[str, Any] = {"quote": quote_row}
+ if close_row is not None:
+ entry["close"] = close_row
+ return entry
+
+
+def quotes(entries: list[dict[str, Any]] | None, *, closes_error: str | None = None) -> dict[str, Any]:
+ """Return a ``get_equity_quotes`` envelope."""
+ data: dict[str, Any] = {"results": entries}
+ if closes_error is not None:
+ data["closes_error"] = closes_error
+ return envelope("get_equity_quotes", data)
diff --git a/agent/tests/test_capability_matrix.py b/agent/tests/test_capability_matrix.py
index 855bea603..bcb126002 100644
--- a/agent/tests/test_capability_matrix.py
+++ b/agent/tests/test_capability_matrix.py
@@ -54,7 +54,7 @@ def test_paper_order_capability_never_becomes_a_live_permission() -> None:
assert "orders.place" not in rows[profile.id][7]
assert rows["alpaca-live-trade"][8] == "mandate required"
assert rows["robinhood-live-mcp"][8] == "mandate required"
- assert rows["robinhood-live-mcp-readonly"][6] == "none declared"
+ assert rows["robinhood-live-mcp-readonly"][6] == "remote_mcp" # quotes.read prices positions
assert "positions.edit" in rows["etoro-live-trade"][7]
diff --git a/agent/tests/test_robinhood_mcp_mapping.py b/agent/tests/test_robinhood_mcp_mapping.py
index 2d982864e..077c9eeee 100644
--- a/agent/tests/test_robinhood_mcp_mapping.py
+++ b/agent/tests/test_robinhood_mcp_mapping.py
@@ -9,6 +9,7 @@ account, an omitted cost as zero.
from __future__ import annotations
from types import SimpleNamespace
+from typing import Any
import pytest
@@ -18,6 +19,8 @@ from tests import robinhood_mcp_helpers as rh
pytestmark = pytest.mark.unit
+ACCOUNT = "5QR12345"
+
def test_portfolio_summary_reads_the_nested_data_object() -> None:
summary = mcp.portfolio_summary(rh.portfolio(total_value="1234.50", cash="200.00", buying_power="180.25"))
@@ -110,11 +113,24 @@ def test_position_rows_map_symbol_quantity_and_cost() -> None:
)
assert rows == [
- {"symbol": "AAPL", "quantity": "10.5", "average_cost": "150.25", "broker_type": "unobserved"},
- {"symbol": "MSFT", "quantity": "2", "average_cost": None, "broker_type": "unobserved"},
+ {"symbol": "AAPL", "quantity": "10.5", "average_cost": "150.25", "broker_type": "long"},
+ {"symbol": "MSFT", "quantity": "2", "average_cost": None, "broker_type": "long"},
]
+def test_the_position_type_is_carried_through_never_interpreted() -> None:
+ rows = mcp.position_rows(rh.positions([rh.position("AAPL", "-3", type="short")]))
+
+ assert rows[0]["broker_type"] == "short"
+ assert rows[0]["quantity"] == "-3" # the sign stays the broker's own fact
+
+
[email protected]("broken", [None, "", " "])
+def test_a_position_row_without_its_required_type_is_an_error(broken: str | None) -> None:
+ with pytest.raises(mcp.RobinhoodShapeError, match=r"positions\[0\] has no type"):
+ mcp.position_rows(rh.positions([{**rh.position("AAPL", "1"), "type": broken}]))
+
+
def test_an_empty_position_list_is_a_complete_empty_account() -> None:
assert mcp.position_rows(rh.positions([])) == []
assert mcp.position_rows(rh.positions([], next_page="")) == []
@@ -198,12 +214,12 @@ def test_normalize_result_marks_an_unmappable_reply_instead_of_failing_the_read(
assert "more than one page" in normalized["mapping_error"]
-def test_normalize_result_leaves_error_envelopes_and_other_operations_alone() -> None:
+def test_normalize_result_leaves_error_envelopes_and_unmapped_operations_alone() -> None:
error = {"status": "error", "error": "boom"}
- quote = {"status": "ok", "data": {"anything": 1}}
+ orders = {"status": "ok", "data": {"anything": 1}}
assert mcp.normalize_result("positions", error) is error
- assert mcp.normalize_result("quote", quote) is quote
+ assert mcp.normalize_result("orders", orders) is orders
def test_account_scoped_operations_send_account_number_and_accounts_sends_nothing() -> None:
@@ -213,6 +229,228 @@ def test_account_scoped_operations_send_account_number_and_accounts_sends_nothin
assert mcp.remote_arguments("accounts", {"account": "5QR1"}) == {}
+def test_a_cursor_goes_only_to_the_tools_whose_schema_has_one() -> None:
+ assert mcp.remote_arguments("positions", {"account": "5QR1", "cursor": " c1 "}) == {
+ "account_number": "5QR1",
+ "cursor": " c1 ",
+ }
+ assert mcp.remote_arguments("orders", {"cursor": "c1"}) == {"cursor": "c1"}
+ assert mcp.remote_arguments("positions", {"account": "5QR1", "cursor": ""}) == {"account_number": "5QR1"}
+ assert mcp.remote_arguments("positions", {"account": "5QR1", "cursor": 7}) == {"account_number": "5QR1"}
+ assert mcp.remote_arguments("account", {"account": "5QR1", "cursor": "c1"}) == {"account_number": "5QR1"}
+ assert mcp.remote_arguments("accounts", {"cursor": "c1"}) == {}
+
+
+# --------------------------------------------------------------------------- #
+# get_equity_quotes #
+# --------------------------------------------------------------------------- #
+
+
+def test_quote_summary_maps_the_reply_onto_the_shared_quote_reader_names() -> None:
+ summary = mcp.quote_summary(
+ rh.quotes([rh.quote_result(rh.quote("AAPL", last_trade_price="150.25", bid_price="150", ask_price="151"))])
+ )
+
+ assert summary == {
+ "symbol": "AAPL",
+ "last": "150.25",
+ "close": None,
+ "bid": "150",
+ "ask": "151",
+ "has_traded": True,
+ "state": "active",
+ }
+
+
+def test_quote_summary_maps_the_official_settled_close_when_present() -> None:
+ summary = mcp.quote_summary(
+ rh.quotes([rh.quote_result(rh.quote("AAPL"), close_row=rh.settled_close("AAPL", price="149.50"))])
+ )
+
+ assert summary["close"] == "149.50"
+
+
+def test_quote_summary_maps_a_zero_book_as_no_price_not_zero() -> None:
+ summary = mcp.quote_summary(rh.quotes([rh.quote_result(rh.quote("AAPL", bid_price="0", ask_price="0"))]))
+
+ assert summary["last"] == "100.00"
+ assert summary["bid"] == "0" # a closed book's sentinel, not a price
+ assert summary["ask"] == "0"
+
+
+def test_a_quote_that_has_never_traded_maps_no_price_fields() -> None:
+ summary = mcp.quote_summary(rh.quotes([rh.quote_result(rh.quote("AAPL", has_traded=False))]))
+
+ assert summary["has_traded"] is False
+ assert summary["last"] is None and summary["bid"] is None and summary["ask"] is None
+ assert mcp.normalize_result("quote", rh.quotes([rh.quote_result(rh.quote("AAPL", has_traded=False))]))[
+ "quote"
+ ] == summary
+
+
+def test_normalize_result_adds_the_quote_view_and_keeps_the_raw_reply() -> None:
+ envelope = rh.quotes([rh.quote_result(rh.quote("MSFT", last_trade_price="400.10"))])
+
+ normalized = mcp.normalize_result("quote", envelope)
+
+ assert normalized["quote"]["last"] == "400.10"
+ assert normalized["structured_content"] is envelope["structured_content"]
+ assert "mapping_error" not in normalized
+
+
+def _broken_quote(**overrides: Any) -> dict:
+ """A quote result with the required quote object replaced or damaged."""
+ entry = rh.quote_result(rh.quote("AAPL"))
+ entry.update(overrides)
+ return entry
+
+
+ ("envelope", "message"),
+ [
+ (rh.quotes(None), ""), # a null results list maps to no quote, not an error
+ (rh.quotes([]), ""),
+ (rh.quotes([{"quote": None}]), ""), # an explicitly null quote is the same
+ (rh.quotes([rh.quote_result(rh.quote("AAPL")), rh.quote_result(rh.quote("MSFT"))]), "2 quote rows"),
+ (rh.envelope("get_equity_quotes", {"results": [], "surprise": 1}), "unmapped data keys: surprise"),
+ (rh.quotes([{"close": rh.settled_close("AAPL")}]), "results[0] has no quote"),
+ (rh.quotes([_broken_quote(quote={**rh.quote("AAPL"), "ghost": "1"})]), "unmapped fields: ghost"),
+ (
+ rh.quotes([_broken_quote(quote={k: v for k, v in rh.quote("AAPL").items() if k != "state"})]),
+ "quote is missing state",
+ ),
+ (rh.quotes([_broken_quote(quote={**rh.quote("AAPL"), "has_traded": "yes"})]), "has_traded is not a boolean"),
+ (rh.quotes([_broken_quote(close={"price": "1"})]), "close is missing"),
+ (rh.quotes(["a row"]), "results[0] is not an object"),
+ ],
+)
+def test_quote_replies_that_are_not_the_advertised_shape(envelope: dict, message: str) -> None:
+ normalized = mcp.normalize_result("quote", envelope)
+
+ if message:
+ assert message in normalized.get("mapping_error", "")
+ assert "quote" not in normalized
+ else:
+ assert normalized.get("quote") is None
+
+
+# --------------------------------------------------------------------------- #
+# pagination #
+# --------------------------------------------------------------------------- #
+
+
+def test_records_still_refuse_a_lone_first_page() -> None:
+ with pytest.raises(mcp.RobinhoodShapeError, match="more than one page"):
+ mcp.records(rh.positions([rh.position("AAPL", "1")], next_page="cursor-2"), "positions", "get_equity_positions")
+
+
+def test_with_all_pages_follows_the_cursor_and_merges_every_page() -> None:
+ fetched: list[str] = []
+
+ def refetch(cursor: str) -> dict:
+ fetched.append(cursor)
+ if cursor == "cursor-2":
+ return rh.positions([rh.position("MSFT", "2")], next_page="cursor-3")
+ return rh.positions([rh.position("NVDA", "3")], next_page="")
+
+ merged = mcp.with_all_pages(
+ rh.positions([rh.position("AAPL", "1")], next_page="cursor-2"),
+ "positions",
+ "get_equity_positions",
+ refetch,
+ )
+
+ assert fetched == ["cursor-2", "cursor-3"]
+ assert [row["symbol"] for row in mcp.records(merged, "positions", "get_equity_positions")] == [
+ "AAPL",
+ "MSFT",
+ "NVDA",
+ ]
+ data = merged["structured_content"]["data"]
+ assert data["next"] == "" # the merged reply is one complete page
+ assert merged["data"] is merged["structured_content"] # both views stay the same object
+ assert merged["structured_content"]["guide"] == "Values are strings." # the first page's guide
+
+
+def test_with_all_pages_leaves_a_complete_reply_and_error_envelopes_untouched() -> None:
+ complete = rh.positions([])
+ failed = {"status": "error", "error": "token expired"}
+ unmappable = {"status": "ok"} # no data object: nothing to follow, mappers will name it
+
+ def unused_refetch(cursor: str) -> dict:
+ raise AssertionError(f"no page was owed for cursor {cursor!r}")
+
+ assert mcp.with_all_pages(complete, "positions", "get_equity_positions", unused_refetch) is complete
+ assert mcp.with_all_pages(failed, "positions", "get_equity_positions", unused_refetch) is failed
+ assert mcp.with_all_pages(unmappable, "positions", "get_equity_positions", unused_refetch) is unmappable
+
+
+def test_with_all_pages_drops_every_page_when_a_follow_up_fails() -> None:
+ def refetch(cursor: str) -> dict:
+ raise RuntimeError("token expired")
+
+ with pytest.raises(mcp.RobinhoodShapeError, match="next-page call failed: token expired"):
+ mcp.with_all_pages(
+ rh.positions([rh.position("AAPL", "1")], next_page="cursor-2"),
+ "positions",
+ "get_equity_positions",
+ refetch,
+ )
+
+
+def test_with_all_pages_refuses_a_cursor_that_never_ends(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(mcp, "_MAX_PAGES", 3)
+
+ def refetch(cursor: str) -> dict:
+ return rh.positions([rh.position(f"S{len(cursor)}", "1")], next_page=f"{cursor}x")
+
+ with pytest.raises(mcp.RobinhoodShapeError, match="did not reach a last page within 3 pages"):
+ mcp.with_all_pages(
+ rh.positions([rh.position("AAPL", "1")], next_page="c"),
+ "positions",
+ "get_equity_positions",
+ refetch,
+ )
+
+
+def test_the_trading_service_follows_position_pages_before_mapping(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ calls: list[tuple[str, dict]] = []
+ server = SimpleNamespace(
+ url="https://agent.robinhood.com/mcp/trading",
+ enabled_tools=["get_equity_positions"],
+ auth=SimpleNamespace(cache_dir="/tmp/vibe-token"),
+ )
+
+ class _Adapter:
+ def __init__(self, server_name, server_config, **kwargs): # noqa: ANN001
+ assert kwargs == {"interactive_oauth": False}
+
+ def call_tool(self, remote_name, arguments): # noqa: ANN001
+ calls.append((remote_name, dict(arguments)))
+ if arguments.get("cursor") == "cursor-2":
+ return rh.positions([rh.position("MSFT", "2")], next_page="")
+ return rh.positions([rh.position("AAPL", "1")], next_page="cursor-2")
+
+ monkeypatch.setattr(
+ "src.config.loader.load_agent_config", lambda: SimpleNamespace(mcp_servers={"robinhood": server})
+ )
+ monkeypatch.setattr("src.live.registry.has_cached_oauth_token", lambda *_: True)
+ monkeypatch.setattr("src.tools.mcp.MCPServerAdapter", _Adapter)
+
+ result = service.get_positions(
+ "robinhood-live-mcp-readonly", account=ACCOUNT, interactive_oauth=False
+ )
+
+ assert calls == [
+ ("get_equity_positions", {"account_number": ACCOUNT}),
+ ("get_equity_positions", {"account_number": ACCOUNT, "cursor": "cursor-2"}),
+ ]
+ assert [row["symbol"] for row in result["positions"]] == ["AAPL", "MSFT"]
+ assert "mapping_error" not in result
+
+
def test_trading_service_lists_accounts_through_get_accounts(monkeypatch: pytest.MonkeyPatch) -> None:
calls: list[tuple[str, dict]] = []
server = SimpleNamespace(
diff --git a/agent/tests/test_robinhood_portfolio_source.py b/agent/tests/test_robinhood_portfolio_source.py
index f5ffc6e48..63fa19ccc 100644
--- a/agent/tests/test_robinhood_portfolio_source.py
+++ b/agent/tests/test_robinhood_portfolio_source.py
@@ -37,6 +37,20 @@ class _Broker:
"get_portfolio": rh.portfolio(total_value="1500.00", cash="500.00"),
"get_equity_positions": rh.positions([]),
}
+ self.quotes_by_symbol: dict[str, str | dict] = {}
+ self.page_replies: dict[str, dict] = {}
+
+ def reply_for(self, remote_name: str, arguments: dict) -> dict:
+ cursor = arguments.get("cursor")
+ if cursor:
+ return self.page_replies[cursor]
+ if remote_name == "get_equity_quotes":
+ symbol = arguments["symbols"][0]
+ quoted = self.quotes_by_symbol.get(symbol)
+ if isinstance(quoted, dict):
+ return quoted # a fully-built envelope the test arranged
+ return rh.quotes([rh.quote_result(rh.quote(symbol, last_trade_price=quoted or "0"))])
+ return self.replies[remote_name]
def adapter_class(self):
broker = self
@@ -48,7 +62,7 @@ class _Broker:
def call_tool(self, remote_name, arguments): # noqa: ANN001
broker.calls.append((remote_name, dict(arguments)))
- return broker.replies[remote_name]
+ return broker.reply_for(remote_name, dict(arguments))
return _Adapter
@@ -111,7 +125,7 @@ def test_an_empty_account_is_a_complete_snapshot_read_for_the_selected_account(t
]
-def test_positions_are_listed_unpriced_and_quotes_are_never_called(tmp_path, broker: _Broker) -> None:
+def test_positions_are_priced_through_get_equity_quotes(tmp_path, broker: _Broker) -> None:
broker.replies["get_portfolio"] = rh.portfolio(total_value="2500.00", cash="500.00")
broker.replies["get_equity_positions"] = rh.positions(
[
@@ -119,19 +133,50 @@ def test_positions_are_listed_unpriced_and_quotes_are_never_called(tmp_path, bro
rh.position("MSFT", "2", average_buy_price=None),
]
)
+ broker.quotes_by_symbol = {"AAPL": "150.25", "MSFT": "400.10"}
snapshot = _service(tmp_path).refresh()
rows = {row["symbol"]: row for row in snapshot["positions"]}
assert rows["AAPL"]["quantity"] == 4.0
assert rows["AAPL"]["cost_price"] == 150.0
+ assert rows["AAPL"]["market_price"] == 150.25
+ assert rows["AAPL"]["priced"] is True
+ assert rows["AAPL"]["market_value_usd"] == 601.0
+ assert not rows["AAPL"].get("price_error")
assert rows["MSFT"]["cost_price"] is None # omitted while reconciling, never zero
- assert all(row["market_price"] is None for row in rows.values())
- assert all("quotes are not mapped" in row["price_error"] for row in rows.values())
+ assert rows["MSFT"]["market_price"] == 400.10
+ assert snapshot["accounts"][0]["status"] == "ok"
assert snapshot["accounts"][0]["total_usd"] == 2500.0
- assert snapshot["accounts"][0]["unpriced_or_other_usd"] == 2000.0
- assert any("No price available" in warning for warning in snapshot["warnings"])
- assert "get_equity_quotes" not in [name for name, _ in broker.calls]
+ # 2500 total - 500 cash - 4*150.25 - 2*400.10 priced
+ assert snapshot["accounts"][0]["unpriced_or_other_usd"] == 598.8
+ assert not any("No price available" in warning for warning in snapshot["warnings"])
+ assert snapshot["complete"] is True
+ assert ("get_equity_quotes", {"symbols": ["AAPL"]}) in broker.calls
+ assert ("get_equity_quotes", {"symbols": ["MSFT"]}) in broker.calls
+
+
+def test_a_quote_read_that_fails_to_map_leaves_the_row_unpriced_with_the_reason(
+ tmp_path, broker: _Broker
+) -> None:
+ broker.replies["get_equity_positions"] = rh.positions(
+ [
+ rh.position("AAPL", "4", average_buy_price="150.00"),
+ rh.position("MSFT", "2", average_buy_price=None),
+ ]
+ )
+ missing_state = rh.quote("MSFT")
+ del missing_state["state"]
+ broker.quotes_by_symbol = {"AAPL": "150.25", "MSFT": rh.quotes([rh.quote_result(missing_state)])}
+
+ snapshot = _service(tmp_path).refresh()
+
+ rows = {row["symbol"]: row for row in snapshot["positions"]}
+ assert rows["AAPL"]["priced"] is True
+ assert rows["MSFT"]["priced"] is False
+ assert rows["MSFT"]["market_price"] is None
+ assert "quote is missing state" in rows["MSFT"]["price_error"]
+ assert any("robinhood:MSFT" in warning for warning in snapshot["warnings"])
@pytest.mark.parametrize("field", ["options_value", "crypto_value", "futures_value", "fixed_income_value"])
@@ -165,7 +210,6 @@ def test_an_unreported_non_equity_value_is_not_read_as_zero(tmp_path, broker: _B
@pytest.mark.parametrize(
("reply", "message"),
[
- (rh.positions([rh.position("AAPL", "1")], next_page="cursor-2"), "more than one page"),
(rh.positions(None), "no positions list"),
(rh.positions([None]), "is not an object"),
],
@@ -181,6 +225,47 @@ def test_a_partial_or_null_position_read_is_an_error_not_an_empty_account(
assert message in account["error"]
+def test_positions_across_pages_become_one_whole_account(tmp_path, broker: _Broker) -> None:
+ broker.replies["get_equity_positions"] = rh.positions(
+ [rh.position("AAPL", "1")], next_page="cursor-2"
+ )
+ broker.page_replies["cursor-2"] = rh.positions([rh.position("MSFT", "2")], next_page="")
+ broker.quotes_by_symbol = {"AAPL": "150.25", "MSFT": "400.10"}
+
+ snapshot = _service(tmp_path).refresh()
+
+ account = snapshot["accounts"][0]
+ assert account["status"] == "ok"
+ assert account["total_usd"] == 1500.0
+ assert sorted(row["symbol"] for row in snapshot["positions"]) == ["AAPL", "MSFT"]
+ assert all(row["priced"] for row in snapshot["positions"])
+ assert snapshot["complete"] is True
+ assert broker.calls == [
+ ("get_portfolio", {"account_number": ACCOUNT}),
+ ("get_equity_positions", {"account_number": ACCOUNT}),
+ ("get_equity_positions", {"account_number": ACCOUNT, "cursor": "cursor-2"}),
+ ("get_equity_quotes", {"symbols": ["AAPL"]}),
+ ("get_equity_quotes", {"symbols": ["MSFT"]}),
+ ]
+
+
+def test_a_failed_second_page_errors_the_source_instead_of_showing_partial_holdings(
+ tmp_path, broker: _Broker
+) -> None:
+ broker.replies["get_equity_positions"] = rh.positions(
+ [rh.position("AAPL", "1")], next_page="cursor-2"
+ ) # no page_replies entry: the follow-up call fails
+
+ snapshot = _service(tmp_path).refresh()
+
+ account = snapshot["accounts"][0]
+ assert account["status"] == "error"
+ assert "next-page call failed" in account["error"]
+ assert snapshot["positions"] == []
+ assert account["total_usd"] is None
+ assert snapshot["complete"] is False
+
+
def test_a_missing_total_value_is_an_error_not_a_zero_account(tmp_path, broker: _Broker) -> None:
envelope = rh.portfolio()
del envelope["structured_content"]["data"]["total_value"]