Files
Cerbero-Bite/tests/unit/test_mcp_endpoints.py
Adriano ce158a92dd 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>
2026-05-01 17:14:40 +02:00

116 lines
3.5 KiB
Python

"""Tests for the MCP endpoint, token and bot-tag resolver."""
from __future__ import annotations
import pytest
from cerbero_bite.config.mcp_endpoints import (
DEFAULT_BOT_TAG,
DEFAULT_ENDPOINTS,
MCP_SERVICES,
load_bot_tag,
load_endpoints,
load_token,
)
def test_defaults_match_known_docker_dns() -> None:
assert DEFAULT_ENDPOINTS["deribit"] == "http://mcp-deribit:9011"
assert DEFAULT_ENDPOINTS["sentiment"] == "http://mcp-sentiment:9014"
def test_load_endpoints_uses_defaults_when_env_empty() -> None:
endpoints = load_endpoints(env={})
for name, url in DEFAULT_ENDPOINTS.items():
assert endpoints.for_service(name) == url
def test_per_service_env_var_override() -> None:
endpoints = load_endpoints(
env={"CERBERO_BITE_MCP_DERIBIT_URL": "http://localhost:9911"}
)
assert endpoints.deribit == "http://localhost:9911"
assert endpoints.macro == DEFAULT_ENDPOINTS["macro"]
def test_per_service_env_var_strips_trailing_slash() -> None:
endpoints = load_endpoints(
env={"CERBERO_BITE_MCP_DERIBIT_URL": "http://localhost:9911///"}
)
assert endpoints.deribit == "http://localhost:9911"
def test_for_service_unknown_raises_key_error() -> None:
endpoints = load_endpoints(env={})
with pytest.raises(KeyError, match="unknown MCP service"):
endpoints.for_service("nope")
def test_load_token_uses_explicit_value() -> None:
assert load_token(value="abcdef") == "abcdef"
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_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_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(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:
# Telegram and Portfolio are now in-process and must NOT be listed
# as shared MCP services.
expected = {"deribit", "hyperliquid", "macro", "sentiment"}
assert set(MCP_SERVICES) == expected