Skip to content

The agent that grows with you

fix(tui-gateway): scope MCP discovery to active profile

LionGateOSc6e811e48f26
diff --git a/tests/test_tui_gateway_server.py b/tests/test_tui_gateway_server.py
index dbdd2ec5ffc..dfbe62f2808 100644
--- a/tests/test_tui_gateway_server.py
+++ b/tests/test_tui_gateway_server.py
@@ -566,6 +566,93 @@ def _write_profile_cfg(home: Path, cwd: str | None) -> Path:
return home
+def test_profile_scoped_mcp_discovery_uses_target_home(monkeypatch, tmp_path):
+ """MCP discovery must start under the selected profile's HERMES_HOME."""
+ from hermes_constants import get_hermes_home
+ from tui_gateway import entry
+
+ profile_home = tmp_path / "profiles" / "sheepyr"
+ profile_home.mkdir(parents=True)
+
+ (profile_home / "config.yaml").write_text(
+ "mcp_servers:\n"
+ " bluesky_sheepyr:\n"
+ " command: test-command\n",
+ encoding="utf-8",
+ )
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "default"))
+ token = set_hermes_home_override(str(profile_home))
+
+ seen = []
+
+ monkeypatch.setattr(entry, "_mcp_discovery_thread", None)
+ monkeypatch.setattr(
+ "tools.mcp_tool.discover_mcp_tools",
+ lambda: seen.append(str(get_hermes_home())),
+ )
+
+ try:
+ entry.ensure_mcp_discovery_started()
+ thread = entry._mcp_discovery_thread
+ assert thread is not None
+ thread.join(timeout=2)
+ finally:
+ reset_hermes_home_override(token)
+ entry._mcp_discovery_thread = None
+
+ assert seen == [str(profile_home)]
+
+
+def test_profile_scoped_agent_build_starts_mcp_discovery_in_profile_home(
+ monkeypatch, tmp_path
+):
+ """Agent construction must start MCP discovery under the selected profile."""
+ import threading
+
+ from hermes_constants import get_hermes_home
+
+ profile_home = tmp_path / "profiles" / "sheepyr"
+ profile_home.mkdir(parents=True)
+
+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / "default"))
+
+ seen = []
+ built = threading.Event()
+
+ monkeypatch.setattr(
+ server,
+ "_make_agent",
+ lambda *args, **kwargs: built.set()
+ or type("Agent", (), {"model": "test"})(),
+ )
+ monkeypatch.setattr(
+ "tui_gateway.entry.ensure_mcp_discovery_started",
+ lambda: seen.append(str(get_hermes_home())),
+ )
+ monkeypatch.setattr(server, "_wire_callbacks", lambda _sid: None)
+ monkeypatch.setattr(server, "_SlashWorker", lambda *args: None)
+ monkeypatch.setattr(server, "_attach_worker", lambda *args: None)
+ monkeypatch.setattr(server, "_config_model_target", lambda: ("", ""))
+
+ ready = threading.Event()
+ sid = "test-sid"
+ session = {
+ "agent_ready": ready,
+ "session_key": "test-key",
+ "profile_home": str(profile_home),
+ }
+
+ server._sessions[sid] = session
+ try:
+ server._start_agent_build(sid, session)
+ assert built.wait(timeout=2)
+ finally:
+ server._sessions.pop(sid, None)
+
+ assert seen == [str(profile_home)]
+
+
def test_profile_configured_cwd_reads_target_profile(tmp_path):
"""A profile's own terminal.cwd is read from its config.yaml."""
project = tmp_path / "proj"
diff --git a/tests/test_tui_gateway_ws.py b/tests/test_tui_gateway_ws.py
index 3c9792d7040..7c6c82dc9b2 100644
--- a/tests/test_tui_gateway_ws.py
+++ b/tests/test_tui_gateway_ws.py
@@ -213,5 +213,7 @@ def test_ws_starts_mcp_discovery_before_ready(monkeypatch):
asyncio.run(ws_mod.handle_ws(FakeWS()))
- assert calls == ["mcp"]
- assert events == ["accept", "ready_after_1"]
+ # Discovery moved to profile-aware agent construction. WebSocket transport
+ # should not start MCP discovery before a profile has been bound.
+ assert calls == []
+ assert events == ["accept", "ready_after_0"]
diff --git a/tui_gateway/entry.py b/tui_gateway/entry.py
index 645fd482119..b7bdb9eecbf 100644
--- a/tui_gateway/entry.py
+++ b/tui_gateway/entry.py
@@ -364,19 +364,26 @@ def ensure_mcp_discovery_started() -> None:
"""
global _mcp_discovery_thread
+ from hermes_constants import get_hermes_home_override, reset_hermes_home_override, set_hermes_home_override
+
if _mcp_discovery_thread is not None:
return
if not _has_configured_mcp_servers():
return
+ home_override = get_hermes_home_override()
+
def _discover_mcp_background() -> None:
+ token = set_hermes_home_override(home_override)
try:
from tools.mcp_tool import discover_mcp_tools
discover_mcp_tools()
except Exception:
logger.warning("Background MCP tool discovery failed", exc_info=True)
+ finally:
+ reset_hermes_home_override(token)
import threading as _mcp_threading
diff --git a/tui_gateway/server.py b/tui_gateway/server.py
index ec43de410a5..7bddf0bc82c 100644
--- a/tui_gateway/server.py
+++ b/tui_gateway/server.py
@@ -1849,6 +1849,14 @@ def _start_agent_build(sid: str, session: dict) -> None:
session_db = SessionDB(db_path=Path(profile_home) / "state.db")
except Exception:
session_db = None
+
+ try:
+ from tui_gateway.entry import ensure_mcp_discovery_started
+
+ ensure_mcp_discovery_started()
+ except Exception:
+ logger.warning("MCP discovery startup failed", exc_info=True)
+
try:
# Lazy-resumed (watch) sessions carry the stored conversation
# id — pass it through so the upgrade continues that session
diff --git a/tui_gateway/ws.py b/tui_gateway/ws.py
index 11469f93c20..795f85c13e7 100644
--- a/tui_gateway/ws.py
+++ b/tui_gateway/ws.py
@@ -303,22 +303,6 @@ async def handle_ws(ws: Any) -> None:
transport = WSTransport(ws, asyncio.get_running_loop(), peer=peer)
- # The desktop app and dashboard chat reach the agent through this WS
- # sidecar, NOT through tui_gateway.entry.main() (the stdio TUI path that
- # spawns the background MCP discovery thread). Without starting it here,
- # discovery never runs in this process: _make_agent only *waits* on the
- # thread (wait_for_mcp_discovery), which no-ops when it was never
- # created, so the agent snapshots an MCP-less tool list and the only way
- # to surface MCP tools is a manual /reload-mcp. Start it once per
- # process here (idempotent, config-gated) before gateway.ready so the
- # first agent build can pick up already-spawning servers. (#38945)
- from hermes_cli.mcp_startup import start_background_mcp_discovery
-
- start_background_mcp_discovery(
- logger=_log,
- thread_name="tui-ws-mcp-discovery",
- )
-
ready_ok = await transport.write_async(
{
"jsonrpc": "2.0",