"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
feat(mcp): expose the three QVeris tools over MCP (closes #964)
Haozhe Wu8d019e3f0eb2
diff --git a/README.md b/README.mdindex c9f5e0a33..dfe107d88 100644--- a/README.md+++ b/README.md@@ -1086,7 +1086,7 @@ Posting `{}` schedules a template on its own suggested cadence with its declared## 🔌 MCP Plugin-Vibe-Trading exposes 59 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. Core research tools work with zero API keys for HK/US/crypto; trading connector tools use the selected connector profile, and `run_swarm` needs an LLM key.+Vibe-Trading exposes 62 MCP tools for any MCP-compatible client. Runs as a stdio subprocess — no server setup needed. Core research tools work with zero API keys for HK/US/crypto; trading connector tools use the selected connector profile, and `run_swarm` needs an LLM key.**Environment variables:** the client spawns the server itself, so a shell `export` never reaches it — set them in the client's `env` block. Generated backtest code is sandboxed to the allowed run roots, so writing results into a workspace of your own needs `VIBE_TRADING_ALLOWED_RUN_ROOTS`:@@ -1155,7 +1155,7 @@ with `--host` / `--port`.</details>-**MCP tools exposed (59):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`.+**MCP tools exposed (62):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`.### SWARM external MCP tools@@ -1490,7 +1490,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 59 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 62 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent corediff --git a/README_ar.md b/README_ar.mdindex 98bdc6e01..e12589281 100644--- a/README_ar.md+++ b/README_ar.md@@ -1056,7 +1056,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \## 🔌 MCP Plugin-يعرض Vibe-Trading 59 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.+يعرض Vibe-Trading 62 أداة MCP لأي عميل متوافق مع MCP. يعمل كعملية stdio فرعية، دون إعداد خادم. أدوات البحث الأساسية تعمل دون أي مفاتيح API لأسواق HK/US/crypto؛ وأدوات connector للتداول تستخدم profile الموصل المختار، ويحتاج `run_swarm` وحده إلى مفتاح LLM.**متغيرات البيئة:** العميل هو من يشغّل الخادم بنفسه، لذا لا يصل إليه `export` من الـ shell أبداً —— اضبطها في كتلة `env` الخاصة بالعميل. كود الاختبار الخلفي المولَّد محصور ضمن جذور التشغيل المسموح بها، لذا تحتاج إلى `VIBE_TRADING_ALLOWED_RUN_ROOTS` لكتابة النتائج في دليل عمل خاص بك:@@ -1112,7 +1112,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**أدوات MCP المعروضة (59):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`.+**أدوات MCP المعروضة (62):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`.### أدوات MCP الخارجية في SWARM@@ -1433,7 +1433,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 59 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 62 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent corediff --git a/README_ja.md b/README_ja.mdindex 44352afae..5b53dcaf5 100644--- a/README_ja.md+++ b/README_ja.md@@ -1053,7 +1053,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \## 🔌 MCP Plugin-Vibe-Trading は MCP-compatible client 向けに 59 MCP tools を公開します。stdio subprocess として動作し、server setup は不要です。Core research tools は HK/US/crypto で API key なしに動作し、trading connector tools は選択中の connector profile を使います。LLM key が必要なのは `run_swarm` のみです。+Vibe-Trading は MCP-compatible client 向けに 62 MCP tools を公開します。stdio subprocess として動作し、server setup は不要です。Core research tools は HK/US/crypto で API key なしに動作し、trading connector tools は選択中の connector profile を使います。LLM key が必要なのは `run_swarm` のみです。**環境変数:** server は client 自身が spawn するため、shell の `export` は届きません —— client の `env` block に設定してください。生成された backtest code は allowed run roots 内に制限されるので、結果を自分の作業 directory に書き出すには `VIBE_TRADING_ALLOWED_RUN_ROOTS` が必要です:@@ -1109,7 +1109,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**公開される MCP tools(59):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`.+**公開される MCP tools(62):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`.### SWARM の外部 MCP tools@@ -1436,7 +1436,7 @@ Vibe-Trading/├── agent/ # バックエンド (Python)│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 59 tools+│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 62 tools│ ││ ├── src/│ │ ├── agent/ # ReAct エージェントコアdiff --git a/README_ko.md b/README_ko.mdindex 0f6e8844c..17cbc5f0e 100644--- a/README_ko.md+++ b/README_ko.md@@ -1056,7 +1056,7 @@ curl -X POST http://localhost:8899/scheduled-runs/playbooks/premarket-brief \## 🔌 MCP Plugin-Vibe-Trading은 모든 MCP-compatible client를 위해 59개 MCP tools를 제공합니다. stdio subprocess로 실행되므로 server setup이 필요 없습니다. 핵심 research tools는 HK/US/crypto에서 API key 없이 작동하고, trading connector tools는 선택된 connector profile을 사용하며, `run_swarm`만 LLM key가 필요합니다.+Vibe-Trading은 모든 MCP-compatible client를 위해 62개 MCP tools를 제공합니다. stdio subprocess로 실행되므로 server setup이 필요 없습니다. 핵심 research tools는 HK/US/crypto에서 API key 없이 작동하고, trading connector tools는 선택된 connector profile을 사용하며, `run_swarm`만 LLM key가 필요합니다.**환경 변수:** server는 client가 직접 spawn하므로 shell의 `export`는 전달되지 않습니다 —— client의 `env` block에 설정하세요. 생성된 backtest code는 allowed run roots 안으로 제한되므로, 결과를 자신의 작업 directory에 쓰려면 `VIBE_TRADING_ALLOWED_RUN_ROOTS`가 필요합니다:@@ -1112,7 +1112,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**노출되는 MCP tools(59):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`.+**노출되는 MCP tools(62):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`.### SWARM 외부 MCP tools@@ -1435,7 +1435,7 @@ Vibe-Trading/├── agent/ # Backend (Python)│ ├── cli/ # CLI package — interactive TUI + subcommands│ ├── api_server.py # FastAPI server — runs, sessions, upload, swarm, SSE-│ ├── mcp_server.py # MCP server — 59 tools for OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server — 62 tools for OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent corediff --git a/README_zh.md b/README_zh.mdindex b4fb6d823..959340938 100644--- a/README_zh.md+++ b/README_zh.md@@ -1050,7 +1050,7 @@ POST `{}` 即按模板自身的建议节奏和默认变量排程。渲染后的## 🔌 MCP Plugin-Vibe-Trading 为任何 MCP-compatible client 暴露 59 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。+Vibe-Trading 为任何 MCP-compatible client 暴露 62 个 MCP tools。它作为 stdio subprocess 运行,无需 server setup。核心 research tools 对港股/美股/加密零 API key 可用;trading connector tools 使用当前选择的 connector profile;只有 `run_swarm` 需要 LLM key。**环境变量:** server 由 client 自己 spawn,因此在 shell 里 `export` 永远传不进去 —— 请写在 client 的 `env` 块里。生成的回测代码被限制在 allowed run roots 内,所以要把结果写进你自己的工作目录,需要 `VIBE_TRADING_ALLOWED_RUN_ROOTS`:@@ -1106,7 +1106,7 @@ vibe-trading-mcp --transport sse # legacy SSE (deprecated)</details>-**暴露的 MCP tools(59):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`.+**暴露的 MCP tools(62):** `list_skills`, `load_skill`, `start_research_goal`, `get_research_goal`, `add_goal_evidence`, `update_research_goal_status`, `backtest`, `factor_analysis`, `analyze_options`, `analyze_options_payoff`, `pattern_recognition`, `read_url`, `read_document`, `web_search`, `write_file`, `read_file`, `list_swarm_presets`, `run_swarm`, `get_market_data`, `get_fund_flow`, `get_dragon_tiger`, `get_northbound_flow`, `get_margin_trading`, `get_block_trades`, `get_shareholder_count`, `get_lockup_expiry`, `get_sector_info`, `get_research_reports`, `get_stock_news`, `get_sec_filings`, `get_financial_statements`, `get_options_chain`, `get_stock_profile`, `screen_market`, `search_symbol`, `get_macro_series`, `iwencai_search`, `qveris_search`, `qveris_inspect`, `qveris_execute`, `get_institutional_holdings`, `etf_holdings`, `prediction_market`, `research_papers`, `get_swarm_status`, `get_run_result`, `list_runs`, `reap_stale_runs`, `retry_run`, `analyze_trade_journal`, `extract_shadow_strategy`, `run_shadow_backtest`, `render_shadow_report`, `scan_shadow_signals`, `trading_connections`, `trading_select_connection`, `trading_check`, `trading_account`, `trading_positions`, `trading_orders`, `trading_quote`, `trading_history`.### SWARM 的外部 MCP tools@@ -1423,7 +1423,7 @@ Vibe-Trading/├── agent/ # 后端(Python)│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE-│ ├── mcp_server.py # MCP server —— 59 个工具,面向 OpenClaw / Claude Desktop+│ ├── mcp_server.py # MCP server —— 62 个工具,面向 OpenClaw / Claude Desktop│ ││ ├── src/│ │ ├── agent/ # ReAct agent 内核diff --git a/agent/SKILL.md b/agent/SKILL.mdindex 10cd5464b..b7b499601 100644--- a/agent/SKILL.md+++ b/agent/SKILL.md@@ -130,7 +130,7 @@ Comprehensive knowledge base covering:Use `load_skill(name)` to access full methodology docs with code templates.-## Available MCP Tools (55)+## Available MCP Tools (58)| Tool | Description | API Key ||------|-------------|---------|@@ -164,6 +164,9 @@ Use `load_skill(name)` to access full methodology docs with code templates.| `search_symbol` | Symbol / ticker search across markets | None || `get_macro_series` | FRED macroeconomic series | FRED_API_KEY || `iwencai_search` | A-share natural-language research search | IWENCAI_KEY |+| `qveris_search` | Search QVeris premium data/tool marketplace (free discovery) | QVERIS_API_KEY + paid mode |+| `qveris_inspect` | Inspect QVeris tool schemas before executing (free) | QVERIS_API_KEY + paid mode |+| `qveris_execute` | Execute a QVeris capability; budget-bounded, may be billable | QVERIS_API_KEY + paid mode || `web_search` | Search the web via DuckDuckGo | None || `read_url` | Fetch web page as Markdown | None || `read_document` | Extract text from PDF/DOCX/XLSX/PPTX/images | None |diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex dc7e3be29..13aed5fcc 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -6,18 +6,21 @@ Zero API key required for HK/US/crypto research markets (yfinance, OKX,AKShare are free). Trading connector tools are profile-scoped and require theselected connector's own local app or OAuth setup.-Surfaces 59 tools: skills, research goals, backtest/factor/options/pattern+Surfaces 62 tools: skills, research goals, backtest/factor/options/patternanalysis, market data, fundamentals & capital-flow & news & discovery(get_fund_flow / get_dragon_tiger / get_northbound_flow / get_margin_trading /get_block_trades / get_shareholder_count / get_lockup_expiry / get_sector_info /get_research_reports / get_stock_news / get_sec_filings /get_financial_statements / get_options_chain / get_stock_profile /-screen_market / search_symbol / get_macro_series / iwencai_search),+screen_market / search_symbol / get_macro_series / iwencai_search /+qveris_search / qveris_inspect / qveris_execute),institutional-research and alternative data (get_institutional_holdings /etf_holdings / prediction_market / research_papers), read-onlytrading-connector reads, swarm orchestration, trade-journal and shadow-accountanalysis. Every exposed tool is read-only or research-only; no order-placing or-order-cancelling tool is ever surfaced via MCP.+order-cancelling tool is ever surfaced via MCP. The QVeris tools additionally+require QVeris paid routing (QVERIS_API_KEY + paid mode), and qveris_execute+is billable research-data execution only — it never places orders.Usage:python mcp_server.py # stdio transport (default)@@ -1446,10 +1449,12 @@ def get_market_data(# Each wrapper delegates to the auto-discovered local registry, exactly like# factor_analysis / pattern_recognition above. The registry returns a clean# JSON error envelope when a key-gated tool (get_macro_series needs-# FRED_API_KEY, iwencai_search needs VIBE_TRADING_IWENCAI_KEY) is absent — see+# FRED_API_KEY, iwencai_search needs VIBE_TRADING_IWENCAI_KEY, the qveris_*+# tools need QVeris paid routing: QVERIS_API_KEY + paid mode) is absent — see# ``_execute_key_gated`` below, which honours that contract even though the# tool is excluded from the registry by ``check_available()``. Every tool below-# is strictly read-only data — no order/trading tool is ever surfaced via MCP.+# is read-only or research-only data — no order/trading tool is ever surfaced+# via MCP (qveris_execute spends QVeris credits on data calls, never orders).# ---------------------------------------------------------------------------@@ -1459,35 +1464,47 @@ def get_market_data(# answer with a generic "Tool not found". That contradicts the documented# contract above (a clean, env-var-named error). For these tools we therefore# fall through to the tool's own ``execute()`` — whose missing-key envelope-# names the exact env var (``FRED_API_KEY`` / ``VIBE_TRADING_IWENCAI_KEY``).+# names the exact env var (``FRED_API_KEY`` / ``VIBE_TRADING_IWENCAI_KEY``),+# or the missing QVeris paid-routing setup (``QVERIS_API_KEY`` + paid mode).def _key_gated_tool_classes() -> dict[str, Any]:"""Return the {tool_name: tool_class} map for key-gated MCP tools.- Imported lazily so a missing optional dependency in either module degrades- to the registry path rather than breaking module import.+ Imported lazily so a missing optional dependency in any mapped module+ degrades to the registry path rather than breaking module import.Returns:Mapping of MCP tool name to its ``BaseTool`` subclass."""from src.tools.fred_macro_tool import FredMacroToolfrom src.tools.iwencai_tool import IWenCaiSearchTool+ from src.tools.qveris_tool import (+ QVerisExecuteTool,+ QVerisInspectTool,+ QVerisSearchTool,+ )return {"get_macro_series": FredMacroTool,"iwencai_search": IWenCaiSearchTool,+ "qveris_search": QVerisSearchTool,+ "qveris_inspect": QVerisInspectTool,+ "qveris_execute": QVerisExecuteTool,}def _execute_key_gated(name: str, params: dict[str, Any]) -> str:- """Run a key-gated read-only tool, preserving its env-var-named error.+ """Run a key-gated MCP tool, preserving its env-var-named error.- Prefers the auto-discovered registry (present when the API key is set). When- the key is absent the tool is excluded from the registry, so we invoke its- concrete ``execute()`` directly to surface the documented missing-key error- that names the exact env var — never a generic "Tool not found".+ Prefers the auto-discovered registry (present when the API key is set and,+ for the qveris_* tools, paid mode is on). When the gating is absent the+ tool is excluded from the registry, so we invoke its concrete ``execute()``+ directly to surface the documented missing-key error that names the exact+ env var — or the missing QVeris paid routing — never a generic "Tool not+ found".Args:- name: MCP tool name (``get_macro_series`` or ``iwencai_search``).+ name: MCP tool name (``get_macro_series``, ``iwencai_search``,+ ``qveris_search``, ``qveris_inspect`` or ``qveris_execute``).params: Keyword arguments forwarded to the tool.Returns:@@ -1861,6 +1878,100 @@ def iwencai_search(query: str, limit: int = 20) -> str:return _execute_key_gated("iwencai_search", {"query": query, "limit": limit})+def qveris_search(query: str, limit: int = 20, session_id: str | None = None) -> str:+ """Search the QVeris premium data/tool marketplace for capabilities.++ Discovery is free. Returns candidate tools with ``tool_id``, ``provider``,+ ``parameters``, ``expected_cost`` and ``stats.success_rate``; choose by+ expected cost and success rate before any paid execute. Requires QVeris+ paid routing (``QVERIS_API_KEY`` and paid mode via ``vibe-trading data+ mode paid`` or Settings -> QVeris) — without it the tool returns a+ not-available error.++ Args:+ query: Capability search query, e.g. "US listed options chain implied+ volatility Greeks AAPL".+ limit: Maximum candidates to return.+ session_id: Optional QVeris session id linking follow-up calls.+ """+ params: dict[str, Any] = {"query": query, "limit": limit}+ if session_id:+ params["session_id"] = session_id+ return _execute_key_gated("qveris_search", params)+++def qveris_inspect(+ tool_ids: list[str],+ search_id: str | None = None,+ session_id: str | None = None,+) -> str:+ """Inspect full parameter schemas of QVeris tools before executing them.++ Fetches the complete descriptors for one or more ``tool_ids`` returned by+ ``qveris_search``. Inspection is free: verify required parameters, enum+ values, date formats and output shape before a paid call. Requires QVeris+ paid routing (``QVERIS_API_KEY`` and paid mode via ``vibe-trading data+ mode paid`` or Settings -> QVeris) — without it the tool returns a+ not-available error.++ Args:+ tool_ids: QVeris tool ids taken from ``qveris_search`` results.+ search_id: Optional search id from the ``qveris_search`` response.+ session_id: Optional QVeris session id linking follow-up calls.+ """+ params: dict[str, Any] = {"tool_ids": tool_ids}+ if search_id:+ params["search_id"] = search_id+ if session_id:+ params["session_id"] = session_id+ return _execute_key_gated("qveris_inspect", params)+++def qveris_execute(+ tool_id: str,+ parameters: dict[str, Any],+ search_id: str | None = None,+ session_id: str | None = None,+ model: str | None = None,+ max_response_size: int = 20480,+) -> str:+ """Execute one QVeris capability after discovery and inspection.++ Runs the ``tool_id`` selected via ``qveris_search`` / ``qveris_inspect``.+ MAY BE BILLABLE — provider calls are charged by QVeris when billable+ (failed or empty calls are not charged), and the tool enforces the local+ per-session credit budget before sending the request; the result preserves+ ``cost`` and ``remaining_credits``. Research/data execution only — it+ never places orders. Requires QVeris paid routing (``QVERIS_API_KEY`` and+ paid mode via ``vibe-trading data mode paid`` or Settings -> QVeris) —+ without it the tool returns a not-available error.++ Args:+ tool_id: QVeris tool id to execute.+ parameters: Provider call parameters matching the inspected schema.+ search_id: Optional search id from the ``qveris_search`` response.+ session_id: Optional QVeris session id used for budget accounting.+ model: Optional provider model override.+ max_response_size: Provider response truncation budget (default+ 20480; -1 disables truncation).+ """+ params: dict[str, Any] = {+ "tool_id": tool_id,+ "parameters": parameters,+ "max_response_size": max_response_size,+ }+ if search_id:+ params["search_id"] = search_id+ if session_id:+ params["session_id"] = session_id+ if model:+ params["model"] = model+ return _execute_key_gated("qveris_execute", params)++# ---------------------------------------------------------------------------# Institutional-research & alternative-data tools (schema mirrored from source)#diff --git a/agent/src/tools/qveris_tool.py b/agent/src/tools/qveris_tool.pyindex 77ee7ebbb..08b83e9cb 100644--- a/agent/src/tools/qveris_tool.py+++ b/agent/src/tools/qveris_tool.py@@ -151,6 +151,30 @@ def _json_response(payload: dict[str, Any]) -> str:return json.dumps(payload, ensure_ascii=False, default=str)+def _unconfigured_message(config: QVerisConfig | None = None) -> str:+ """Build an actionable error message when QVeris routing is unavailable.++ Args:+ config: Optional pre-loaded configuration; defaults to+ :func:`load_qveris_config`.++ Returns:+ Operator-facing error text. When no API key is saved it names+ ``QVERIS_API_KEY`` and the paid-mode switch; when a key exists but+ paid routing is off it points at the paid-mode toggle only.+ """+ cfg = config or load_qveris_config()+ if not has_qveris_credentials(cfg):+ return (+ "QVeris is not configured; set QVERIS_API_KEY and enable paid mode "+ "(`vibe-trading data mode paid` or Settings -> QVeris) to use QVeris tools"+ )+ return (+ "QVeris paid mode is off; enable it with `vibe-trading data mode paid` "+ "or Settings -> QVeris to use QVeris tools"+ )++def _parse_expected_cost(value: Any) -> float | None:"""Extract a numeric expected-cost hint from QVeris metadata."""if value is None:@@ -397,7 +421,7 @@ class QVerisSearchTool(_QVerisBaseTool):it is rejected rather than sent to the marketplace as ``""``."""if not is_qveris_configured():- return _json_response({"ok": False, "error": "QVeris is not configured"})+ return _json_response({"ok": False, "error": _unconfigured_message()})query = kwargs.get("query")if not isinstance(query, str) or not query.strip():return _json_response(@@ -436,7 +460,7 @@ class QVerisInspectTool(_QVerisBaseTool):def execute(self, **kwargs: Any) -> str:if not is_qveris_configured():- return _json_response({"ok": False, "error": "QVeris is not configured"})+ return _json_response({"ok": False, "error": _unconfigured_message()})payload = self._client().inspect(list(kwargs["tool_ids"]),search_id=kwargs.get("search_id"),@@ -547,7 +571,7 @@ class QVerisExecuteTool(_QVerisBaseTool):"""cfg = load_qveris_config()if not is_qveris_configured(cfg):- return _json_response({"ok": False, "error": "QVeris is not configured"})+ return _json_response({"ok": False, "error": _unconfigured_message(cfg)})raw_tool_id = kwargs.get("tool_id")if not isinstance(raw_tool_id, str) or not raw_tool_id.strip():return _json_response(diff --git a/agent/tests/test_qveris_mcp.py b/agent/tests/test_qveris_mcp.pynew file mode 100644index 000000000..7fe09ecb1--- /dev/null+++ b/agent/tests/test_qveris_mcp.py@@ -0,0 +1,131 @@+"""Contract tests for issue #964 — QVeris tools exposed over MCP.++The three QVeris agent tools (``qveris_search`` / ``qveris_inspect`` /+``qveris_execute``) must be registered on the FastMCP server and follow the+key-gated contract of ``get_macro_series`` / ``iwencai_search``: an+unconfigured install receives an actionable, setup-naming JSON envelope from+the tool's own ``execute()`` — never the registry's generic "Tool not found".++The cached ``mcp_server._registry`` bakes in ``check_available()`` results, so+every behavioral test resets it to ``None`` before and after the call to force+a rebuild against the monkeypatched config path.+"""++from __future__ import annotations++import asyncio+import json+import re+from pathlib import Path++import pytest++import mcp_server+from src.tools import qveris_tool as qt++# fastmcp wraps the tool; reach the raw callable.+_qveris_search = getattr(mcp_server.qveris_search, "fn", None) or getattr(+ mcp_server.qveris_search, "__wrapped__", mcp_server.qveris_search+)+_qveris_inspect = getattr(mcp_server.qveris_inspect, "fn", None) or getattr(+ mcp_server.qveris_inspect, "__wrapped__", mcp_server.qveris_inspect+)+_qveris_execute = getattr(mcp_server.qveris_execute, "fn", None) or getattr(+ mcp_server.qveris_execute, "__wrapped__", mcp_server.qveris_execute+)++[email protected](autouse=True)+def qveris_config_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch):+ monkeypatch.setattr(qt, "QVERIS_CONFIG_PATH", tmp_path / "qveris.json")+ monkeypatch.delenv("QVERIS_API_KEY", raising=False)+ monkeypatch.delenv("QVERIS_BASE_URL", raising=False)+ qt._SESSION_SPEND.clear()+ getattr(qt, "_SESSION_RESERVED", {}).clear()+ return tmp_path / "qveris.json"+++def fresh_mcp_registry():+ """Force mcp_server to rebuild its cached registry under the test config."""+ mcp_server._registry = None+ yield+ mcp_server._registry = None+++def test_mcp_server_registers_qveris_tools() -> None:+ """All three qveris wrappers must be registered on the FastMCP instance."""+ tools = asyncio.run(mcp_server.mcp.list_tools())+ registered = {t.name for t in tools}++ expected = {"qveris_search", "qveris_inspect", "qveris_execute"}+ missing = expected - registered+ assert not missing, (+ f"MCP server is missing qveris tools: {missing}. "+ "Issue #964 requires all three QVeris tools on the MCP surface."+ )+ # Read the claim out of the docstring instead of hardcoding it a third+ # time. A literal here is a number nobody updates: it was written as 55,+ # shipped as 58, and the surface was 59 before these three landed. This+ # asserts the docstring and the surface agree, whatever they say.+ claimed = re.search(r"Surfaces (\d+) tools", mcp_server.__doc__ or "")+ assert claimed, "mcp_server's module docstring no longer states a tool count"+ assert len(tools) == int(claimed.group(1)), (+ f"Module docstring says {claimed.group(1)} tools, surface has {len(tools)}."+ )+++def test_qveris_search_unconfigured_returns_actionable_error(+ fresh_mcp_registry,+) -> None:+ """Without QVeris routing the MCP call surfaces the setup hint, not 'Tool not found'."""+ payload = json.loads(_qveris_search("US listed options chain implied volatility Greeks AAPL"))++ assert payload.get("ok") is False+ assert payload.get("error") != "Tool 'qveris_search' not found"+ assert "QVERIS_API_KEY" in payload.get("error", "")+++def test_qveris_search_configured_paid_delegates(fresh_mcp_registry, monkeypatch: pytest.MonkeyPatch) -> None:+ """A keyed paid-mode install delegates to the registered tool end to end."""+ qt.save_qveris_config(qt.QVerisConfig(enabled=True, api_key="sk-live", mode="paid"))+ canned = {+ "search_id": "srch_1",+ "results": [+ {+ "tool_id": "tool_options_iv",+ "name": "US options IV surface",+ "provider": "options-data-co",+ "expected_cost": "1 credit",+ "stats": {"success_rate": 0.98},+ }+ ],+ "remaining_credits": 99.0,+ }++ class FakeClient:+ def search(self, query, *, limit=20, session_id=None):+ return canned++ monkeypatch.setattr(qt.QVerisSearchTool, "_client", lambda self: FakeClient())++ payload = json.loads(_qveris_search("options iv greeks", limit=5))++ assert payload["ok"] is True+ assert payload["search_id"] == "srch_1"+ assert payload["results"][0]["tool_id"] == "tool_options_iv"+ assert payload["results"][0]["provider"] == "options-data-co"+ assert payload["results"][0]["expected_cost"] == "1 credit"+ assert payload["results"][0]["stats"] == {"success_rate": 0.98}+ assert payload["remaining_credits"] == 99.0+++def test_qveris_execute_unconfigured_returns_actionable_error(+ fresh_mcp_registry,+) -> None:+ """qveris_execute must also surface the actionable envelope, never 'Tool not found'."""+ payload = json.loads(_qveris_execute(tool_id="tool_1", parameters={"x": 1}))++ assert payload.get("ok") is False+ assert payload.get("error") != "Tool 'qveris_execute' not found"+ assert "QVeris is not configured" in payload.get("error", "")diff --git a/agent/tests/test_qveris_tool.py b/agent/tests/test_qveris_tool.pyindex f6a5953ee..2e429ea4d 100644--- a/agent/tests/test_qveris_tool.py+++ b/agent/tests/test_qveris_tool.py@@ -111,7 +111,25 @@ def test_free_mode_execute_is_unavailable(monkeypatch: pytest.MonkeyPatch):qt.QVerisExecuteTool().execute(tool_id="tool_1", parameters={"x": 1}))- assert payload == {"ok": False, "error": "QVeris is not configured"}+ assert payload == {+ "ok": False,+ "error": (+ "QVeris paid mode is off; enable it with `vibe-trading data mode paid` "+ "or Settings -> QVeris to use QVeris tools"+ ),+ }+++def test_unconfigured_execute_names_missing_api_key():+ payload = json.loads(qt.QVerisSearchTool().execute(query="options iv"))++ assert payload == {+ "ok": False,+ "error": (+ "QVeris is not configured; set QVERIS_API_KEY and enable paid mode "+ "(`vibe-trading data mode paid` or Settings -> QVeris) to use QVeris tools"+ ),+ }def test_paid_mode_rejects_when_expected_cost_exceeds_budget(monkeypatch):