The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(mcp): demote re-park lines to DEBUG while a server never revived
liuhao102478b8669b698d
diff --git a/tests/tools/test_mcp_park_log_dedupe.py b/tests/tools/test_mcp_park_log_dedupe.pynew file mode 100644index 00000000000..46738000e58--- /dev/null+++ b/tests/tools/test_mcp_park_log_dedupe.py@@ -0,0 +1,150 @@+"""Tests for parked-MCP-server log dedupe (#115713).++A parked server's timed self-probe wakes the run task, which retries the+transport and — when the dependency is still down — re-parks. Every re-park+used to emit the same WARNING as the first park, so a long-lived gateway+accumulated thousands of identical lines per month (10,548 for one server in+the report) and drowned the genuinely-new errors in gateway.error.log. The+park lines now go through ``MCPServerTask._log_park``: the first park (a real+state transition) warns; re-parks while the server never revived are demoted+to DEBUG. A session that proves healthy clears ``_was_parked``, so the next+outage warns again.+"""++import asyncio+import logging++import pytest++from tools.mcp_tool import MCPServerTask+++def _fast_time(monkeypatch):+ """Zero out the retry sleeps and the parked self-probe interval."""+ from tools import mcp_tool++ monkeypatch.setattr(mcp_tool, "_PARKED_RETRY_INTERVAL", 0)+ real_sleep = asyncio.sleep++ async def _sleep(_delay, *a, **kw):+ await real_sleep(0)++ monkeypatch.setattr(asyncio, "sleep", _sleep)++[email protected]_isolate+def test_reparked_server_logs_once_not_per_probe(monkeypatch, tmp_path, caplog):+ """First park warns; every failed self-probe that re-parks the same dead+ server logs at DEBUG only — the parked state is already visible via+ ``hermes mcp list`` (#115713)."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ from tools import mcp_tool++ monkeypatch.setattr(mcp_tool, "_MAX_INITIAL_CONNECT_RETRIES", 1)+ _fast_time(monkeypatch)++ state = {"calls": 0}++ async def _scenario():+ class _Task(MCPServerTask):+ def _is_http(self):+ return False++ def _deregister_tools(self):+ self._registered_tool_names = []++ async def _run_stdio(self, config):+ state["calls"] += 1+ if state["calls"] >= 10:+ self._shutdown_event.set()+ raise ConnectionError("addon not running")++ task = _Task("blender")+ task._registered_tool_names = []+ run_task = asyncio.ensure_future(task.run({"command": "x"}))+ await asyncio.wait_for(run_task, timeout=15)++ with caplog.at_level(logging.DEBUG, logger="tools.mcp_tool"):+ asyncio.run(_scenario())++ parks = [+ r for r in caplog.records if "failed initial connection after" in r.getMessage()+ ]+ assert len(parks) >= 4, (+ f"scenario only produced {len(parks)} park lines — expected several "+ "self-probe re-park cycles"+ )+ assert sum(1 for r in parks if r.levelno >= logging.WARNING) == 1, (+ "the first park must warn exactly once; the re-parks must be DEBUG"+ )+ assert sum(1 for r in parks if r.levelno == logging.DEBUG) >= 3++[email protected]_isolate+def test_park_after_revival_warns_again(monkeypatch, tmp_path, caplog):+ """A server that revived (session proven → ``_was_parked`` cleared) and then+ fails again must warn on its next park: a fresh outage is a state+ transition, not probe chatter."""+ monkeypatch.setenv("HERMES_HOME", str(tmp_path))++ from tools import mcp_tool++ monkeypatch.setattr(mcp_tool, "_MAX_INITIAL_CONNECT_RETRIES", 1)+ monkeypatch.setattr(mcp_tool, "_MAX_RECONNECT_RETRIES", 1)+ _fast_time(monkeypatch)++ state = {"calls": 0}++ async def _scenario():+ class _Task(MCPServerTask):+ def _is_http(self):+ return False++ def _deregister_tools(self):+ self._registered_tool_names = []++ async def _run_stdio(self, config):+ state["calls"] += 1+ if state["calls"] == 3:+ # The revival probe succeeds: session proves healthy and+ # clears the parked latch.+ self._ever_connected = True+ self.session = object()+ self._ready.set()+ self._mark_session_proven()+ self.session = None+ return "reconnect"+ if state["calls"] >= 7:+ self._shutdown_event.set()+ raise ConnectionError("addon not running")++ task = _Task("blender")+ task._registered_tool_names = []+ run_task = asyncio.ensure_future(task.run({"command": "x"}))+ await asyncio.wait_for(run_task, timeout=15)++ with caplog.at_level(logging.DEBUG, logger="tools.mcp_tool"):+ asyncio.run(_scenario())++ initial_parks = [+ r for r in caplog.records if "failed initial connection after" in r.getMessage()+ ]+ reconnect_parks = [+ r for r in caplog.records if "reconnection attempts" in r.getMessage()+ ]+ assert [r.levelno >= logging.WARNING for r in initial_parks] == [True]+ # First park of the new outage warns; the re-park after it is DEBUG.+ assert [r.levelno >= logging.WARNING for r in reconnect_parks] == [True, False]+++def test_log_park_first_warns_repeat_debugs(caplog):+ task = MCPServerTask("t")+ task._was_parked = False+ with caplog.at_level(logging.DEBUG, logger="tools.mcp_tool"):+ task._log_park("first park of %s", "t")+ assert caplog.records[-1].levelno == logging.WARNING+ caplog.clear()+ task._was_parked = True+ task._log_park("repeat park of %s", "t")+ assert caplog.records[-1].levelno == logging.DEBUGdiff --git a/tools/mcp_tool_server_run.py b/tools/mcp_tool_server_run.pyindex 5eb4c379c5c..0b58c15008b 100644--- a/tools/mcp_tool_server_run.py+++ b/tools/mcp_tool_server_run.py@@ -170,6 +170,17 @@ class MCPServerRunMixin:self._reconnect_event.clear()return "reconnect"+ def _log_park(self, msg: str, *args) -> None:+ """Park chatter control (#115713): re-parking a server that never revived is not a state+ transition — ``hermes mcp list`` already surfaces the parked state, so one identical+ WARNING per self-probe carries no new information. The first park (and the revived line+ in ``_mark_session_proven``) stays a WARNING; repeats while still parked are demoted to+ DEBUG so a long-lived gateway's error log is not flooded (10k+ identical lines/month)."""+ if self._was_parked:+ logger.debug(msg, *args)+ else:+ logger.warning(msg, *args)+async def _park(self, revival_reason: str) -> bool:"""Drop this server's tools and wait for a reconnect request; True when shutdown came instead.The run task must NOT exit (it is the only ``_reconnect_event`` listener, so returning@@ -337,7 +348,7 @@ class MCPServerRunMixin:else:self._reconnect_retries += 1if self._reconnect_retries > _core._MAX_RECONNECT_RETRIES:- logger.warning(+ self._log_park("MCP server '%s': %d consecutive reconnects without a healthy session (rapid-drop budget ""exhausted), parking; will self-probe every %ds until it recovers (state: degraded → parked)",self.name, _core._MAX_RECONNECT_RETRIES, _core._PARKED_RETRY_INTERVAL)@@ -398,7 +409,7 @@ class MCPServerRunMixin:return await self._on_permanent_error(root, budget)self._reconnect_retries += 1if self._reconnect_retries > _core._MAX_RECONNECT_RETRIES:- logger.warning(+ self._log_park("MCP server '%s' failed after %d reconnection attempts, parking; will self-probe every %ds ""until it recovers (state: degraded → parked): %s: %s",self.name, _core._MAX_RECONNECT_RETRIES, _core._PARKED_RETRY_INTERVAL, type(root).__name__, root)@@ -417,12 +428,12 @@ class MCPServerRunMixin:detail = (f"authentication, parking until credentials change; re-authenticate with "f"`hermes mcp login {self.name}`" if _errors._is_auth_error(root)else "connection with a permanent error, parking without retries")- logger.warning("MCP server '%s' failed initial %s (state: connecting → parked): %s: %s",+ self._log_park("MCP server '%s' failed initial %s (state: connecting → parked): %s: %s",self.name, detail, type(root).__name__, root)return await self._park_initial_failure(exc, "after permanent initial failure", budget)budget.initial_retries += 1if budget.initial_retries > _core._MAX_INITIAL_CONNECT_RETRIES:- logger.warning(+ self._log_park("MCP server '%s' failed initial connection after %d attempts, parking until a reconnect is ""requested (state: connecting → parked): %s: %s",self.name, _core._MAX_INITIAL_CONNECT_RETRIES, type(root).__name__, root)@@ -450,7 +461,7 @@ class MCPServerRunMixin:await asyncio.sleep(_jittered(1.0))return not self._shutdown_event.is_set()# Deterministic failure on a working server: park now.- logger.warning(+ self._log_park("MCP server '%s' hit a permanent error, parking without retries; will self-probe every %ds ""(state: connected → parked): %s: %s", self.name, _core._PARKED_RETRY_INTERVAL, type(root).__name__, root)return await self._park_and_rearm("from parked state (permanent error)", budget)