"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(integration): align tool contracts and locale versions and keep API assembly thin
Haozhe Wubdeeef21039b
diff --git a/agent/api_server.py b/agent/api_server.pyindex 28f0006ef..2399febd0 100644--- a/agent/api_server.py+++ b/agent/api_server.py@@ -332,68 +332,10 @@ from src.api.scheduled_routes import ( # noqa: E402, F401# ============================================================================def serve_main(argv: list[str] | None = None) -> int:- """Start the API server from CLI-style arguments."""- import argparse- import subprocess- import uvicorn- from src.api.spa import SPAStaticFiles-- parser = argparse.ArgumentParser(description="Vibe-Trading Server")- parser.add_argument("--port", type=int, default=8000, help="Listen port (default 8000)")- parser.add_argument("--host", default="127.0.0.1", help="Bind address")- parser.add_argument("--dev", action="store_true", help="Dev mode: spawn Vite on :5173")- try:- args = parser.parse_args(argv)- except SystemExit as exc:- return int(exc.code) if isinstance(exc.code, int) else 2-- if not _is_loopback_bind_host(args.host) and not _configured_api_key():- print(- f"[warn] Binding to {args.host} without API_AUTH_KEY set. "- f"Remote requests are rejected by the loopback peer-IP check, "- f"but consider using --host 127.0.0.1 for local-only access."- )-- frontend_dist = Path(__file__).resolve().parent.parent / "frontend" / "dist"- frontend_root = Path(__file__).resolve().parent.parent / "frontend"-- vite_proc = None- if args.dev and frontend_root.exists():- print("[dev] Starting Vite dev server on :5173 ...")- vite_proc = subprocess.Popen(- ["npx", "vite", "--host", "0.0.0.0"],- cwd=str(frontend_root),- stdout=subprocess.DEVNULL,- stderr=subprocess.DEVNULL,- )- print(f"[dev] Vite PID={vite_proc.pid}")- print("[dev] Frontend: http://localhost:5173")- print(f"[dev] API: http://localhost:{args.port}")- elif frontend_dist.exists():- if not any(getattr(route, "path", None) == "/" for route in app.routes):- app.mount("/", SPAStaticFiles(directory=str(frontend_dist), html=True), name="frontend")- print(f"[prod] Frontend served from {frontend_dist}")- else:- print(f"[warn] No frontend build found at {frontend_dist}")- print("[warn] Run: cd frontend && npm run build")-- print("=" * 50)- print(" Vibe-Trading Server")- print(f" http://127.0.0.1:{args.port}")- print("=" * 50)-- # Redact api_key=/ticket= values from Uvicorn's access log (it logs the full- # request line including the query string). Installed before run() so the- # filter is attached when Uvicorn configures its loggers.- install_access_log_redaction_filter()+ """Start the API server, preserving the module's public CLI entry point."""+ from src.api.server_cli import serve- try:- uvicorn.run(app, host=args.host, port=args.port, log_level="info")- finally:- if vite_proc:- vite_proc.terminate()- print("[dev] Vite stopped")- return 0+ return serve(app, argv, repo_root=Path(__file__).resolve().parent.parent)if __name__ == "__main__":diff --git a/agent/mcp_server.py b/agent/mcp_server.pyindex b7402375b..bb6344bbc 100644--- a/agent/mcp_server.py+++ b/agent/mcp_server.py@@ -6,7 +6,7 @@ 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 80 tools: skills, research goals, strategy discovery,+Surfaces 81 tools: skills, research goals, strategy discovery,backtest/factor/options/patternanalysis, market data, fundamentals & capital-flow & news & discovery(get_fund_flow / get_dragon_tiger / get_northbound_flow / get_southbound_flow /diff --git a/agent/src/api/server_cli.py b/agent/src/api/server_cli.pynew file mode 100644index 000000000..8e2785d1a--- /dev/null+++ b/agent/src/api/server_cli.py@@ -0,0 +1,74 @@+"""CLI server startup kept separate from the API route assembler."""+from __future__ import annotations++from pathlib import Path+from fastapi import FastAPI+from src.api.security import (+ _is_loopback_bind_host, _configured_api_key, install_access_log_redaction_filter,+)+++def serve(app: FastAPI, argv: list[str] | None, *, repo_root: Path) -> int:+ """Start the API server from CLI-style arguments."""+ import argparse+ import subprocess+ import uvicorn+ from src.api.spa import SPAStaticFiles++ parser = argparse.ArgumentParser(description="Vibe-Trading Server")+ parser.add_argument("--port", type=int, default=8000, help="Listen port (default 8000)")+ parser.add_argument("--host", default="127.0.0.1", help="Bind address")+ parser.add_argument("--dev", action="store_true", help="Dev mode: spawn Vite on :5173")+ try:+ args = parser.parse_args(argv)+ except SystemExit as exc:+ return int(exc.code) if isinstance(exc.code, int) else 2++ if not _is_loopback_bind_host(args.host) and not _configured_api_key():+ print(+ f"[warn] Binding to {args.host} without API_AUTH_KEY set. "+ f"Remote requests are rejected by the loopback peer-IP check, "+ f"but consider using --host 127.0.0.1 for local-only access."+ )++ frontend_dist = repo_root / "frontend" / "dist"+ frontend_root = repo_root / "frontend"++ vite_proc = None+ if args.dev and frontend_root.exists():+ print("[dev] Starting Vite dev server on :5173 ...")+ vite_proc = subprocess.Popen(+ ["npx", "vite", "--host", "0.0.0.0"],+ cwd=str(frontend_root),+ stdout=subprocess.DEVNULL,+ stderr=subprocess.DEVNULL,+ )+ print(f"[dev] Vite PID={vite_proc.pid}")+ print("[dev] Frontend: http://localhost:5173")+ print(f"[dev] API: http://localhost:{args.port}")+ elif frontend_dist.exists():+ if not any(getattr(route, "path", None) == "/" for route in app.routes):+ app.mount("/", SPAStaticFiles(directory=str(frontend_dist), html=True), name="frontend")+ print(f"[prod] Frontend served from {frontend_dist}")+ else:+ print(f"[warn] No frontend build found at {frontend_dist}")+ print("[warn] Run: cd frontend && npm run build")++ print("=" * 50)+ print(" Vibe-Trading Server")+ print(f" http://127.0.0.1:{args.port}")+ print("=" * 50)++ # Redact api_key=/ticket= values from Uvicorn's access log (it logs the full+ # request line including the query string). Installed before run() so the+ # filter is attached when Uvicorn configures its loggers.+ install_access_log_redaction_filter()++ try:+ uvicorn.run(app, host=args.host, port=args.port, log_level="info")+ finally:+ if vite_proc:+ vite_proc.terminate()+ print("[dev] Vite stopped")+ return 0+diff --git a/agent/tests/test_strategy_discovery_tools.py b/agent/tests/test_strategy_discovery_tools.pyindex a1deb7e1b..cfd24d2da 100644--- a/agent/tests/test_strategy_discovery_tools.py+++ b/agent/tests/test_strategy_discovery_tools.py@@ -1,11 +1,11 @@"""Frozen-contract tests for ``src.tools.strategy_discovery_tool`` — issue #969.-AC1 (tools callable at runtime): the module must expose exactly four+AC1 (tools callable at runtime): the module must expose exactly five``BaseTool`` classes whose ``name`` attributes are ``list_strategies`` /``query_strategies`` / ``get_strategy_evidence`` /-``refresh_strategy_evidence``. The three query tools are read-only; the-refresh tool is the single WRITE tool (``is_readonly=False``, scope limited-to the disposable evidence cache — Phase 2, plan D13). All return strict-JSON+``refresh_strategy_evidence`` / ``adapt_strategy``. The three query tools+are read-only. Refresh writes only the disposable evidence cache; adaptation+creates a new unvalidated SDM child with its own bound run (Phase 3, #1149). All return strict-JSONenvelopes with ``status`` ok/error and never raise on invalid parametertypes.@@ -37,7 +37,8 @@ requires_tools = pytest.mark.skipif(READ_TOOL_NAMES = {"list_strategies", "query_strategies", "get_strategy_evidence"}WRITE_TOOL_NAME = "refresh_strategy_evidence"-EXPECTED_NAMES = READ_TOOL_NAMES | {WRITE_TOOL_NAME}+WRITE_TOOL_NAMES = {WRITE_TOOL_NAME, "adapt_strategy"}+EXPECTED_NAMES = READ_TOOL_NAMES | WRITE_TOOL_NAMESdef _strict_json_loads(text: str) -> dict:@@ -114,8 +115,8 @@ def _discover_tool_classes():def _instantiate_tools() -> dict:classes = _discover_tool_classes()- assert len(classes) == 4, (- f"expected exactly 4 BaseTool classes in strategy_discovery_tool, found "+ assert len(classes) == len(EXPECTED_NAMES), (+ f"expected exactly {len(EXPECTED_NAMES)} BaseTool classes in strategy_discovery_tool, found "f"{[c.__name__ for c in classes]}")tools = {cls().name: cls() for cls in classes}@@ -137,11 +138,9 @@ class TestToolClasses:), f"{name} must declare a JSON-schema parameters block"assert tool.is_readonly is True, f"{name} must be read-only"- def test_refresh_tool_is_the_single_write_tool(self, fake_facade) -> None:- # Phase 2 (plan D13): refresh_strategy_evidence is a WRITE tool, but- # its scope is the disposable evidence cache only — it rebuilds that- # cache from run artifacts and never touches Alpha Zoo/SDM sources of- # truth. It must be the ONLY non-read-only tool in the module.+ def test_only_refresh_and_adaptation_are_write_tools(self, fake_facade) -> None:+ # Refresh remains limited to evidence-cache replacement; Phase 3 adds+ # the independently guarded SDM-child write, never an edit to the parent.tools = _instantiate_tools()tool = tools[WRITE_TOOL_NAME]assert isinstance(tool, BaseTool)@@ -154,9 +153,9 @@ class TestToolClasses:non_readonly = [name for name, instance in tools.items() if instance.is_readonly is False]- assert non_readonly == [- WRITE_TOOL_NAME- ], f"only {WRITE_TOOL_NAME} may be non-read-only, got {non_readonly}"+ assert set(non_readonly) == WRITE_TOOL_NAMES+ assert tools["adapt_strategy"].parameters+ assert tools["adapt_strategy"].repeatable is False@requires_toolsdiff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.jsonindex 1553ed15e..a9c3ba390 100644--- a/frontend/src/i18n/locales/fa.json+++ b/frontend/src/i18n/locales/fa.json@@ -1,6 +1,6 @@{"app": {- "version": "v0.1.14"+ "version": "v0.1.16"},"charts": {"noPriceData": "هنوز داده قیمتی برای این نماد وجود ندارد",diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.jsonindex 93969b38a..335c87448 100644--- a/frontend/src/i18n/locales/tr.json+++ b/frontend/src/i18n/locales/tr.json@@ -1,6 +1,6 @@{"app": {- "version": "v0.1.15"+ "version": "v0.1.16"},"charts": {"noPriceData": "Bu sembol için henüz fiyat verisi yok",