Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(mcp): unresolved symbols, finite options validation, row cap (#120)

Teerapat Vatpitak220abb10a129
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 7592eaf6e..ce2ba122b 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -27,6 +27,8 @@ Claude Desktop config:
from __future__ import annotations
import json
+import logging
+import math
import os
import re
import sys
@@ -42,6 +44,8 @@ from fastmcp import FastMCP
mcp = FastMCP("Vibe-Trading")
+logger = logging.getLogger(__name__)
+
# ---------------------------------------------------------------------------
# Lazy-loaded singletons
@@ -61,6 +65,7 @@ def _get_skills_loader():
global _skills_loader
if _skills_loader is None:
from src.agent.skills import SkillsLoader
+
_skills_loader = SkillsLoader()
return _skills_loader
@@ -69,6 +74,7 @@ def _get_registry():
global _registry
if _registry is None:
from src.tools import build_registry
+
_registry = build_registry(include_shell_tools=_include_shell_tools)
return _registry
@@ -77,6 +83,7 @@ def _get_registry():
# Skill tools
# ---------------------------------------------------------------------------
+
@mcp.tool
def list_skills() -> str:
"""List all available finance skills with names and descriptions.
@@ -111,6 +118,7 @@ def load_skill(name: str) -> str:
# Backtest tool
# ---------------------------------------------------------------------------
+
@mcp.tool
def backtest(run_dir: str) -> str:
"""Run a vectorized backtest using config.json and code/signal_engine.py.
@@ -133,6 +141,7 @@ def backtest(run_dir: str) -> str:
run_dir: Path to the run directory containing config.json and code/.
"""
from src.tools.backtest_tool import run_backtest
+
return run_backtest(run_dir)
@@ -140,6 +149,7 @@ def backtest(run_dir: str) -> str:
# Factor analysis tool
# ---------------------------------------------------------------------------
+
@mcp.tool
def factor_analysis(
codes: list[str],
@@ -165,17 +175,25 @@ def factor_analysis(
bottom_n: Number of bottom-ranked stocks per period.
"""
registry = _get_registry()
- return registry.execute("factor_analysis", {
- "codes": codes, "factor_name": factor_name,
- "start_date": start_date, "end_date": end_date,
- "source": source, "top_n": top_n, "bottom_n": bottom_n,
- })
+ return registry.execute(
+ "factor_analysis",
+ {
+ "codes": codes,
+ "factor_name": factor_name,
+ "start_date": start_date,
+ "end_date": end_date,
+ "source": source,
+ "top_n": top_n,
+ "bottom_n": bottom_n,
+ },
+ )
# ---------------------------------------------------------------------------
# Options pricing tool
# ---------------------------------------------------------------------------
+
@mcp.tool
def analyze_options(
spot: float,
@@ -196,17 +214,24 @@ def analyze_options(
option_type: "call" or "put".
"""
registry = _get_registry()
- return registry.execute("options_pricing", {
- "spot": spot, "strike": strike, "expiry_days": expiry_days,
- "risk_free_rate": risk_free_rate, "volatility": volatility,
- "option_type": option_type,
- })
+ return registry.execute(
+ "options_pricing",
+ {
+ "spot": spot,
+ "strike": strike,
+ "expiry_days": expiry_days,
+ "risk_free_rate": risk_free_rate,
+ "volatility": volatility,
+ "option_type": option_type,
+ },
+ )
# ---------------------------------------------------------------------------
# Pattern recognition tool
# ---------------------------------------------------------------------------
+
@mcp.tool
def pattern_recognition(run_dir: str) -> str:
"""Detect technical chart patterns (head-and-shoulders, double top/bottom,
@@ -226,6 +251,7 @@ def pattern_recognition(run_dir: str) -> str:
# Web & document reading tools
# ---------------------------------------------------------------------------
+
@mcp.tool
def read_url(url: str) -> str:
"""Fetch a web page and convert it to clean Markdown text.
@@ -237,6 +263,7 @@ def read_url(url: str) -> str:
url: Target URL to read.
"""
from src.tools.web_reader_tool import read_url as _read_url
+
return _read_url(url)
@@ -258,6 +285,7 @@ def read_document(file_path: str) -> str:
# Web search tool
# ---------------------------------------------------------------------------
+
@mcp.tool
def web_search(query: str, max_results: int = 5) -> str:
"""Search the web via DuckDuckGo and return top results.
@@ -270,15 +298,20 @@ def web_search(query: str, max_results: int = 5) -> str:
max_results: Maximum results to return (default 5, max 10).
"""
registry = _get_registry()
- return registry.execute("web_search", {
- "query": query, "max_results": min(max_results, 10),
- })
+ return registry.execute(
+ "web_search",
+ {
+ "query": query,
+ "max_results": min(max_results, 10),
+ },
+ )
# ---------------------------------------------------------------------------
# File I/O tools (sandboxed to workspace)
# ---------------------------------------------------------------------------
+
@mcp.tool
def write_file(path: str, content: str) -> str:
"""Write content to a file. Used to create config.json and signal_engine.py
@@ -307,6 +340,7 @@ def read_file(path: str) -> str:
# Swarm team tool
# ---------------------------------------------------------------------------
+
@mcp.tool
def list_swarm_presets() -> str:
"""List available swarm multi-agent team presets.
@@ -316,6 +350,7 @@ def list_swarm_presets() -> str:
Returns preset names, descriptions, agent counts, and required variables.
"""
from src.swarm.presets import list_presets
+
presets = list_presets()
return json.dumps(presets, ensure_ascii=False, indent=2)
@@ -361,15 +396,19 @@ def run_swarm(preset_name: str, variables: dict[str, str]) -> str:
{"id": t.id, "agent_id": t.agent_id, "status": t.status.value, "summary": t.summary}
for t in current.tasks
]
- return json.dumps({
- "status": current.status.value,
- "preset": preset_name,
- "run_id": current.id,
- "final_report": current.final_report,
- "tasks": tasks,
- "total_input_tokens": current.total_input_tokens,
- "total_output_tokens": current.total_output_tokens,
- }, ensure_ascii=False, indent=2)
+ return json.dumps(
+ {
+ "status": current.status.value,
+ "preset": preset_name,
+ "run_id": current.id,
+ "final_report": current.final_report,
+ "tasks": tasks,
+ "total_input_tokens": current.total_input_tokens,
+ "total_output_tokens": current.total_output_tokens,
+ },
+ ensure_ascii=False,
+ indent=2,
+ )
return json.dumps({"status": "error", "error": "Swarm timed out after 30 minutes"}, ensure_ascii=False)
@@ -378,6 +417,8 @@ def run_swarm(preset_name: str, variables: dict[str, str]) -> str:
# Market data tool
# ---------------------------------------------------------------------------
+DEFAULT_MAX_ROWS = 250
+
_SOURCE_PATTERNS = [
(re.compile(r"^\d{6}\.(SZ|SH|BJ)$", re.I), "tushare"),
(re.compile(r"^[A-Z]+\.US$", re.I), "yfinance"),
@@ -397,9 +438,40 @@ def _detect_source(code: str) -> str:
def _get_loader(source: str):
"""Get loader class via registry with fallback support."""
from backtest.loaders.registry import get_loader_cls_with_fallback
+
return get_loader_cls_with_fallback(source)
+def _cap_rows(records: list, max_rows: int) -> list | dict[str, object]:
+ """Bound a per-symbol row list to keep the MCP payload within budget.
+
+ max_rows==0 disables the cap (full list, unchanged shape). A negative
+ max_rows is invalid and enforces the default cap (never unbounded).
+ Otherwise an oversized symbol is *evenly strided* — every step-th bar,
+ with the last bar pinned — so the returned series spans the full range
+ (no head+tail gap, no synthetic ``_gap`` sentinel). Symbols within the
+ cap are returned unchanged (plain list) — small queries are
+ byte-identical.
+ """
+ n = len(records)
+ if max_rows < 0:
+ max_rows = DEFAULT_MAX_ROWS # negative invalid -> enforce cap, never unbounded
+ if max_rows == 0 or n <= max_rows:
+ return records
+ step = math.ceil(n / max_rows)
+ sampled = records[::step]
+ if sampled[-1] is not records[-1]:
+ sampled = sampled + [records[-1]]
+ return {
+ "rows": n,
+ "returned": len(sampled),
+ "truncated": True,
+ "policy": f"every-{step}th-row (even stride; last bar pinned)",
+ "hint": "narrow the date range, coarsen interval, or set max_rows=0 for all rows",
+ "data": sampled,
+ }
+
+
@mcp.tool
def get_market_data(
codes: list[str],
@@ -407,6 +479,7 @@ def get_market_data(
end_date: str,
source: str = "auto",
interval: str = "1D",
+ max_rows: int = DEFAULT_MAX_ROWS,
) -> str:
"""Fetch OHLCV market data for stocks, crypto, or mixed symbols.
@@ -424,6 +497,11 @@ def get_market_data(
end_date: End date (YYYY-MM-DD).
source: Data source ("auto", "yfinance", "okx", "tushare", "akshare", "ccxt").
interval: Bar size (1m/5m/15m/30m/1H/4H/1D, default "1D").
+ max_rows: Per-symbol row cap (default 250) so the response stays
+ within the MCP token budget. A symbol exceeding it returns an
+ even-stride downsample (every step-th bar, last bar pinned)
+ plus truncation metadata. Set max_rows=0 for all rows
+ (unbounded, legacy behavior).
"""
results = {}
@@ -438,7 +516,14 @@ def get_market_data(
for src, src_codes in groups.items():
loader_cls = _get_loader(src)
loader = loader_cls()
- data_map = loader.fetch(src_codes, start_date, end_date, interval=interval)
+ try:
+ data_map = loader.fetch(src_codes, start_date, end_date, interval=interval)
+ except Exception:
+ # A loader blow-up for one group must not lose already-resolved
+ # symbols or surface as an opaque MCP error; those codes fall
+ # through to _unresolved below (P05).
+ logger.exception("market-data loader %r failed for %s; codes fall through to _unresolved", src, src_codes)
+ data_map = {}
for symbol, df in data_map.items():
records = df.reset_index().to_dict(orient="records")
for r in records:
@@ -447,7 +532,16 @@ def get_market_data(
r[k] = v.isoformat()
elif hasattr(v, "item"):
r[k] = v.item()
- results[symbol] = records
+ results[symbol] = _cap_rows(records, max_rows)
+
+ # P05: a typo / wrong-suffix / delisted / no-data symbol used to vanish
+ # silently (the dict only held winners), indistinguishable from "no data".
+ # Surface every requested code that produced nothing under a reserved key.
+ # Additive: omitted entirely when all codes resolved, so the happy-path
+ # payload is byte-identical to before.
+ unresolved = [c for c in codes if c not in results]
+ if unresolved:
+ results["_unresolved"] = unresolved
return json.dumps(results, ensure_ascii=False, indent=2)
@@ -456,10 +550,12 @@ def get_market_data(
# Swarm status & history tools
# ---------------------------------------------------------------------------
+
def _get_swarm_store():
swarm_dir = AGENT_DIR / ".swarm" / "runs"
swarm_dir.mkdir(parents=True, exist_ok=True)
from src.swarm.store import SwarmStore
+
return SwarmStore(base_dir=swarm_dir)
@@ -532,14 +628,16 @@ def list_runs(limit: int = 20) -> str:
runs = store.list_runs(limit=limit)
items = []
for run in runs:
- items.append({
- "run_id": run.id,
- "preset": run.preset_name,
- "status": run.status.value,
- "created_at": run.created_at,
- "total_input_tokens": run.total_input_tokens,
- "total_output_tokens": run.total_output_tokens,
- })
+ items.append(
+ {
+ "run_id": run.id,
+ "preset": run.preset_name,
+ "status": run.status.value,
+ "created_at": run.created_at,
+ "total_input_tokens": run.total_input_tokens,
+ "total_output_tokens": run.total_output_tokens,
+ }
+ )
return json.dumps(items, ensure_ascii=False, indent=2)
@@ -547,6 +645,7 @@ def list_runs(limit: int = 20) -> str:
# Trade journal tool
# ---------------------------------------------------------------------------
+
@mcp.tool
def analyze_trade_journal(
file_path: str,
@@ -570,17 +669,21 @@ def analyze_trade_journal(
"symbol=600519.SH", "market=china_a").
"""
registry = _get_registry()
- return registry.execute("analyze_trade_journal", {
- "file_path": file_path,
- "analysis_type": analysis_type,
- "filter_expr": filter_expr,
- })
+ return registry.execute(
+ "analyze_trade_journal",
+ {
+ "file_path": file_path,
+ "analysis_type": analysis_type,
+ "filter_expr": filter_expr,
+ },
+ )
# ---------------------------------------------------------------------------
# Shadow Account tools (4)
# ---------------------------------------------------------------------------
+
@mcp.tool
def extract_shadow_strategy(
journal_path: str,
@@ -600,11 +703,14 @@ def extract_shadow_strategy(
max_rules: Maximum rules to return (typically 3-5).
"""
registry = _get_registry()
- return registry.execute("extract_shadow_strategy", {
- "journal_path": journal_path,
- "min_support": min_support,
- "max_rules": max_rules,
- })
+ return registry.execute(
+ "extract_shadow_strategy",
+ {
+ "journal_path": journal_path,
+ "min_support": min_support,
+ "max_rules": max_rules,
+ },
+ )
@mcp.tool
@@ -697,16 +803,15 @@ def scan_shadow_signals(
# Entry point
# ---------------------------------------------------------------------------
+
def main():
"""Entry point for `vibe-trading-mcp` CLI command."""
global _include_shell_tools, _registry
import argparse
parser = argparse.ArgumentParser(description="Vibe-Trading MCP Server")
- parser.add_argument("--transport", choices=["stdio", "sse"], default="stdio",
- help="MCP transport (default: stdio)")
- parser.add_argument("--port", type=int, default=8900,
- help="SSE port (only used with --transport sse)")
+ parser.add_argument("--transport", choices=["stdio", "sse"], default="stdio", help="MCP transport (default: stdio)")
+ parser.add_argument("--port", type=int, default=8900, help="SSE port (only used with --transport sse)")
args = parser.parse_args()
_include_shell_tools = True if args.transport == "stdio" else _env_shell_tools_enabled()
_registry = None
diff --git a/agent/src/tools/options_pricing_tool.py b/agent/src/tools/options_pricing_tool.py
index 51aa74ed3..7d1075b62 100644
--- a/agent/src/tools/options_pricing_tool.py
+++ b/agent/src/tools/options_pricing_tool.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import json
+import math
from typing import Any
import numpy as np
@@ -11,6 +12,36 @@ from scipy.stats import norm
from src.agent.tools import BaseTool
+def _validate_inputs(
+ spot: float, strike: float, expiry_days: float, sigma: float, r: float, option_type: str
+) -> str | None:
+ """Reject genuinely invalid inputs at the boundary (P06).
+
+ T == 0 is a *valid* expiry (handled downstream as intrinsic value), so
+ it is intentionally NOT rejected here — only invalid inputs are.
+ """
+ if option_type not in ("call", "put"):
+ return f"option_type must be 'call' or 'put', got {option_type!r}"
+ for _name, _val in (
+ ("spot", spot),
+ ("strike", strike),
+ ("expiry_days", expiry_days),
+ ("volatility", sigma),
+ ("risk_free_rate", r),
+ ):
+ if not math.isfinite(_val):
+ return f"{_name} must be a finite number, got {_val}"
+ if spot <= 0:
+ return f"spot must be positive, got {spot}"
+ if strike <= 0:
+ return f"strike must be positive, got {strike}"
+ if sigma <= 0:
+ return f"volatility must be positive, got {sigma}"
+ if expiry_days < 0:
+ return f"expiry_days must be non-negative, got {expiry_days}"
+ return None
+
+
def _bs_price_and_greeks(
spot: float,
strike: float,
@@ -42,7 +73,7 @@ def _bs_price_and_greeks(
return {"price": price, "delta": delta, "gamma": 0.0, "theta": 0.0, "vega": 0.0}
sqrt_T = np.sqrt(T)
- d1 = (np.log(spot / strike) + (r + sigma ** 2 / 2) * T) / (sigma * sqrt_T)
+ d1 = (np.log(spot / strike) + (r + sigma**2 / 2) * T) / (sigma * sqrt_T)
d2 = d1 - sigma * sqrt_T
nd1_pdf = float(norm.pdf(d1))
@@ -108,6 +139,13 @@ class OptionsPricingTool(BaseTool):
sigma = float(kwargs["volatility"])
option_type = kwargs["option_type"]
+ err = _validate_inputs(spot, strike, expiry_days, sigma, r, option_type)
+ if err is not None:
+ return json.dumps(
+ {"status": "error", "tool": "options_pricing", "error": err},
+ ensure_ascii=False,
+ )
+
T = expiry_days / 365.0
result = _bs_price_and_greeks(spot, strike, T, r, sigma, option_type)
@@ -120,6 +158,24 @@ class OptionsPricingTool(BaseTool):
"option_type": option_type,
"T_years": round(T, 6),
}
- result["status"] = "ok"
-
- return json.dumps(result, ensure_ascii=False)
+ nonfinite = any(
+ k not in result or not math.isfinite(float(result[k])) for k in ("price", "delta", "gamma", "theta", "vega")
+ )
+ if T == 0.0 or nonfinite:
+ result["status"] = "degenerate"
+ result["degenerate"] = True
+ result["warning"] = (
+ "option at expiry (T=0): Greeks are singular; intrinsic value returned"
+ if T == 0.0
+ else "non-finite result (extreme inputs); values unreliable"
+ )
+ else:
+ result["status"] = "ok"
+
+ try:
+ return json.dumps(result, ensure_ascii=False, allow_nan=False)
+ except ValueError as exc:
+ return json.dumps(
+ {"status": "error", "tool": "options_pricing", "error": f"non-serializable numeric result: {exc}"},
+ ensure_ascii=False,
+ )
diff --git a/agent/tests/test_get_market_data_size.py b/agent/tests/test_get_market_data_size.py
new file mode 100644
index 000000000..614e29099
--- /dev/null
+++ b/agent/tests/test_get_market_data_size.py
@@ -0,0 +1,120 @@
+"""Regression test for P07 — get_market_data must bound its per-symbol output.
+
+Pre-fix: every row of every symbol was emitted, so "1 symbol, 1 year, daily"
+(~251 rows) already breached the MCP token cap and had to spool to a file.
+Post-fix (G3): a `max_rows` cap (default 250) returns an *even-stride*
+downsample (every step-th bar, last bar pinned) plus truncation metadata for
+oversized symbols — spanning the full range with no `_gap` sentinel; small
+queries are unchanged (plain list); `max_rows=0` restores the unbounded
+legacy behavior; a negative `max_rows` is invalid and enforces the cap.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pandas as pd
+
+import mcp_server
+
+_gmd = getattr(mcp_server.get_market_data, "fn", None) or getattr(
+ mcp_server.get_market_data, "__wrapped__", mcp_server.get_market_data
+)
+
+
+def _loader_with_rows(n: int):
+ idx = pd.date_range("2025-01-01", periods=n, freq="D")
+ df = pd.DataFrame({"open": 1.0, "high": 1.0, "low": 1.0, "close": 1.0, "volume": 1.0}, index=idx)
+ df.index.name = "trade_date"
+
+ class _L:
+ def fetch(self, codes, start, end, interval="1D"):
+ return {"X.US": df}
+
+ return _L
+
+
+def _call(monkeypatch, n, **kw):
+ monkeypatch.setattr(mcp_server, "_get_loader", lambda src: _loader_with_rows(n))
+ return json.loads(_gmd(codes=["X.US"], start_date="2025-01-01", end_date="2026-01-01", source="yfinance", **kw))
+
+
+def test_oversized_symbol_is_capped_with_metadata(monkeypatch):
+ out = _call(monkeypatch, 300)["X.US"]
+ assert out["truncated"] is True
+ assert out["rows"] == 300
+ assert out["returned"] == len(out["data"])
+ assert out["returned"] <= 251 # 250-stride sample, last bar maybe pinned
+ assert "every-" in out["policy"]
+ assert not any(isinstance(row, dict) and "_gap" in row for row in out["data"])
+
+
+def test_small_query_unchanged_plain_list(monkeypatch):
+ """No-regression: under the cap the shape is the original plain list."""
+ out = _call(monkeypatch, 50)["X.US"]
+ assert isinstance(out, list) and len(out) == 50
+
+
+def test_max_rows_zero_disables_cap(monkeypatch):
+ out = _call(monkeypatch, 300, max_rows=0)["X.US"]
+ assert isinstance(out, list) and len(out) == 300
+
+
+def test_default_caps_canonical_one_year_daily(monkeypatch):
+ """The canonical ~251-row 1y-daily request must no longer be unbounded."""
+ out = _call(monkeypatch, 251)["X.US"]
+ assert isinstance(out, dict) and out["truncated"] is True
+
+
+def test_boundary_n_equals_max_rows_is_plain_list(monkeypatch):
+ """G3 (i): exactly at the cap returns the plain list, not truncated."""
+ out = _call(monkeypatch, 250, max_rows=250)["X.US"]
+ assert isinstance(out, list) and len(out) == 250
+
+
+def test_negative_max_rows_still_caps(monkeypatch):
+ """G3 (ii): a negative max_rows is invalid -> cap enforced, never unbounded."""
+ out = _call(monkeypatch, 300, max_rows=-1)["X.US"]
+ assert isinstance(out, dict)
+ assert out["truncated"] is True
+ assert out["returned"] == len(out["data"]) < 300
+
+
+def test_stride_form_last_pinned_increasing_no_gap(monkeypatch):
+ """G3 (iii): stride sample — last row == original last, dates strictly
+ increasing, and no {"_gap": ...} sentinel anywhere."""
+ out = _call(monkeypatch, 1000)["X.US"]
+ data = out["data"]
+ assert not any(isinstance(row, dict) and "_gap" in row for row in data)
+ dates = [row["trade_date"] for row in data]
+ assert dates == sorted(dates) and len(set(dates)) == len(dates)
+ # original series ends 2025-01-01 + 999 days; last sampled bar is pinned.
+ last_expected = pd.Timestamp("2025-01-01") + pd.Timedelta(days=999)
+ assert pd.Timestamp(data[-1]["trade_date"]) == last_expected
+
+
+def test_multi_symbol_capped_independently(monkeypatch):
+ """G3 (iv): each symbol in a multi-symbol payload is capped on its own."""
+ big = pd.date_range("2025-01-01", periods=400, freq="D")
+ small = pd.date_range("2025-01-01", periods=10, freq="D")
+
+ def _frame(idx):
+ df = pd.DataFrame({"open": 1.0, "high": 1.0, "low": 1.0, "close": 1.0, "volume": 1.0}, index=idx)
+ df.index.name = "trade_date"
+ return df
+
+ class _Multi:
+ def fetch(self, codes, start, end, interval="1D"):
+ return {"BIG.US": _frame(big), "SMALL.US": _frame(small)}
+
+ monkeypatch.setattr(mcp_server, "_get_loader", lambda src: _Multi)
+ out = json.loads(
+ _gmd(
+ codes=["BIG.US", "SMALL.US"],
+ start_date="2025-01-01",
+ end_date="2026-01-01",
+ source="yfinance",
+ )
+ )
+ assert isinstance(out["BIG.US"], dict) and out["BIG.US"]["truncated"] is True
+ assert isinstance(out["SMALL.US"], list) and len(out["SMALL.US"]) == 10
diff --git a/agent/tests/test_get_market_data_unresolved.py b/agent/tests/test_get_market_data_unresolved.py
new file mode 100644
index 000000000..25c5aa970
--- /dev/null
+++ b/agent/tests/test_get_market_data_unresolved.py
@@ -0,0 +1,96 @@
+"""Regression test for P05 — get_market_data must not silently drop a
+requested symbol that returned no data.
+
+Pre-fix: the result dict only held winners, so a typo / wrong-suffix /
+delisted / no-data code just vanished — indistinguishable from "no data",
+and a loader exception lost every already-resolved symbol. Post-fix: any
+unresolved requested code is surfaced under the reserved ``_unresolved``
+key (additive: omitted entirely when all codes resolve, so the happy-path
+payload is byte-identical to before), and a loader blow-up is contained.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+
+import pandas as pd
+import pytest
+
+import mcp_server
+
+# fastmcp wraps the tool; reach the raw callable.
+_gmd = getattr(mcp_server.get_market_data, "fn", None) or getattr(
+ mcp_server.get_market_data, "__wrapped__", mcp_server.get_market_data
+)
+
+
+def _df():
+ df = pd.DataFrame(
+ {"open": [1.0], "high": [1.0], "low": [1.0], "close": [1.0], "volume": [1.0]},
+ index=pd.to_datetime(["2026-05-01"]),
+ )
+ df.index.name = "trade_date"
+ return df
+
+
+class _GoodOnlyLoader:
+ def fetch(self, codes, start, end, interval="1D"):
+ return {"GOOD.US": _df()} if "GOOD.US" in codes else {}
+
+
+class _PartialLoader:
+ """Returns only a subset of the requested codes."""
+
+ def fetch(self, codes, start, end, interval="1D"):
+ return {c: _df() for c in codes if c.startswith("OK")}
+
+
+class _BoomLoader:
+ def fetch(self, codes, start, end, interval="1D"):
+ raise RuntimeError("simulated loader blow-up")
+
+
+def good_only(monkeypatch):
+ monkeypatch.setattr(mcp_server, "_get_loader", lambda src: _GoodOnlyLoader)
+
+
+def _call(codes):
+ return json.loads(_gmd(codes=codes, start_date="2026-05-01", end_date="2026-05-02", source="yfinance"))
+
+
+def test_unresolved_symbol_is_surfaced(good_only):
+ out = _call(["GOOD.US", "BOGUS.US"])
+ assert "GOOD.US" in out
+ assert out.get("_unresolved") == ["BOGUS.US"]
+
+
+def test_all_resolved_has_no_unresolved_key(good_only):
+ """Happy path must stay byte-identical (additive only)."""
+ out = _call(["GOOD.US"])
+ assert "GOOD.US" in out
+ assert "_unresolved" not in out
+
+
+def test_loader_exception_is_contained_not_lost(monkeypatch):
+ monkeypatch.setattr(mcp_server, "_get_loader", lambda src: _BoomLoader)
+ out = _call(["AAA.US", "BBB.US"]) # must not raise an opaque MCP error
+ assert sorted(out.get("_unresolved", [])) == ["AAA.US", "BBB.US"]
+
+
+def test_partial_loader_only_missing_codes_unresolved(monkeypatch):
+ """G2: a loader returning only SOME requested codes -> the rest land
+ under _unresolved (not silently dropped)."""
+ monkeypatch.setattr(mcp_server, "_get_loader", lambda src: _PartialLoader)
+ out = _call(["OK1.US", "OK2.US", "MISS1.US", "MISS2.US"])
+ assert "OK1.US" in out and "OK2.US" in out
+ assert sorted(out.get("_unresolved", [])) == ["MISS1.US", "MISS2.US"]
+
+
+def test_swallowed_loader_exception_is_logged(monkeypatch, caplog):
+ """G2: the contained loader blow-up must still be logged (was silent)."""
+ monkeypatch.setattr(mcp_server, "_get_loader", lambda src: _BoomLoader)
+ with caplog.at_level(logging.ERROR, logger=mcp_server.logger.name):
+ _call(["AAA.US", "BBB.US"])
+ assert any("market-data loader" in r.message for r in caplog.records)
diff --git a/agent/tests/test_options_pricing_degenerate.py b/agent/tests/test_options_pricing_degenerate.py
new file mode 100644
index 000000000..732f1362c
--- /dev/null
+++ b/agent/tests/test_options_pricing_degenerate.py
@@ -0,0 +1,98 @@
+"""Regression tests for P06 — analyze_options/options_pricing must not return
+confident `status:"ok"` numbers for degenerate or invalid inputs.
+
+Pre-fix: invalid inputs (σ≤0, spot/strike≤0, negative expiry, bad type) and
+T=0 all returned `status:"ok"`; NaN could leak into the JSON. Post-fix:
+invalid inputs are rejected with an error envelope, T=0 is flagged
+`status:"degenerate"` with a warning (intrinsic value still returned), and
+the normal path is numerically unchanged.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+from src.tools.options_pricing_tool import OptionsPricingTool
+
+
+def _run(**kw):
+ return json.loads(OptionsPricingTool().execute(**kw))
+
+
+def test_normal_path_unchanged_status_ok():
+ """ATM call 30d, r=0.05, σ=0.25 — authoritative BS reference values.
+ Guards against any regression in the happy path."""
+ out = _run(spot=100, strike=100, expiry_days=30, risk_free_rate=0.05, volatility=0.25, option_type="call")
+ assert out["status"] == "ok"
+ assert out["price"] == pytest.approx(3.0626, abs=1e-3)
+ assert out["delta"] == pytest.approx(0.537118, abs=1e-4)
+ assert out["gamma"] == pytest.approx(0.055421, abs=1e-4)
+ assert out["vega"] == pytest.approx(0.113878, abs=1e-4)
+
+
+def test_expiry_zero_is_degenerate_not_ok():
+ out = _run(spot=100, strike=100, expiry_days=0, risk_free_rate=0.05, volatility=0.25, option_type="call")
+ assert out["status"] == "degenerate"
+ assert out["degenerate"] is True
+ assert "warning" in out
+ assert out["price"] == 0.0 # ATM intrinsic at expiry — still correct
+
+
+def test_in_the_money_expiry_returns_intrinsic_degenerate():
+ out = _run(spot=120, strike=100, expiry_days=0, risk_free_rate=0.05, volatility=0.25, option_type="call")
+ assert out["status"] == "degenerate"
+ assert out["price"] == pytest.approx(20.0, abs=1e-9)
+
+
+ "kw",
+ [
+ {"spot": 100, "strike": 100, "expiry_days": 30, "volatility": 0.0, "option_type": "call"},
+ {"spot": 100, "strike": 100, "expiry_days": 30, "volatility": -0.2, "option_type": "call"},
+ {"spot": 0, "strike": 100, "expiry_days": 30, "volatility": 0.25, "option_type": "call"},
+ {"spot": 100, "strike": 0, "expiry_days": 30, "volatility": 0.25, "option_type": "call"},
+ {"spot": 100, "strike": 100, "expiry_days": -5, "volatility": 0.25, "option_type": "call"},
+ {"spot": 100, "strike": 100, "expiry_days": 30, "volatility": 0.25, "option_type": "straddle"},
+ ],
+)
+def test_invalid_inputs_rejected_with_error(kw):
+ out = _run(risk_free_rate=0.05, **kw)
+ assert out["status"] == "error"
+ assert "error" in out and out["error"]
+
+
+ "kw",
+ [
+ {"spot": 100, "strike": 100, "expiry_days": 30, "volatility": float("nan"), "option_type": "call"},
+ {"spot": float("inf"), "strike": 100, "expiry_days": 30, "volatility": 0.25, "option_type": "call"},
+ {
+ "spot": 100,
+ "strike": 100,
+ "expiry_days": 30,
+ "volatility": 0.25,
+ "risk_free_rate": float("nan"),
+ "option_type": "call",
+ },
+ ],
+)
+def test_non_finite_inputs_rejected_with_error(kw):
+ """G2: NaN/Inf in any numeric input is rejected before pricing."""
+ kw.setdefault("risk_free_rate", 0.05)
+ out = _run(**kw)
+ assert out["status"] == "error"
+ assert "error" in out and out["error"]
+ assert "finite" in out["error"]
+
+
+def test_output_is_strict_json_no_nan():
+ # json.loads already enforces strict JSON; assert it parses for all branches.
+ for kw in (
+ dict(spot=100, strike=100, expiry_days=30, volatility=0.25, option_type="put"),
+ dict(spot=100, strike=100, expiry_days=0, volatility=0.25, option_type="put"),
+ ):
+ raw = OptionsPricingTool().execute(risk_free_rate=0.03, **kw)
+ assert "NaN" not in raw and "Infinity" not in raw
+ json.loads(raw) # must not raise