options-scanner / mcp_server.py
Reckless88's picture
MCP server: 7 tools wrapping the engine
8587686 verified
Raw History Blame Contribute Delete
13.4 kB
"""Options Scanner MCP server.
Exposes the options_scanner engine as MCP tools: universe scanning,
per-symbol strategy building, chain summaries, and position/roll checks.
Run (stdio transport, what Claude Desktop / Hermes expect):
python mcp_server.py
Data provider is auto-selected from the environment:
TRADIER_API_KEY real-time, full greeks/OI
ALPACA_KEY_ID+SECRET real-time IEX (thin quotes, no OI)
POLYGON_API_KEY real-time snapshot
(none set) Yahoo Finance, ~15-min delayed
This server reads market data and computes structures. It never places
orders.
"""
import json
from dataclasses import asdict
# SDK compatibility: current main is mcp.server.mcpserver.MCPServer; the
# released 1.x package still exposes the same decorator API as FastMCP.
try:
from mcp.server.mcpserver import MCPServer
except ImportError: # pragma: no cover - released SDK
from mcp.server.fastmcp import FastMCP as MCPServer
from options_scanner.config import RiskParams, LARGE_CAPS, HIGH_IV_CANDIDATES, LIQUID_ETFS
from options_scanner.data import get_provider
from options_scanner.strategies import ALL_BUILDERS
from options_scanner.risk import passes_liquidity, passes_defined_risk, risk_report, score
from options_scanner.rolling import Position, check, DEFAULT_ROLL_RULES
from options_scanner.universe import auto_universe
from options_scanner.scan import scan_symbol as engine_scan_symbol
mcp = MCPServer("options-scanner")
STRATEGY_FAMILIES = {
"vertical": "Bull/Bear credit and debit spreads",
"calendar": "Same-strike call/put calendars",
"diagonal": "Offset-strike diagonals (long theta)",
"butterfly": "Long call butterfly + iron butterfly",
"iron_condor": "Iron condor (credit, defined risk)",
"ratio_backspread": "1x2 call ratio backspread",
"jade_lizard": "Short put + call spread credit combo",
"double_diagonal": "Short strangle with long back-month wings",
"short_straddle": "Naked straddle (blocked unless allow_undefined_risk)",
"short_strangle": "Naked strangle (blocked unless allow_undefined_risk)",
}
def _params(account_size=25000.0, risk_pct=5.0, allow_undefined_risk=False,
min_oi=100, max_rel_spread=0.25, credit_short_delta=0.30,
condor_short_delta=0.20, min_dte=5, max_dte=45) -> RiskParams:
return RiskParams(
account_size=account_size, max_buying_power_pct=risk_pct,
allow_undefined_risk=allow_undefined_risk, min_oi=min_oi,
max_rel_spread=max_rel_spread, credit_short_delta=credit_short_delta,
condor_short_delta=condor_short_delta, min_dte=min_dte, max_dte=max_dte,
)
def _candidates_json(symbol, cands):
return {"symbol": symbol, "count": len(cands),
"candidates": [{"strategy": c.name, "view": c.view,
"legs": [l.label() for l, _ in c.legs],
"credit_debit_usd": round(c.net_credit * 100, 2),
"risk": risk_report(c),
"score": c.score, "notes": c.notes,
"reasons": c.reasons} for c in cands]}
# ---------- impl functions (plain Python, unit-testable) ----------
def impl_scan_universe(symbols=None, provider=None, max_expiries=5,
account_size=25000.0, risk_pct=5.0,
allow_undefined_risk=False, top_n=15):
params = _params(account_size, risk_pct, allow_undefined_risk)
prov = get_provider(provider)
universe = ([s.strip().upper() for s in symbols.split(",") if s.strip()]
if symbols else auto_universe())
rows, errors = [], []
for sym in universe:
try:
_, cands, err = engine_scan_symbol(prov, sym, params, max_expiries)
if err:
errors.append({"symbol": sym, "error": err})
continue
rows.extend({"symbol": sym, "strategy": c.name, "view": c.view,
"credit_debit_usd": round(c.net_credit * 100, 2),
"max_profit_usd": round(c.max_profit * 100, 2),
"max_loss_usd": round(c.max_loss * 100, 2),
"pop_pct": round(c.pop * 100, 1), "score": c.score,
"legs": " ; ".join(l.label() for l, _ in c.legs),
"breakevens": ",".join(str(b) for b in c.breakevens),
"notes": c.notes}
for c in cands)
except Exception as e:
errors.append({"symbol": sym, "error": str(e)[:200]})
rows.sort(key=lambda r: r["score"], reverse=True)
return {"provider": prov.name, "scanned": len(universe) - len(errors),
"universe_size": len(universe), "candidates_found": len(rows),
"top": rows[:top_n], "errors": errors}
def impl_scan_symbol(symbol, provider=None, max_expiries=5,
account_size=25000.0, risk_pct=5.0,
allow_undefined_risk=False):
params = _params(account_size, risk_pct, allow_undefined_risk)
prov = get_provider(provider)
params.max_candidates_per_symbol = 999 # return everything, caller filters
_, cands, err = engine_scan_symbol(prov, symbol.strip().upper(), params, max_expiries)
return _candidates_json(symbol.strip().upper(), cands) if not err else {"error": err}
def impl_build_strategy(symbol, strategy, provider=None, account_size=25000.0,
risk_pct=5.0, allow_undefined_risk=False):
"""Build one named structure family on a symbol. `strategy` matches the
family keys from list_strategies (e.g. iron_condor, jade_lizard)."""
params = _params(account_size, risk_pct, allow_undefined_risk)
params.max_candidates_per_symbol = 999
prov = get_provider(provider)
sym = symbol.strip().upper()
_, cands, err = engine_scan_symbol(prov, sym, params, 5)
if err:
return {"error": err}
key = strategy.strip().lower().replace("-", "_").replace(" ", "_")
needle = STRATEGY_FAMILIES.get(key)
if needle is None:
return {"error": f"unknown strategy '{strategy}'. Use list_strategies."}
# match by family keywords in the candidate name
aliases = {"vertical": "Spread", "calendar": "Calendar",
"diagonal": "Diagonal", "butterfly": "Butterfly",
"iron_condor": "Iron Condor", "ratio_backspread": "Backspread",
"jade_lizard": "Jade Lizard", "double_diagonal": "Double Diagonal",
"short_straddle": "Straddle", "short_strangle": "Strangle"}
want = aliases[key]
hits = [c for c in cands if want.lower() in c.name.lower()]
if not hits:
return {"symbol": sym, "count": 0,
"note": f"no {needle} built for {sym} — usually a wing/strike "
f"missing from the provider feed (the builder refuses to "
f"fake strikes), or a liquidity/earnings gate rejection.",
"families_that_did_build": sorted({c.name for c in cands})}
return _candidates_json(sym, hits[:4])
def impl_chain_summary(symbol, provider=None, max_expiries=6):
prov = get_provider(provider)
chain = prov.get_chain(symbol.strip().upper(), max_expiries=max_expiries)
exps = chain.expirations()
return {"symbol": chain.symbol, "provider": prov.name, "spot": round(chain.spot, 2),
"iv30_pct": round(chain.iv30 * 100, 1),
"next_earnings": chain.next_earnings or None,
"expirations": exps[:max_expiries],
"quote_count": len(chain.quotes),
"front_liquidity": round(chain.liquidity_score(exps[0]), 1) if exps else 0.0}
def impl_check_position(position, symbol, provider=None,
profit_target_pct=0.50, stop_loss_mult=2.0,
roll_dte=21, tested_delta=0.40):
"""position: list of legs [{kind:'C'|'P', strike, expiry:'YYYY-MM-DD',
side:+1|-1, qty}], plus entry_credit (per share, >0 credit) and
entry_date. Returns close/roll/hold recommendations."""
prov = get_provider(provider)
chain = prov.get_chain(symbol.strip().upper(), max_expiries=6)
pos = Position(symbol=symbol.strip().upper(),
structure=str(position.get("structure", "custom")),
legs=[(l["kind"], float(l["strike"]), l["expiry"],
int(l["side"]), int(l.get("qty", 1)))
for l in position["legs"]],
entry_credit=float(position.get("entry_credit", 0.0)),
entry_date=str(position.get("entry_date", "")))
rules = dict(DEFAULT_ROLL_RULES, profit_target_pct=profit_target_pct,
stop_loss_mult=stop_loss_mult, roll_dte=roll_dte,
tested_delta=tested_delta)
actions = check(pos, chain, rules)
return {"symbol": pos.symbol, "spot": round(chain.spot, 2),
"dte_left": min(chain.get(k, e, kk).dte
for kk, k, e, s, q in pos.legs
if chain.get(k, e, kk)),
"actions": [{"action": a.action, "reason": a.reason,
"urgency": a.urgency,
"proposed_legs": [list(x) for x in a.proposed_legs]}
for a in actions]}
def impl_list_strategies():
return {"families": STRATEGY_FAMILIES,
"defaults": {"credit_short_delta": 0.30, "condor_short_delta": 0.20,
"spread_width_usd": 10.0, "min_oi": 100,
"max_rel_spread": 0.25, "risk_pct_default": 5.0,
"roll_rules": DEFAULT_ROLL_RULES}}
def impl_list_watchlists():
return {"large_caps": LARGE_CAPS, "high_iv": HIGH_IV_CANDIDATES,
"sector_etfs": LIQUID_ETFS,
"auto_universe_size": len(auto_universe())}
# ---------- MCP tool registration ----------
@mcp.tool()
def scan_universe(symbols: str = "", provider: str = "", max_expiries: int = 5,
account_size: float = 25000.0, risk_pct: float = 5.0,
allow_undefined_risk: bool = False, top_n: int = 15) -> dict:
"""Run the multi-strategy scanner. Empty `symbols` = auto universe
(large caps + high-IV names + ETFs). Returns ranked candidates with
credit/debit, max profit/loss, POP, breakevens and legs. `provider`:
'' (auto) | tradier | alpaca | polygon | yfinance."""
return impl_scan_universe(symbols or None, provider or None, max_expiries,
account_size, risk_pct, allow_undefined_risk, top_n)
@mcp.tool()
def scan_symbol(symbol: str, provider: str = "", max_expiries: int = 5,
account_size: float = 25000.0, risk_pct: float = 5.0,
allow_undefined_risk: bool = False) -> dict:
"""Build every eligible strategy on one ticker, with full risk reports:
max profit/loss, POP, breakevens, per-leg labels and gate reasons."""
return impl_scan_symbol(symbol, provider or None, max_expiries,
account_size, risk_pct, allow_undefined_risk)
@mcp.tool()
def build_strategy(symbol: str, strategy: str, provider: str = "",
account_size: float = 25000.0, risk_pct: float = 5.0,
allow_undefined_risk: bool = False) -> dict:
"""Build a specific structure family on a symbol: vertical, calendar,
diagonal, butterfly, iron_condor, ratio_backspread, jade_lizard,
double_diagonal, short_straddle, short_strangle. Returns matching
candidates with legs and risk. See list_strategies for details."""
return impl_build_strategy(symbol, strategy, provider or None,
account_size, risk_pct, allow_undefined_risk)
@mcp.tool()
def chain_summary(symbol: str, provider: str = "", max_expiries: int = 6) -> dict:
"""Quick chain read on a ticker: spot, 30-day ATM IV, front expiry
liquidity score, next earnings date, quote count."""
return impl_chain_summary(symbol, provider or None, max_expiries)
@mcp.tool()
def check_position(position: dict, symbol: str, provider: str = "",
profit_target_pct: float = 0.50, stop_loss_mult: float = 2.0,
roll_dte: int = 21, tested_delta: float = 0.40) -> dict:
"""Position management with rolling mechanics. Pass the open position as
{"structure": "...", "entry_credit": 3.2, "entry_date": "2026-10-01",
"legs": [{"kind": "P", "strike": 279.0, "expiry": "2026-11-02",
"side": -1, "qty": 1}, ...]} (entry_credit per share, >0 =
credit received). Returns close/take-profit/roll-out/roll-down/roll-up
recommendations per the given rules."""
return impl_check_position(position, symbol, provider or None,
profit_target_pct, stop_loss_mult,
roll_dte, tested_delta)
@mcp.tool()
def list_strategies() -> dict:
"""All supported strategy families and the engine's default risk
parameters and roll rules."""
return impl_list_strategies()
@mcp.tool()
def list_watchlists() -> dict:
"""The built-in watchlist pools (large caps, high-IV names, sector ETFs)
and the auto universe size."""
return impl_list_watchlists()
if __name__ == "__main__":
import sys
if "--http" in sys.argv: # remote clients: http://127.0.0.1:8000/mcp
mcp.run(transport="streamable-http")
else:
mcp.run()