Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(macro): report when get_macro_series caps the series

cgycoreya8e7994b43cf
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 48bee3962..9c9bb753c 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -2304,7 +2304,9 @@ def get_macro_series(
series_id: FRED series identifier (e.g. "CPIAUCSL", "UNRATE").
start_date: Inclusive window start, YYYY-MM-DD. Omit for full history.
end_date: Inclusive window end, YYYY-MM-DD. Omit for the latest date.
- limit: Maximum number of most-recent observations to return.
+ limit: Maximum number of most-recent observations to return (max
+ 5000). A series longer than that is capped and says so in the
+ result: truncated, observations_available, and a hint.
"""
params: dict[str, Any] = {"series_id": series_id, "limit": limit}
if start_date:
diff --git a/agent/src/tools/fred_macro_tool.py b/agent/src/tools/fred_macro_tool.py
index a535bf740..7ee022e1c 100644
--- a/agent/src/tools/fred_macro_tool.py
+++ b/agent/src/tools/fred_macro_tool.py
@@ -87,7 +87,11 @@ class FredMacroTool(BaseTool):
"type": "integer",
"description": (
"Maximum number of most-recent observations to return "
- f"(1-{_MAX_LIMIT}). Defaults to {_DEFAULT_LIMIT}."
+ f"(1-{_MAX_LIMIT}). Defaults to {_DEFAULT_LIMIT}. A longer "
+ "series is capped rather than refused: the envelope "
+ "reports truncated and observations_available, plus a hint "
+ "naming the way out (raise this where the cap allows it, "
+ "or narrow the date window)."
),
"default": _DEFAULT_LIMIT,
},
@@ -116,8 +120,15 @@ class FredMacroTool(BaseTool):
Returns:
A JSON string envelope. On success:
``{"ok": true, "market": "US", "source": "fred",
- "data": {"series_id", "observations": [{"date", "value"}, ...],
- "count"}}``. On failure: ``{"ok": false, "error": str}``.
+ "data": {"series_id", "count", "observations_available",
+ "truncated", "limit", "observations": [{"date", "value"}, ...]}}``.
+ The series is capped at ``limit`` observations, keeping the most
+ recent ones; ``truncated`` says whether that cap bit,
+ ``observations_available`` is the count before capping, and a
+ ``hint`` names the way out. The scalars are emitted before
+ ``observations`` so a capped series still reports itself after the
+ tool-result character cap trims the array. On failure:
+ ``{"ok": false, "error": str}``.
"""
api_key = get_env_config().data.fred_api_key or None
if not api_key:
@@ -161,17 +172,42 @@ class FredMacroTool(BaseTool):
# Keep the most recent observations when the cap is exceeded; FRED serves
# oldest-first, so the tail holds the newest records.
capped = observations[-limit:]
+ # A capped series must not read as a complete one: the caller asked for a
+ # date window and would otherwise take the returned tail for the whole
+ # window. Mirrors the convention get_market_data's own cap uses (cap_rows
+ # in agent/src/market_data.py): flag it, and say the way out.
+ available = len(observations)
+ truncated = available > limit
+
+ data: dict[str, Any] = {
+ "series_id": series_id,
+ "count": len(capped),
+ "observations_available": available,
+ "truncated": truncated,
+ "limit": limit,
+ }
+ if truncated:
+ # At the ceiling, "raise limit" is advice the caller cannot take.
+ if limit < _MAX_LIMIT:
+ remedy = f"raise limit (max {_MAX_LIMIT}) or narrow the date window"
+ else:
+ remedy = "narrow the date window"
+ data["hint"] = (
+ f"returned the {limit} most recent of {available} observations; "
+ f"{remedy}"
+ )
+ # The array goes last so the report above survives the tool-result
+ # character cap (TOOL_RESULT_LIMIT, src/config/limits.py), which cuts an
+ # oversized envelope to a prefix. Behind 2,000 rows of observations the
+ # cap report never reaches the caller it exists for.
+ data["observations"] = capped
return json.dumps(
{
"ok": True,
"market": "US",
"source": "fred",
- "data": {
- "series_id": series_id,
- "observations": capped,
- "count": len(capped),
- },
+ "data": data,
},
ensure_ascii=False,
)
diff --git a/agent/tests/test_fred_macro_tool.py b/agent/tests/test_fred_macro_tool.py
index af13f57bc..5fa31bf21 100644
--- a/agent/tests/test_fred_macro_tool.py
+++ b/agent/tests/test_fred_macro_tool.py
@@ -8,8 +8,10 @@ so we monkeypatch that name on the ``fred_macro_tool`` module.
from __future__ import annotations
import json
+from datetime import date, timedelta
from typing import Any, Dict
+from src.config.limits import TOOL_RESULT_LIMIT, truncate_tool_result
from src.tools import fred_macro_tool
from src.tools.fred_macro_tool import FredMacroTool
@@ -179,3 +181,131 @@ class TestParsing:
payload = {"observations": [{"value": "1.0"}, {"date": "2024-01-01", "value": "2.0"}]}
rows = fred_macro_tool._parse_observations(payload)
assert rows == [{"date": "2024-01-01", "value": 2.0}]
+
+
+# ---------------------------------------------------------------------------
+# Truncation reporting
+# ---------------------------------------------------------------------------
+
+
+def _long_payload(count: int) -> Dict[str, Any]:
+ """``count`` ascending daily observations, oldest first, from 2000-01-01."""
+ start = date(2000, 1, 1)
+ return {
+ "observations": [
+ {"date": (start + timedelta(days=i)).isoformat(), "value": str(float(i))}
+ for i in range(count)
+ ]
+ }
+
+
+class TestTruncationReporting:
+ """A capped series reports the cap instead of looking complete."""
+
+ def _run(self, monkeypatch, count: int, **kwargs: Any) -> Dict[str, Any]:
+ monkeypatch.setenv("FRED_API_KEY", "tok_123")
+ monkeypatch.setattr(
+ fred_macro_tool,
+ "throttled_get_json",
+ lambda url, **kw: _long_payload(count),
+ )
+ return json.loads(FredMacroTool().execute(series_id="UNRATE", **kwargs))
+
+ def test_cap_is_reported(self, monkeypatch):
+ available = 2_500
+ out = self._run(monkeypatch, available)
+ data = out["data"]
+
+ assert data["count"] == fred_macro_tool._DEFAULT_LIMIT
+ assert data["truncated"] is True
+ assert data["observations_available"] == available
+ assert data["limit"] == fred_macro_tool._DEFAULT_LIMIT
+ assert str(fred_macro_tool._DEFAULT_LIMIT) in data["hint"]
+ assert str(available) in data["hint"]
+ # Below the ceiling the raise clause is offered, not just the window.
+ assert "raise limit" in data["hint"]
+ # The tail is kept: the window still ends on the newest observation and
+ # starts exactly ``limit`` rows before it.
+ newest = date(2000, 1, 1) + timedelta(days=available - 1)
+ oldest = date(2000, 1, 1) + timedelta(
+ days=available - fred_macro_tool._DEFAULT_LIMIT
+ )
+ assert data["observations"][-1]["date"] == newest.isoformat()
+ assert data["observations"][0]["date"] == oldest.isoformat()
+
+ def test_series_that_fits_is_not_marked_truncated(self, monkeypatch):
+ out = self._run(monkeypatch, fred_macro_tool._DEFAULT_LIMIT)
+ data = out["data"]
+
+ assert data["truncated"] is False
+ assert data["observations_available"] == data["count"]
+ assert "hint" not in data
+
+ def test_raised_limit_uncaps_the_series(self, monkeypatch):
+ out = self._run(monkeypatch, 2_500, limit=2_500)
+ data = out["data"]
+
+ assert data["count"] == 2_500
+ assert data["truncated"] is False
+ # The limit is echoed as asked, not swapped for the default.
+ assert data["limit"] == 2_500
+
+ def test_limit_above_the_ceiling_reports_the_ceiling(self, monkeypatch):
+ out = self._run(monkeypatch, 6_000, limit=fred_macro_tool._MAX_LIMIT + 5_000)
+ data = out["data"]
+
+ assert data["limit"] == fred_macro_tool._MAX_LIMIT
+ assert data["count"] == fred_macro_tool._MAX_LIMIT
+ assert data["truncated"] is True
+ # No dead advice: a limit already at its ceiling cannot be raised.
+ assert "raise limit" not in data["hint"]
+ assert "narrow the date window" in data["hint"]
+
+ def test_one_row_over_the_cap_is_reported(self, monkeypatch):
+ # The boundary: one row over the cap is a cut, not a fit.
+ out = self._run(monkeypatch, fred_macro_tool._DEFAULT_LIMIT + 1)
+ data = out["data"]
+
+ assert data["count"] == fred_macro_tool._DEFAULT_LIMIT
+ assert data["observations_available"] == fred_macro_tool._DEFAULT_LIMIT + 1
+ assert data["truncated"] is True
+
+ def test_below_the_limit_the_request_is_echoed(self, monkeypatch):
+ # The below-cap regime: the limit is echoed as asked and
+ # observations_available is the parsed count, not the cap.
+ out = self._run(monkeypatch, 3, limit=3_000)
+ data = out["data"]
+
+ assert data["observations_available"] == 3
+ assert data["limit"] == 3_000
+ assert data["truncated"] is False
+
+ def test_hint_offers_the_raise_clause_below_the_ceiling(self, monkeypatch):
+ # A cap below the tool's own ceiling offers both remedies, even when the
+ # series is longer than the ceiling itself.
+ out = self._run(monkeypatch, 6_000, limit=fred_macro_tool._DEFAULT_LIMIT)
+ data = out["data"]
+
+ assert data["observations_available"] == 6_000
+ assert "raise limit" in data["hint"]
+ assert "narrow the date window" in data["hint"]
+
+ def test_cap_report_survives_the_tool_result_cap(self, monkeypatch):
+ # The agent loop trims every tool result to TOOL_RESULT_LIMIT characters.
+ # A cap report serialized behind the observation array is cut away in
+ # exactly the long-series case it exists for.
+ monkeypatch.setenv("FRED_API_KEY", "tok_123")
+ monkeypatch.setattr(
+ fred_macro_tool,
+ "throttled_get_json",
+ lambda url, **kw: _long_payload(2_500),
+ )
+ envelope = FredMacroTool().execute(series_id="UNRATE")
+ delivered = truncate_tool_result(envelope)
+
+ assert len(envelope) > TOOL_RESULT_LIMIT
+ assert len(delivered) <= TOOL_RESULT_LIMIT
+ for field in ("observations_available", "truncated", "limit", "hint"):
+ assert f'"{field}"' in delivered
+ # The observations are the part that gets cut.
+ assert delivered.count('"date"') < fred_macro_tool._DEFAULT_LIMIT