Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(mcp): expose the four new data tools

Haozhe Wuc95e0be410f0
diff --git a/README.md b/README.md
index a32e97fc3..bb7ab3ff7 100644
--- a/README.md
+++ b/README.md
@@ -1412,7 +1412,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 — 55 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 59 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
diff --git a/README_ar.md b/README_ar.md
index 9145b0812..43ab12c72 100644
--- a/README_ar.md
+++ b/README_ar.md
@@ -1147,7 +1147,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 — 54 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 59 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
diff --git a/README_ja.md b/README_ja.md
index cfb8846a3..35aeab811 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -1144,7 +1144,7 @@ Vibe-Trading/
├── agent/ # バックエンド (Python)
│ ├── cli/ # CLI パッケージ — インタラクティブ TUI + サブコマンド
│ ├── api_server.py # FastAPI サーバー — runs、sessions、upload、swarm、SSE
-│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 54 tools
+│ ├── mcp_server.py # MCP サーバー — OpenClaw / Claude Desktop 向け 59 tools
│ │
│ ├── src/
│ │ ├── agent/ # ReAct エージェントコア
diff --git a/README_ko.md b/README_ko.md
index fec77c9e6..221f4e4bb 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -1147,7 +1147,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 — 54 tools for OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server — 59 tools for OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent core
diff --git a/README_zh.md b/README_zh.md
index 6f73e6361..a6db813aa 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -1171,7 +1171,7 @@ Vibe-Trading/
├── agent/ # 后端(Python)
│ ├── cli/ # CLI 包 —— 交互式 TUI + 子命令
│ ├── api_server.py # FastAPI server —— runs、sessions、upload、swarm、SSE
-│ ├── mcp_server.py # MCP server —— 54 个工具,面向 OpenClaw / Claude Desktop
+│ ├── mcp_server.py # MCP server —— 59 个工具,面向 OpenClaw / Claude Desktop
│ │
│ ├── src/
│ │ ├── agent/ # ReAct agent 内核
diff --git a/agent/mcp_server.py b/agent/mcp_server.py
index 17005e922..fdd247f8f 100644
--- a/agent/mcp_server.py
+++ b/agent/mcp_server.py
@@ -6,13 +6,15 @@ Zero API key required for HK/US/crypto research markets (yfinance, OKX,
AKShare are free). Trading connector tools are profile-scoped and require the
selected connector's own local app or OAuth setup.
-Surfaces 55 tools: skills, research goals, backtest/factor/options/pattern
+Surfaces 59 tools: skills, research goals, backtest/factor/options/pattern
analysis, 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), read-only
+screen_market / search_symbol / get_macro_series / iwencai_search),
+institutional-research and alternative data (get_institutional_holdings /
+etf_holdings / prediction_market / research_papers), read-only
trading-connector reads, swarm orchestration, trade-journal and shadow-account
analysis. Every exposed tool is read-only or research-only; no order-placing or
order-cancelling tool is ever surfaced via MCP.
@@ -51,6 +53,8 @@ from __future__ import annotations
import json
import logging
import sys
+from copy import deepcopy
+from importlib import import_module
from pathlib import Path
from typing import Any
@@ -1807,6 +1811,162 @@ def iwencai_search(query: str, limit: int = 20) -> str:
return _execute_key_gated("iwencai_search", {"query": query, "limit": limit})
+# ---------------------------------------------------------------------------
+# Institutional-research & alternative-data tools (schema mirrored from source)
+#
+# get_institutional_holdings / etf_holdings / prediction_market /
+# research_papers carry large multi-mode JSON Schemas (mode enums, per-mode
+# required arguments, paging bounds) that live on the tool class itself.
+# Re-declaring them here as Python signatures — the pattern used by the
+# single-purpose tools above — would create a SECOND definition that silently
+# drifts from the agent-side one every time a mode or bound changes. So these
+# four are registered with the tool class' own ``parameters`` and
+# ``description``: an MCP client sees byte-identical argument documentation to
+# what the agent sees, from one source.
+#
+# Read-only is structural here, not a comment: _register_mirrored_tool refuses
+# any class whose ``is_readonly`` is not True, so an order-placing tool cannot
+# be surfaced through this path even if someone adds it to the list below.
+# ``trading_place_order`` / ``trading_cancel_order`` are never MCP-exposed.
+#
+# Tradeoff accepted: fastmcp validates call arguments against the wrapper's
+# Python signature, not against ``parameters``, so a mirrored tool receives its
+# arguments unvalidated by the server (we only drop nulls and undeclared keys).
+# That is the same contract the tool already has with the agent — every one of
+# these tools parses/clamps its own ``**kwargs`` — and ToolRegistry.execute
+# turns any failure into a JSON error envelope rather than a transport error.
+# KNOWN DIVERGENCE from the hand-written wrappers above, which declare
+# ``additionalProperties: false`` and therefore REJECT an undeclared argument:
+# here an undeclared argument is dropped instead. Every identity argument is
+# still enforced by the tool itself (a missing symbol/manager/query fails
+# closed), so the residual risk is a mistyped OPTIONAL argument silently
+# falling back to its default. Closing this belongs on the tool classes —
+# adding ``additionalProperties: false`` to their ``parameters`` fixes the
+# agent side and this surface at once, since the schema here is theirs.
+# ---------------------------------------------------------------------------
+
+
+_MIRRORED_TOOL_SOURCES = (
+ ("src.tools.institutional_holdings_tool", "InstitutionalHoldingsTool"),
+ ("src.tools.etf_holdings_tool", "EtfHoldingsTool"),
+ ("src.tools.prediction_market_tool", "PredictionMarketTool"),
+ ("src.tools.research_papers_tool", "ResearchPapersTool"),
+)
+
+
+def _mirrored_tool_classes() -> list[Any]:
+ """Return the read-only tool classes exposed with their own JSON Schema.
+
+ Each module is imported lazily AND independently: a missing optional
+ dependency or a broken module costs exactly the one tool it defines, and
+ the other three still reach the MCP surface. Importing them together in a
+ single ``from ... import`` block would make one bad module drop all four.
+
+ Returns:
+ The ``BaseTool`` subclasses to mirror onto the MCP surface, in
+ declaration order, minus any whose module failed to import.
+ """
+ classes: list[Any] = []
+ for module_path, class_name in _MIRRORED_TOOL_SOURCES:
+ try:
+ classes.append(getattr(import_module(module_path), class_name))
+ except Exception: # noqa: BLE001 - one unavailable module, not four
+ logger.exception(
+ "Tool module %s is unavailable; its MCP tool will be absent", module_path
+ )
+ return classes
+
+
+def _string_result_output_schema() -> dict[str, Any] | None:
+ """Return the output schema fastmcp derives for a ``-> str`` tool.
+
+ Derived from a probe function instead of hardcoded so the mirrored tools
+ keep announcing the same result envelope as the ``@mcp.tool`` wrappers
+ above across fastmcp versions (currently a wrapped ``{"result": str}``).
+
+ Returns:
+ The derived output schema, or None if this fastmcp version declares none.
+ """
+ from fastmcp.tools import FunctionTool
+
+ def _probe() -> str: # pragma: no cover - shape probe only
+ return ""
+
+ return FunctionTool.from_function(_probe, name="probe").output_schema
+
+
+def _mirrored_call_params(schema: dict[str, Any], kwargs: dict[str, Any]) -> dict[str, Any]:
+ """Reduce raw MCP call arguments to the ones the tool actually declares.
+
+ Drops ``None`` values (no mirrored schema declares a nullable property, so
+ an explicit null means "not supplied") and keys the schema does not declare,
+ matching the ``additionalProperties: false`` behaviour of the hand-written
+ wrappers.
+
+ Args:
+ schema: The tool's own ``parameters`` JSON Schema.
+ kwargs: Arguments as received from the MCP client.
+
+ Returns:
+ The filtered keyword arguments to forward to the registry.
+ """
+ declared = schema.get("properties") or {}
+ return {k: v for k, v in kwargs.items() if v is not None and k in declared}
+
+
+def _register_mirrored_tool(tool_cls: Any) -> bool:
+ """Register one read-only tool on the MCP surface using its own schema.
+
+ Args:
+ tool_cls: A ``BaseTool`` subclass with ``name`` / ``description`` /
+ ``parameters``.
+
+ Returns:
+ True when the tool was registered; False when it was refused (not
+ read-only) or this fastmcp version rejected the registration.
+ """
+ name = getattr(tool_cls, "name", "")
+ if getattr(tool_cls, "is_readonly", False) is not True:
+ logger.error(
+ "Refusing to expose non-read-only tool %r via MCP; only read-only "
+ "tools are ever surfaced.",
+ name or tool_cls,
+ )
+ return False
+
+ try:
+ from fastmcp.tools import FunctionTool
+
+ schema = deepcopy(getattr(tool_cls, "parameters", None)) or {
+ "type": "object",
+ "properties": {},
+ "required": [],
+ }
+
+ def _call(**kwargs: Any) -> str:
+ """Forward an MCP call to the auto-discovered local tool registry."""
+ return _get_registry().execute(name, _mirrored_call_params(schema, kwargs))
+
+ mcp.add_tool(
+ FunctionTool(
+ fn=_call,
+ name=name,
+ description=tool_cls.description,
+ parameters=schema,
+ output_schema=_string_result_output_schema(),
+ return_type=str,
+ )
+ )
+ except Exception: # noqa: BLE001 - never let one tool break server startup
+ logger.exception("Failed to expose tool %r via MCP", name)
+ return False
+ return True
+
+
+for _mirrored_cls in _mirrored_tool_classes():
+ _register_mirrored_tool(_mirrored_cls)
+
+
# ---------------------------------------------------------------------------
# Swarm status & history tools
# ---------------------------------------------------------------------------
diff --git a/agent/tests/test_mcp_new_tools.py b/agent/tests/test_mcp_new_tools.py
new file mode 100644
index 000000000..636eece48
--- /dev/null
+++ b/agent/tests/test_mcp_new_tools.py
@@ -0,0 +1,344 @@
+"""MCP exposure of the institutional-research & alternative-data tools.
+
+Covers the four tools that reach the MCP surface by mirroring their own JSON
+Schema (``get_institutional_holdings`` / ``etf_holdings`` /
+``prediction_market`` / ``research_papers``) and the red-line regression that
+guards *which* tools the MCP server is allowed to surface at all.
+
+No network: the only test that actually invokes a tool swaps the mcp_server
+registry for a recording fake, so nothing reaches SEC / Polymarket / arXiv.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import importlib
+import sys
+from pathlib import Path
+from typing import Any
+
+import pytest
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+MIRRORED_TOOL_NAMES = (
+ "get_institutional_holdings",
+ "etf_holdings",
+ "prediction_market",
+ "research_papers",
+)
+
+# Tools that mutate state (is_readonly is not True on the agent side) and were
+# ALREADY exposed on the MCP surface before the institutional-research tools
+# were added. They are sandbox/session writes — a backtest run, a session file
+# write, a swarm launch, research-goal bookkeeping, and selecting which broker
+# profile subsequent READS use — not broker order flow.
+#
+# This snapshot is the regression gate: adding an MCP tool that mutates
+# anything outside this list must fail the suite loudly.
+KNOWN_MUTATING_MCP_TOOLS = frozenset(
+ {
+ "add_goal_evidence",
+ "backtest",
+ "run_swarm",
+ "start_research_goal",
+ "trading_select_connection",
+ "update_research_goal_status",
+ "write_file",
+ }
+)
+
+
+def _import_mcp_server():
+ """Import ``agent/mcp_server.py`` without executing ``main()``.
+
+ Returns:
+ The imported mcp_server module.
+ """
+ agent_dir = Path(__file__).resolve().parent.parent
+ if str(agent_dir) not in sys.path:
+ sys.path.insert(0, str(agent_dir))
+ if "mcp_server" in sys.modules:
+ return sys.modules["mcp_server"]
+ return importlib.import_module("mcp_server")
+
+
+def _mcp_tools() -> dict[str, Any]:
+ """Return the registered MCP tools keyed by name (public async API)."""
+ mod = _import_mcp_server()
+ return {tool.name: tool for tool in asyncio.run(mod.mcp.list_tools())}
+
+
+def _tool_classes() -> dict[str, Any]:
+ """Return the mirrored tool classes keyed by their tool name."""
+ mod = _import_mcp_server()
+ return {cls.name: cls for cls in mod._mirrored_tool_classes()}
+
+
+# ---------------------------------------------------------------------------
+# Registration
+# ---------------------------------------------------------------------------
+
+
+def test_institutional_research_tools_are_exposed_via_mcp() -> None:
+ """All four institutional-research tools must reach the MCP surface."""
+ registered = set(_mcp_tools())
+
+ missing = set(MIRRORED_TOOL_NAMES) - registered
+ assert not missing, (
+ f"MCP server is missing institutional-research tools: {sorted(missing)}. "
+ "Check _mirrored_tool_classes() in mcp_server.py."
+ )
+
+
+def test_mcp_tool_count_covers_the_mirrored_tools() -> None:
+ """The MCP surface must not shrink below the documented 59 tools."""
+ tools = _mcp_tools()
+
+ assert len(tools) >= 59, (
+ f"Expected at least 59 MCP tools (55 pre-existing + 4 mirrored), found {len(tools)}."
+ )
+
+
+def test_mirrored_tool_names_match_the_agent_side_registry() -> None:
+ """MCP must expose these tools under their agent-side names, not aliases.
+
+ A renamed wrapper would make the MCP call route to a tool the local
+ registry does not have, which only shows up as a 'Tool not found' envelope
+ at call time.
+ """
+ from src.tools import build_registry
+
+ registry = build_registry()
+
+ for name in MIRRORED_TOOL_NAMES:
+ assert registry.get(name) is not None, (
+ f"{name} is exposed via MCP but absent from the agent registry"
+ )
+
+
+# ---------------------------------------------------------------------------
+# One schema, not two
+# ---------------------------------------------------------------------------
+
+
[email protected]("name", MIRRORED_TOOL_NAMES)
+def test_schema_is_the_tool_class_schema(name: str) -> None:
+ """The advertised MCP schema must BE the tool's own schema, not a copy that drifts."""
+ tool_cls = _tool_classes()[name]
+ mcp_tool = _mcp_tools()[name]
+
+ assert mcp_tool.parameters == tool_cls.parameters, (
+ f"{name}: MCP inputSchema diverged from the tool class' parameters. "
+ "The MCP wrapper must read the schema from the tool class."
+ )
+ # to_mcp_tool() is what a client actually receives.
+ assert mcp_tool.to_mcp_tool().inputSchema == tool_cls.parameters
+
+
[email protected]("name", MIRRORED_TOOL_NAMES)
+def test_description_is_the_tool_class_description(name: str) -> None:
+ """MCP clients get the tool's own self-contained description, verbatim."""
+ tool_cls = _tool_classes()[name]
+ mcp_tool = _mcp_tools()[name]
+
+ assert mcp_tool.description == tool_cls.description
+ assert mcp_tool.description, f"{name} exposes an empty description to MCP clients"
+
+
[email protected]("name", MIRRORED_TOOL_NAMES)
+def test_schema_is_isolated_from_the_class_attribute(name: str) -> None:
+ """The registered schema must be a snapshot, so MCP cannot mutate tool state."""
+ tool_cls = _tool_classes()[name]
+ mcp_tool = _mcp_tools()[name]
+
+ assert mcp_tool.parameters is not tool_cls.parameters
+
+
[email protected]("name", MIRRORED_TOOL_NAMES)
+def test_mirrored_tools_announce_the_same_result_envelope(name: str) -> None:
+ """Mirrored tools must return the same wrapped-string envelope as the hand-written ones."""
+ tools = _mcp_tools()
+
+ assert tools[name].output_schema == tools["get_fund_flow"].output_schema
+
+
+# ---------------------------------------------------------------------------
+# Read-only red line
+# ---------------------------------------------------------------------------
+
+
+def test_order_placing_tools_are_never_exposed_via_mcp() -> None:
+ """Order placement / cancellation must never appear on the MCP surface."""
+ from src.tools.trading_connector_tool import (
+ TradingCancelOrderTool,
+ TradingPlaceOrderTool,
+ )
+
+ registered = set(_mcp_tools())
+ order_tools = {TradingPlaceOrderTool.name, TradingCancelOrderTool.name}
+
+ leaked = order_tools & registered
+ assert not leaked, f"Order-placing tools leaked onto the MCP surface: {sorted(leaked)}"
+
+
+def test_no_unexpected_mutating_tool_is_exposed_via_mcp() -> None:
+ """No tool with ``is_readonly=False`` may join the MCP surface.
+
+ The MCP server exposes read-only or sandbox-research tools only. A handful
+ of pre-existing sandbox writers are grandfathered in
+ (KNOWN_MUTATING_MCP_TOOLS); anything else showing up here means a mutating
+ tool was newly exposed, which is a red-line violation.
+ """
+ from src.tools import build_registry
+
+ registry = build_registry()
+
+ exposed_mutating = {
+ name
+ for name in _mcp_tools()
+ if (tool := registry.get(name)) is not None and tool.is_readonly is not True
+ }
+
+ assert exposed_mutating <= KNOWN_MUTATING_MCP_TOOLS, (
+ "Mutating tools newly exposed via MCP: "
+ f"{sorted(exposed_mutating - KNOWN_MUTATING_MCP_TOOLS)}"
+ )
+
+
+def test_every_mirrored_tool_is_readonly() -> None:
+ """The tools added through the mirroring path are all read-only."""
+ for name, cls in _tool_classes().items():
+ assert cls.is_readonly is True, f"{name} is not read-only and must not be mirrored"
+
+
+def test_register_mirrored_tool_refuses_a_non_readonly_class(caplog) -> None:
+ """The mirroring helper is a structural gate, not a convention.
+
+ A mutating class handed to ``_register_mirrored_tool`` must be refused and
+ must not end up on the MCP surface.
+ """
+ mod = _import_mcp_server()
+
+ class _MutatingTool:
+ name = "definitely_not_readonly_probe"
+ description = "probe"
+ parameters = {"type": "object", "properties": {}, "required": []}
+ is_readonly = False
+
+ with caplog.at_level("ERROR"):
+ registered = mod._register_mirrored_tool(_MutatingTool)
+
+ assert registered is False
+ assert _MutatingTool.name not in _mcp_tools()
+ assert any("read-only" in record.message for record in caplog.records)
+
+
+# ---------------------------------------------------------------------------
+# Call forwarding
+# ---------------------------------------------------------------------------
+
+
+class _RecordingRegistry:
+ """Stand-in for the local tool registry that records the forwarded call."""
+
+ def __init__(self) -> None:
+ self.calls: list[tuple[str, dict[str, Any]]] = []
+
+ def execute(self, name: str, params: dict[str, Any]) -> str:
+ """Record the call and return a JSON envelope like the real registry."""
+ self.calls.append((name, params))
+ return '{"status": "ok"}'
+
+
+def test_mirrored_call_reaches_the_registry_with_clean_params(monkeypatch) -> None:
+ """An MCP call is forwarded to the agent tool, minus nulls and undeclared keys."""
+ mod = _import_mcp_server()
+ recorder = _RecordingRegistry()
+ monkeypatch.setattr(mod, "_registry", recorder)
+
+ tool = _mcp_tools()["prediction_market"]
+ result = asyncio.run(
+ tool.run(
+ {
+ "mode": "search",
+ "query": "fed rate cut",
+ "status": None,
+ "not_a_declared_arg": "drop me",
+ }
+ )
+ )
+
+ assert recorder.calls == [
+ ("prediction_market", {"mode": "search", "query": "fed rate cut"})
+ ]
+ assert result.content[0].text == '{"status": "ok"}'
+
+
+def test_mirrored_tool_round_trips_over_a_real_mcp_session(monkeypatch) -> None:
+ """A protocol-level call_tool must reach the tool and wrap the JSON envelope.
+
+ Uses fastmcp's in-memory client transport, so this exercises the same
+ request path an OpenClaw / Claude Desktop client uses — without a socket
+ and without a network call (the registry is a fake).
+ """
+ from fastmcp import Client
+
+ mod = _import_mcp_server()
+ recorder = _RecordingRegistry()
+ monkeypatch.setattr(mod, "_registry", recorder)
+
+ async def _call() -> Any:
+ async with Client(mod.mcp) as client:
+ return await client.call_tool(
+ "research_papers", {"mode": "search", "query": "momentum crash"}
+ )
+
+ result = asyncio.run(_call())
+
+ assert recorder.calls == [
+ ("research_papers", {"mode": "search", "query": "momentum crash"})
+ ]
+ assert result.content[0].text == '{"status": "ok"}'
+ assert result.structured_content == {"result": '{"status": "ok"}'}
+
+
+def test_one_broken_tool_module_costs_only_its_own_tool(monkeypatch, caplog) -> None:
+ """A broken tool module must not take the other three down with it.
+
+ Regression: importing all four classes in one ``from ... import`` block
+ made a single SyntaxError / missing optional dependency raise out of
+ ``_mirrored_tool_classes()``, so the MCP surface silently lost all four
+ institutional-research tools instead of one.
+ """
+ mod = _import_mcp_server()
+
+ def _explode(module_path: str):
+ if module_path.endswith("research_papers_tool"):
+ raise ImportError("simulated broken module")
+ return importlib.import_module(module_path)
+
+ monkeypatch.setattr(mod, "import_module", _explode)
+
+ with caplog.at_level("ERROR"):
+ surviving = {cls.name for cls in mod._mirrored_tool_classes()}
+
+ assert surviving == {
+ "get_institutional_holdings",
+ "etf_holdings",
+ "prediction_market",
+ }, f"one broken module took down more than its own tool: survivors={sorted(surviving)}"
+ assert any("research_papers_tool" in record.message for record in caplog.records)
+
+
+def test_mirrored_call_params_filter() -> None:
+ """The parameter filter keeps declared, non-null arguments only."""
+ mod = _import_mcp_server()
+ schema = {"type": "object", "properties": {"a": {"type": "string"}, "b": {"type": "integer"}}}
+
+ assert mod._mirrored_call_params(schema, {"a": "x", "b": 0, "c": 1, "d": None}) == {
+ "a": "x",
+ "b": 0,
+ }