Skip to content

The agent that grows with you

feat(mcp): make the discovery connect cap configurable (mcp.discovery_concurrency, default 4, 0 = unlimited)

teknium19a1f06293da9
diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.py
index 9199805c952..56bbc6ad806 100644
--- a/hermes_cli/config_defaults.py
+++ b/hermes_cli/config_defaults.py
@@ -519,6 +519,11 @@ DEFAULT_CONFIG = {
# re-sends the full prefix) — costly on long-context models. When false the watcher still
# detects the change and prints /reload-mcp guidance.
"auto_reload_on_config_change": True,
+ # Max MCP servers connected (and their stdio child trees spawned) at once per discovery
+ # pass — at boot, on /reload-mcp and on the config watcher's reconcile. Unbounded, a config
+ # with N servers spawns N process trees in the same instant (RAM/CPU spike, 429 fan-out on
+ # multi-profile fleets). 0 = unlimited.
+ "discovery_concurrency": 4,
},
# Tool-output truncation. max_bytes: terminal_tool output cap in chars (head+tail kept; 50_000 ≈
# 12-15K tokens). max_lines: max `limit` one read_file call may request before clamping.
diff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.py
index 96925664a91..1ebcb461c1a 100644
--- a/tests/tools/test_mcp_tool.py
+++ b/tests/tools/test_mcp_tool.py
@@ -2773,17 +2773,18 @@ class TestDiscoveryFailedCount:
class TestDiscoveryConnectConcurrency:
"""MCP discovery bounds how many servers connect at once (#117373)."""
- def test_concurrent_connects_never_exceed_cap(self):
- """With more servers than the cap, in-flight connects stay capped."""
+ @staticmethod
+ def _run_pass(server_names, cap):
+ """Run a discovery pass with ``mcp.discovery_concurrency=cap``; return (peak in-flight, connected)."""
import asyncio as _asyncio
from tools import mcp_tool_discovery as _discovery
from tools.mcp_tool import _servers
from tools.mcp_tool_loop import _ensure_mcp_loop
- server_names = {f"srv{i}": {"command": "npx", "args": [f"s{i}"]} for i in range(8)}
in_flight = 0
max_in_flight = 0
+ connected = []
async def tracked_register(name, cfg):
nonlocal in_flight, max_in_flight
@@ -2792,50 +2793,34 @@ class TestDiscoveryConnectConcurrency:
# Yield real control so gathers genuinely overlap.
await _asyncio.sleep(0.05)
in_flight -= 1
+ connected.append(name)
return []
with patch("tools.mcp_tool_config._load_mcp_config", return_value=server_names), \
+ patch("hermes_cli.config.load_config", return_value={"mcp": {"discovery_concurrency": cap}}), \
patch("tools.mcp_tool_discovery._discover_and_register_server", side_effect=tracked_register), \
patch("tools.mcp_tool._MCP_AVAILABLE", True), \
patch("tools.mcp_tool_registration._existing_tool_names", return_value=[]):
_ensure_mcp_loop()
- _discovery._run_discovery_pass(server_names)
-
- try:
- assert max_in_flight > 1, "connects should still run concurrently"
- assert max_in_flight <= _discovery._DISCOVERY_CONNECT_CONCURRENCY, (
- f"in-flight connects peaked at {max_in_flight}, "
- f"cap is {_discovery._DISCOVERY_CONNECT_CONCURRENCY}"
- )
- finally:
- for name in server_names:
- _servers.pop(name, None)
-
- def test_cap_lower_than_server_count_still_connects_all(self):
- """A capped pass still connects every server, not just the first N."""
- from tools import mcp_tool_discovery as _discovery
- from tools.mcp_tool import _servers
- from tools.mcp_tool_loop import _ensure_mcp_loop
-
- server_names = {f"srv{i}": {"command": "npx", "args": [f"s{i}"]} for i in range(5)}
- connected = []
+ try:
+ _discovery._run_discovery_pass(server_names)
+ finally:
+ for name in server_names:
+ _servers.pop(name, None)
+ return max_in_flight, connected
- async def recording_register(name, cfg):
- connected.append(name)
- return []
+ def test_configured_cap_bounds_in_flight_connects_and_zero_means_unlimited(self):
+ """``mcp.discovery_concurrency`` caps simultaneous connects (still concurrent, every server
+ still connected — no head-of-line starvation); 0 restores the unbounded gather."""
+ server_names = {f"srv{i}": {"command": "npx", "args": [f"s{i}"]} for i in range(8)}
- with patch("tools.mcp_tool_config._load_mcp_config", return_value=server_names), \
- patch("tools.mcp_tool_discovery._discover_and_register_server", side_effect=recording_register), \
- patch("tools.mcp_tool._MCP_AVAILABLE", True), \
- patch("tools.mcp_tool_registration._existing_tool_names", return_value=[]):
- _ensure_mcp_loop()
- _discovery._run_discovery_pass(server_names)
+ peak, connected = self._run_pass(server_names, cap=3)
+ assert 1 < peak <= 3, f"in-flight connects peaked at {peak}, cap is 3"
+ assert sorted(connected) == sorted(server_names)
- try:
- assert sorted(connected) == sorted(server_names)
- finally:
- for name in server_names:
- _servers.pop(name, None)
+ peak_unlimited, connected = self._run_pass(server_names, cap=0)
+ assert peak_unlimited == len(server_names), f"0 must mean unlimited, peaked at {peak_unlimited}"
+ assert sorted(connected) == sorted(server_names)
def test_pass_timeout_capped_by_waiter_budget(self):
"""The discovery pass timeout is capped so a slow pass cannot outlive the
diff --git a/tools/mcp_tool_discovery.py b/tools/mcp_tool_discovery.py
index 8ec32927dfe..472ddaca2c4 100644
--- a/tools/mcp_tool_discovery.py
+++ b/tools/mcp_tool_discovery.py
@@ -22,9 +22,25 @@ from tools.mcp_tool_scope import _key_name, _key_scope, _key_visible_in_scope, _
logger = logging.getLogger("tools.mcp_tool")
-# Max concurrent MCP server connections per discovery pass (one unbounded
-# `asyncio.gather` spawned every server's subprocess tree simultaneously).
-_DISCOVERY_CONNECT_CONCURRENCY = 3
+# Default max concurrent MCP server connections per discovery pass (one unbounded
+# `asyncio.gather` spawned every server's subprocess tree simultaneously); config.yaml
+# ``mcp.discovery_concurrency`` overrides it, 0 = unlimited (#117373).
+_DISCOVERY_CONNECT_CONCURRENCY = 4
+
+
+def _discovery_connect_concurrency() -> int:
+ """``mcp.discovery_concurrency`` from config (0 = unlimited); a non-integer or negative value
+ warns and falls back to the default rather than silently running unbounded."""
+ try:
+ from hermes_cli.config import load_config
+ raw = (load_config().get("mcp") or {}).get("discovery_concurrency", _DISCOVERY_CONNECT_CONCURRENCY)
+ except Exception:
+ return _DISCOVERY_CONNECT_CONCURRENCY
+ if isinstance(raw, bool) or not isinstance(raw, int) or raw < 0:
+ logger.warning("mcp.discovery_concurrency=%r is not a non-negative integer; using %d",
+ raw, _DISCOVERY_CONNECT_CONCURRENCY)
+ return _DISCOVERY_CONNECT_CONCURRENCY
+ return raw
def _record_connect_failure(server_name: str) -> None:
@@ -382,10 +398,13 @@ async def _discover_all(new_servers: Dict[str, dict]) -> None:
unbounded gather turns a config with many servers into a simultaneous
N-process spawn burst (RAM/CPU spike, EMFILE risk) on every backend boot.
"""
- # ponytail: flat cap for all transports; a per-transport cap only if stdio+HTTP mixes ever matter
- semaphore = asyncio.Semaphore(_DISCOVERY_CONNECT_CONCURRENCY)
+ # Flat cap for all transports; 0 (unlimited) keeps the original unbounded gather.
+ cap = _discovery_connect_concurrency()
+ semaphore = asyncio.Semaphore(cap) if cap > 0 else None
async def _connect_bounded(name: str, cfg: dict):
+ if semaphore is None:
+ return await _discover_and_register_server(name, cfg)
async with semaphore:
return await _discover_and_register_server(name, cfg)
@@ -418,7 +437,8 @@ def _run_discovery_pass(new_servers: Dict[str, dict]) -> None:
# _MCP_DISCOVERY_PASS_MAX_SEC so one stuck connect cannot pin the
# calling thread (and the cross-process discovery lock) for tens of
# minutes; the lock waiter's budget is derived from the same ceiling.
- waves = max(1, -(-len(new_servers) // _DISCOVERY_CONNECT_CONCURRENCY))
+ cap = _discovery_connect_concurrency() or len(new_servers) or 1
+ waves = max(1, -(-len(new_servers) // cap))
timeout = min(120 * waves, _core._MCP_DISCOVERY_PASS_MAX_SEC)
_loop._run_on_mcp_loop(lambda: _discover_all(new_servers), timeout=timeout)
except (TimeoutError, InterruptedError) as _e:
diff --git a/website/docs/user-guide/features/mcp.md b/website/docs/user-guide/features/mcp.md
index 5ac68161419..ba34ca9f915 100644
--- a/website/docs/user-guide/features/mcp.md
+++ b/website/docs/user-guide/features/mcp.md
@@ -738,6 +738,19 @@ That keeps the tool list clean.
Hermes discovers MCP servers at startup and registers their tools into the normal tool registry.
+Servers are connected at most **4 at a time** per discovery pass (startup, `/reload-mcp`, config
+watcher). Every stdio server spawns its own child-process tree, so an unbounded pass with many servers
+used to launch them all in the same instant — a CPU/RAM spike and, on multi-profile fleets, a burst of
+simultaneous provider calls. Tune it in `config.yaml`:
+
+```yaml
+mcp:
+ discovery_concurrency: 4 # max simultaneous server connects; 0 = unlimited
+```
+
+A pass with more servers than the cap runs in waves; each wave keeps the usual 120 s budget (whole
+pass capped at 300 s), so a slow fleet finishes later rather than timing out.
+
### Lazy start
A server with `lazy: true` is registered from the on-disk schema cache instead: its tools appear in the registry immediately, and the process is spawned (or the HTTP endpoint connected) on the first tool call. The cache is written on every live connect, so the first run of a new or changed server is always eager. The banner and the TUI session panel show such a server as **lazy** with its cached tool count (`3 tool(s) (lazy, starts on first use)`) — it is a working server, not a failed one — and the startup discovery summary counts it as `N lazy, not spawned yet`.
diff --git a/website/docs/user-guide/multi-profile-gateways.md b/website/docs/user-guide/multi-profile-gateways.md
index 493c368cf65..56672bc8f11 100644
--- a/website/docs/user-guide/multi-profile-gateways.md
+++ b/website/docs/user-guide/multi-profile-gateways.md
@@ -372,7 +372,10 @@ route *and* credentials, including mTLS `client_cert`/`client_key`) share one
connection, and an owner's `/reload-mcp`
re-registers the sharing profiles' tools without them reloading. `auth: oauth`
servers are never shared across profiles: each profile holds its own token under
-its own `mcp-tokens/` and opens its own connection. Trust policy stays per
+its own `mcp-tokens/` and opens its own connection. Startup connects profiles one
+after another and, within a profile, at most `mcp.discovery_concurrency` servers at
+once (default 4, `0` = unlimited), so a fleet of profiles with many stdio servers
+no longer spawns every helper process in the same instant. Trust policy stays per
profile: a `trust: untrusted` profile sharing a `trust: full` profile's
connection is still asked before every write-capable call, and
`supports_parallel_tool_calls` applies only to the profile that set it. Terminal settings