feat(mcp+runtime): allineamento a Cerbero MCP V2 e flag operativi
Adegua Cerbero Bite alla nuova versione 2.0.0 del server MCP unificato (testnet/mainnet routing per token, header X-Bot-Tag obbligatorio) e introduce due interruttori operativi indipendenti per separare la raccolta dati dall'esecuzione di strategia. Auth e collegamento MCP - Token bearer letto dalla nuova variabile CERBERO_BITE_MCP_TOKEN; il valore sceglie l'ambiente upstream (testnet vs mainnet) sul server. Rimosso il caricamento da file (`secrets/core.token`, CERBERO_BITE_CORE_TOKEN_FILE, Docker secret /run/secrets/core_token). - Aggiunto header X-Bot-Tag (default `BOT__CERBERO_BITE`, override via CERBERO_BITE_MCP_BOT_TAG) su ogni call MCP, con validazione lato client (non vuoto, ≤ 64 caratteri). - Cartella `secrets/` rimossa, `.gitignore` ripulito, Dockerfile e docker-compose.yml aggiornati con env passthrough e fail-fast quando manca il token. Modalità operativa (RuntimeFlags) - Nuovo modulo `config/runtime_flags.py` con `RuntimeFlags( data_analysis_enabled, strategy_enabled)` e loader che parserizza CERBERO_BITE_ENABLE_DATA_ANALYSIS e CERBERO_BITE_ENABLE_STRATEGY (true/false/yes/no/on/off/enabled/disabled, case-insensitive). - L'orchestratore espone i flag, audita e logga la modalità al boot (`engine started: env=… data_analysis=… strategy=…`), e in `install_scheduler` esclude i job `entry`/`monitor` quando strategy è off e il job `market_snapshot` quando data analysis è off. I job di infrastruttura (health, backup, manual_actions) restano sempre attivi. - Default profile = "solo analisi dati" (data_analysis=true, strategy=false), pensato per la finestra di soak post-deploy. GUI saldi - `gui/live_data.py::_fetch_deribit_currency` riconosce il campo soft `error` nel payload V2 (HTTP 200 con `error` valorizzato dal server quando l'auth Deribit fallisce) e lo propaga come `BalanceRow.error`, evitando di mostrare un fuorviante equity = 0,00. CLI - Sostituita l'opzione `--token-file` con `--token` (stringa) sui comandi start/dry-run/ping; il default proviene dall'env. Le chiamate al builder dell'orchestrator passano anche `bot_tag` e `flags`. Documentazione - `docs/04-mcp-integration.md`: descrizione del nuovo flusso di auth V2 (token = ambiente, X-Bot-Tag nell'audit) e router unificati. - `docs/06-operational-flow.md`: nuova sezione "Modalità operativa" con i tre profili canonici e tabella di gating per ogni job; aggiunto `market_snapshot` al cron summary. - `docs/10-config-spec.md`: nuova sezione "Variabili d'ambiente" tabellare con tutti gli env, comprese le bool dei flag operativi. - `docs/02-architecture.md`: layout del repo aggiornato (`secrets/` rimosso, `runtime_flags.py` aggiunto), descrizione di `config/` estesa. Test - 5 nuovi test su `_fetch_deribit_currency` (soft-error, payload pulito, eccezione, error blank, signature parity). - 7 nuovi test su `load_runtime_flags` (default, override, parsing truthy/falsy, blank fallback, valore invalido). - 4 nuovi test su `HttpToolClient` (X-Bot-Tag default e custom, blank e troppo lungo rifiutati). - 3 nuovi test integration sull'orchestratore (gating dei job in base ai flag). - Test esistenti su token/CLI ping/orchestrator aggiornati al nuovo schema. Suite intera: 404 passed, 1 skipped (sqlite3 CLI assente sull'host di sviluppo). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -11,6 +11,7 @@ from pytest_httpx import HTTPXMock
|
||||
|
||||
from cerbero_bite.config import golden_config
|
||||
from cerbero_bite.config.mcp_endpoints import load_endpoints
|
||||
from cerbero_bite.config.runtime_flags import RuntimeFlags
|
||||
from cerbero_bite.runtime import Orchestrator
|
||||
from cerbero_bite.runtime.dependencies import build_runtime
|
||||
|
||||
@@ -58,7 +59,12 @@ def _wire_health_probes(httpx_mock: HTTPXMock) -> None:
|
||||
)
|
||||
|
||||
|
||||
def _build_orch(tmp_path: Path, *, expected: str = "testnet") -> Orchestrator:
|
||||
def _build_orch(
|
||||
tmp_path: Path,
|
||||
*,
|
||||
expected: str = "testnet",
|
||||
flags: RuntimeFlags | None = None,
|
||||
) -> Orchestrator:
|
||||
ctx = build_runtime(
|
||||
cfg=golden_config(),
|
||||
endpoints=load_endpoints(env={}),
|
||||
@@ -72,6 +78,8 @@ def _build_orch(tmp_path: Path, *, expected: str = "testnet") -> Orchestrator:
|
||||
ctx,
|
||||
expected_environment=expected, # type: ignore[arg-type]
|
||||
eur_to_usd=Decimal("1.075"),
|
||||
flags=flags
|
||||
or RuntimeFlags(data_analysis_enabled=True, strategy_enabled=True),
|
||||
)
|
||||
|
||||
|
||||
@@ -122,3 +130,41 @@ def test_install_scheduler_registers_canonical_jobs(tmp_path: Path) -> None:
|
||||
"manual_actions",
|
||||
"market_snapshot",
|
||||
}
|
||||
|
||||
|
||||
def test_install_scheduler_skips_strategy_jobs_when_disabled(tmp_path: Path) -> None:
|
||||
orch = _build_orch(
|
||||
tmp_path,
|
||||
flags=RuntimeFlags(data_analysis_enabled=True, strategy_enabled=False),
|
||||
)
|
||||
sched = orch.install_scheduler()
|
||||
job_ids = {j.id for j in sched.get_jobs()}
|
||||
assert "entry" not in job_ids
|
||||
assert "monitor" not in job_ids
|
||||
# data analysis stays on, plus the always-on infra jobs.
|
||||
assert {"health", "backup", "manual_actions", "market_snapshot"}.issubset(job_ids)
|
||||
|
||||
|
||||
def test_install_scheduler_skips_market_snapshot_when_data_analysis_off(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
orch = _build_orch(
|
||||
tmp_path,
|
||||
flags=RuntimeFlags(data_analysis_enabled=False, strategy_enabled=True),
|
||||
)
|
||||
sched = orch.install_scheduler()
|
||||
job_ids = {j.id for j in sched.get_jobs()}
|
||||
assert "market_snapshot" not in job_ids
|
||||
assert {"entry", "monitor", "health", "backup", "manual_actions"}.issubset(
|
||||
job_ids
|
||||
)
|
||||
|
||||
|
||||
def test_install_scheduler_analysis_only_default(tmp_path: Path) -> None:
|
||||
"""The default RuntimeFlags profile (analysis only) drops entry/monitor."""
|
||||
orch = _build_orch(tmp_path, flags=RuntimeFlags())
|
||||
sched = orch.install_scheduler()
|
||||
job_ids = {j.id for j in sched.get_jobs()}
|
||||
assert "entry" not in job_ids
|
||||
assert "monitor" not in job_ids
|
||||
assert "market_snapshot" in job_ids
|
||||
|
||||
+11
-21
@@ -7,25 +7,14 @@ contains the expected statuses.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from click.testing import CliRunner
|
||||
from pytest_httpx import HTTPXMock
|
||||
|
||||
from cerbero_bite.cli import main as cli_main
|
||||
|
||||
|
||||
def _seed_token(tmp_path: Path) -> Path:
|
||||
target = tmp_path / "core_token"
|
||||
target.write_text("super-secret\n", encoding="utf-8")
|
||||
return target
|
||||
|
||||
|
||||
def test_ping_reports_each_service(
|
||||
tmp_path: Path, httpx_mock: HTTPXMock
|
||||
) -> None:
|
||||
token_file = _seed_token(tmp_path)
|
||||
|
||||
def test_ping_reports_each_service(httpx_mock: HTTPXMock) -> None:
|
||||
httpx_mock.add_response(
|
||||
url="http://mcp-deribit:9011/tools/environment_info",
|
||||
json={
|
||||
@@ -51,7 +40,7 @@ def test_ping_reports_each_service(
|
||||
)
|
||||
|
||||
result = CliRunner().invoke(
|
||||
cli_main, ["ping", "--token-file", str(token_file), "--timeout", "1.0"]
|
||||
cli_main, ["ping", "--token", "super-secret", "--timeout", "1.0"]
|
||||
)
|
||||
assert result.exit_code == 0, result.output
|
||||
assert "deribit" in result.output
|
||||
@@ -65,9 +54,8 @@ def test_ping_reports_each_service(
|
||||
|
||||
|
||||
def test_ping_reports_failure_when_service_unreachable(
|
||||
tmp_path: Path, httpx_mock: HTTPXMock
|
||||
httpx_mock: HTTPXMock,
|
||||
) -> None:
|
||||
token_file = _seed_token(tmp_path)
|
||||
httpx_mock.add_response(
|
||||
url="http://mcp-deribit:9011/tools/environment_info",
|
||||
status_code=500,
|
||||
@@ -88,15 +76,17 @@ def test_ping_reports_failure_when_service_unreachable(
|
||||
)
|
||||
|
||||
result = CliRunner().invoke(
|
||||
cli_main, ["ping", "--token-file", str(token_file), "--timeout", "1.0"]
|
||||
cli_main, ["ping", "--token", "super-secret", "--timeout", "1.0"]
|
||||
)
|
||||
assert result.exit_code == 0
|
||||
assert "FAIL" in result.output
|
||||
|
||||
|
||||
def test_ping_token_missing_exits_nonzero(tmp_path: Path) -> None:
|
||||
result = CliRunner().invoke(
|
||||
cli_main, ["ping", "--token-file", str(tmp_path / "nope")]
|
||||
)
|
||||
def test_ping_token_missing_exits_nonzero(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
# Ensure no env var leaks into the CLI invocation.
|
||||
monkeypatch.delenv("CERBERO_BITE_MCP_TOKEN", raising=False)
|
||||
result = CliRunner().invoke(cli_main, ["ping"])
|
||||
assert result.exit_code == 1
|
||||
assert "token error" in result.output
|
||||
|
||||
@@ -47,6 +47,28 @@ async def test_call_attaches_bearer_token(httpx_mock: HTTPXMock) -> None:
|
||||
assert request is not None
|
||||
assert request.headers["Authorization"] == "Bearer abc123"
|
||||
assert request.headers["Content-Type"] == "application/json"
|
||||
# Default bot tag is sent on every request.
|
||||
assert request.headers["X-Bot-Tag"] == "BOT__CERBERO_BITE"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_call_attaches_custom_bot_tag(httpx_mock: HTTPXMock) -> None:
|
||||
httpx_mock.add_response(json={"ok": True})
|
||||
client = _make_client(bot_tag="BOT__SHADOW")
|
||||
await client.call("any")
|
||||
request = httpx_mock.get_request()
|
||||
assert request is not None
|
||||
assert request.headers["X-Bot-Tag"] == "BOT__SHADOW"
|
||||
|
||||
|
||||
def test_init_rejects_blank_bot_tag() -> None:
|
||||
with pytest.raises(ValueError, match="non-empty"):
|
||||
_make_client(bot_tag=" ")
|
||||
|
||||
|
||||
def test_init_rejects_too_long_bot_tag() -> None:
|
||||
with pytest.raises(ValueError, match="64"):
|
||||
_make_client(bot_tag="x" * 65)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Tests for the GUI live-balances fetcher (soft-error handling)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
|
||||
from cerbero_bite.clients.deribit import DeribitClient
|
||||
from cerbero_bite.gui.live_data import _fetch_deribit_currency
|
||||
|
||||
|
||||
class _FakeDeribit:
|
||||
def __init__(self, payload: dict[str, Any] | Exception) -> None:
|
||||
self._payload = payload
|
||||
|
||||
async def get_account_summary(self, currency: str) -> dict[str, Any]:
|
||||
del currency # not used by the fake; kept for signature parity
|
||||
if isinstance(self._payload, Exception):
|
||||
raise self._payload
|
||||
return self._payload
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_soft_error_payload_becomes_row_error() -> None:
|
||||
"""MCP V2 returns 200 + ``error`` field when upstream auth fails."""
|
||||
fake = _FakeDeribit(
|
||||
{
|
||||
"equity": 0,
|
||||
"balance": 0,
|
||||
"available_funds": 0,
|
||||
"unrealized_pnl": 0,
|
||||
"error": "Deribit auth failed (code=13004): invalid_credentials",
|
||||
}
|
||||
)
|
||||
row = await _fetch_deribit_currency(
|
||||
deribit=fake, # type: ignore[arg-type]
|
||||
currency="USDC",
|
||||
)
|
||||
assert row.exchange == "deribit"
|
||||
assert row.currency == "USDC"
|
||||
assert row.equity is None
|
||||
assert row.available is None
|
||||
assert row.unrealized_pnl is None
|
||||
assert row.error is not None
|
||||
assert "invalid_credentials" in row.error
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_clean_payload_populates_balance_fields() -> None:
|
||||
fake = _FakeDeribit(
|
||||
{
|
||||
"equity": "12.5",
|
||||
"available_funds": "10.0",
|
||||
"unrealized_pnl": "-0.25",
|
||||
}
|
||||
)
|
||||
row = await _fetch_deribit_currency(
|
||||
deribit=fake, # type: ignore[arg-type]
|
||||
currency="USDC",
|
||||
)
|
||||
assert row.error is None
|
||||
assert row.equity == Decimal("12.5")
|
||||
assert row.available == Decimal("10.0")
|
||||
assert row.unrealized_pnl == Decimal("-0.25")
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_exception_becomes_row_error() -> None:
|
||||
fake = _FakeDeribit(RuntimeError("boom"))
|
||||
row = await _fetch_deribit_currency(
|
||||
deribit=fake, # type: ignore[arg-type]
|
||||
currency="USDC",
|
||||
)
|
||||
assert row.equity is None
|
||||
assert row.error is not None
|
||||
assert "RuntimeError" in row.error
|
||||
assert "boom" in row.error
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_blank_error_field_is_ignored() -> None:
|
||||
"""An ``error`` field that is empty/None must not trigger the soft-error path."""
|
||||
fake = _FakeDeribit(
|
||||
{"equity": "1.0", "available_funds": "1.0", "unrealized_pnl": "0.0", "error": None}
|
||||
)
|
||||
row = await _fetch_deribit_currency(
|
||||
deribit=fake, # type: ignore[arg-type]
|
||||
currency="USDC",
|
||||
)
|
||||
assert row.error is None
|
||||
assert row.equity == Decimal("1.0")
|
||||
|
||||
|
||||
# Sanity-check: the production class signature is what we expect to be drop-in
|
||||
# replaceable by ``_FakeDeribit``.
|
||||
def test_fake_matches_production_signature() -> None:
|
||||
assert hasattr(DeribitClient, "get_account_summary")
|
||||
@@ -1,14 +1,14 @@
|
||||
"""Tests for the MCP endpoint and token resolver."""
|
||||
"""Tests for the MCP endpoint, token and bot-tag resolver."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from cerbero_bite.config.mcp_endpoints import (
|
||||
DEFAULT_BOT_TAG,
|
||||
DEFAULT_ENDPOINTS,
|
||||
MCP_SERVICES,
|
||||
load_bot_tag,
|
||||
load_endpoints,
|
||||
load_token,
|
||||
)
|
||||
@@ -46,29 +46,66 @@ def test_for_service_unknown_raises_key_error() -> None:
|
||||
endpoints.for_service("nope")
|
||||
|
||||
|
||||
def test_load_token_uses_explicit_path(tmp_path: Path) -> None:
|
||||
target = tmp_path / "core.token"
|
||||
target.write_text("abcdef\n", encoding="utf-8")
|
||||
assert load_token(path=target) == "abcdef"
|
||||
def test_load_token_uses_explicit_value() -> None:
|
||||
assert load_token(value="abcdef") == "abcdef"
|
||||
|
||||
|
||||
def test_load_token_uses_env_var(tmp_path: Path) -> None:
|
||||
target = tmp_path / "core.token"
|
||||
target.write_text("xyz", encoding="utf-8")
|
||||
token = load_token(env={"CERBERO_BITE_CORE_TOKEN_FILE": str(target)})
|
||||
def test_load_token_strips_whitespace_in_explicit_value() -> None:
|
||||
assert load_token(value=" abcdef\n") == "abcdef"
|
||||
|
||||
|
||||
def test_load_token_uses_env_var() -> None:
|
||||
token = load_token(env={"CERBERO_BITE_MCP_TOKEN": "xyz"})
|
||||
assert token == "xyz"
|
||||
|
||||
|
||||
def test_load_token_raises_when_file_missing(tmp_path: Path) -> None:
|
||||
with pytest.raises(FileNotFoundError):
|
||||
load_token(path=tmp_path / "missing")
|
||||
def test_load_token_strips_whitespace_in_env_var() -> None:
|
||||
token = load_token(env={"CERBERO_BITE_MCP_TOKEN": " xyz\n"})
|
||||
assert token == "xyz"
|
||||
|
||||
|
||||
def test_load_token_raises_when_file_empty(tmp_path: Path) -> None:
|
||||
target = tmp_path / "empty"
|
||||
target.write_text("", encoding="utf-8")
|
||||
def test_load_token_raises_when_missing() -> None:
|
||||
with pytest.raises(ValueError, match="CERBERO_BITE_MCP_TOKEN"):
|
||||
load_token(env={})
|
||||
|
||||
|
||||
def test_load_token_raises_when_empty() -> None:
|
||||
with pytest.raises(ValueError, match="CERBERO_BITE_MCP_TOKEN"):
|
||||
load_token(env={"CERBERO_BITE_MCP_TOKEN": " "})
|
||||
|
||||
|
||||
def test_load_token_raises_when_explicit_value_blank() -> None:
|
||||
with pytest.raises(ValueError, match="empty"):
|
||||
load_token(path=target)
|
||||
load_token(value=" ")
|
||||
|
||||
|
||||
def test_load_bot_tag_default_when_unset() -> None:
|
||||
assert load_bot_tag(env={}) == DEFAULT_BOT_TAG
|
||||
|
||||
|
||||
def test_load_bot_tag_explicit_value_overrides_env() -> None:
|
||||
tag = load_bot_tag(value="BOT__CUSTOM", env={"CERBERO_BITE_MCP_BOT_TAG": "x"})
|
||||
assert tag == "BOT__CUSTOM"
|
||||
|
||||
|
||||
def test_load_bot_tag_uses_env_when_set() -> None:
|
||||
tag = load_bot_tag(env={"CERBERO_BITE_MCP_BOT_TAG": "BOT__SHADOW"})
|
||||
assert tag == "BOT__SHADOW"
|
||||
|
||||
|
||||
def test_load_bot_tag_strips_whitespace() -> None:
|
||||
tag = load_bot_tag(env={"CERBERO_BITE_MCP_BOT_TAG": " BOT__X\n"})
|
||||
assert tag == "BOT__X"
|
||||
|
||||
|
||||
def test_load_bot_tag_falls_back_to_default_when_blank_env() -> None:
|
||||
tag = load_bot_tag(env={"CERBERO_BITE_MCP_BOT_TAG": " "})
|
||||
assert tag == DEFAULT_BOT_TAG
|
||||
|
||||
|
||||
def test_load_bot_tag_rejects_too_long() -> None:
|
||||
with pytest.raises(ValueError, match="exceeds 64"):
|
||||
load_bot_tag(value="x" * 65)
|
||||
|
||||
|
||||
def test_mcp_services_table_is_complete() -> None:
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"""Tests for the runtime flag loader."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from cerbero_bite.config.runtime_flags import (
|
||||
DATA_ANALYSIS_ENV,
|
||||
STRATEGY_ENV,
|
||||
RuntimeFlags,
|
||||
load_runtime_flags,
|
||||
)
|
||||
|
||||
|
||||
def test_default_profile_is_analysis_only() -> None:
|
||||
flags = load_runtime_flags(env={})
|
||||
assert flags == RuntimeFlags(
|
||||
data_analysis_enabled=True, strategy_enabled=False
|
||||
)
|
||||
|
||||
|
||||
def test_strategy_can_be_explicitly_enabled() -> None:
|
||||
flags = load_runtime_flags(env={STRATEGY_ENV: "true"})
|
||||
assert flags.strategy_enabled is True
|
||||
assert flags.data_analysis_enabled is True
|
||||
|
||||
|
||||
def test_data_analysis_can_be_disabled() -> None:
|
||||
flags = load_runtime_flags(env={DATA_ANALYSIS_ENV: "false"})
|
||||
assert flags.data_analysis_enabled is False
|
||||
assert flags.strategy_enabled is False
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"raw,expected",
|
||||
[
|
||||
("1", True),
|
||||
("0", False),
|
||||
("yes", True),
|
||||
("no", False),
|
||||
("on", True),
|
||||
("OFF", False),
|
||||
("ENABLED", True),
|
||||
("Disabled", False),
|
||||
("True", True),
|
||||
("False", False),
|
||||
(" true ", True),
|
||||
],
|
||||
)
|
||||
def test_parses_common_truthy_falsy_tokens(raw: str, expected: bool) -> None:
|
||||
flags = load_runtime_flags(env={STRATEGY_ENV: raw})
|
||||
assert flags.strategy_enabled is expected
|
||||
|
||||
|
||||
def test_blank_value_falls_back_to_default() -> None:
|
||||
flags = load_runtime_flags(env={DATA_ANALYSIS_ENV: " ", STRATEGY_ENV: ""})
|
||||
assert flags.data_analysis_enabled is True
|
||||
assert flags.strategy_enabled is False
|
||||
|
||||
|
||||
def test_unknown_token_raises() -> None:
|
||||
with pytest.raises(ValueError, match=DATA_ANALYSIS_ENV):
|
||||
load_runtime_flags(env={DATA_ANALYSIS_ENV: "maybe"})
|
||||
Reference in New Issue
Block a user