fix(app): MCP discovery never blocks a turn; secrets masked as lines are written; TTS child gets no MCP secrets

- Discovery runs outside the MCP tool cache's lock (one at a time), so a turn reading the cached
  tools never waits for a slow server; a new conversation refreshes in the background.
- The log hub masks secrets before a line is kept or written, so a key replaced or removed later
  stays hidden on the screen, in copies, files and exports, also after a restart.
- The worker takes JARVIS_MCP_ENV out of its environment at start, before MeloTTS runs, and hands
  it to the brain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-13 10:07:52 +09:00
parent 3ef4281180
commit 8b3905f1c2
8 changed files with 191 additions and 31 deletions

View File

@@ -1188,13 +1188,14 @@ def run_reply_engine(db: "Database", cfg, tts: Optional[Any],
except Exception:
pass
# Refresh MCP tools on new conversation (memory expired)
# Refresh MCP tools on new conversation (memory expired), in the background: starting the
# servers can be slow, and this turn uses the tools already cached.
if is_new_conversation and getattr(cfg, "mcps", {}):
try:
from ..tools.registry import refresh_mcp_tools, is_mcp_cache_initialized
from ..tools.registry import refresh_mcp_tools_in_background, is_mcp_cache_initialized
if is_mcp_cache_initialized():
debug_log("New conversation detected, refreshing MCP tools", "mcp")
_tools, _errors = refresh_mcp_tools(verbose=False)
debug_log("New conversation detected, refreshing MCP tools in the background", "mcp")
refresh_mcp_tools_in_background()
except Exception as e:
debug_log(f"MCP refresh on new conversation failed: {e}", "mcp")

View File

@@ -70,12 +70,17 @@ def enabled_builtin_tools(cfg) -> Dict[str, Any]:
_mcp_tools_cache: Dict[str, "ToolSpec"] = {}
_mcp_tools_cache_lock = threading.Lock()
_mcp_config_cache: Dict[str, Any] = {}
# Held while servers are discovered (slow: it starts them); never by readers of the cache.
_mcp_discovery_lock = threading.Lock()
def initialize_mcp_tools(mcps_config: Dict[str, Any], verbose: bool = True) -> Tuple[Dict[str, "ToolSpec"], Dict[str, str]]:
"""
Initialize MCP tools cache at startup.
Discovery starts the servers and can be slow, so it runs outside the cache lock: readers
(``get_cached_mcp_tools``) never wait for it. Discoveries run one at a time.
Args:
mcps_config: MCP server configuration
verbose: Whether to print status messages
@@ -85,14 +90,16 @@ def initialize_mcp_tools(mcps_config: Dict[str, Any], verbose: bool = True) -> T
"""
global _mcp_tools_cache, _mcp_config_cache
with _mcp_tools_cache_lock:
_mcp_config_cache = mcps_config or {}
_mcp_tools_cache, errors = discover_mcp_tools(mcps_config)
with _mcp_discovery_lock:
with _mcp_tools_cache_lock:
_mcp_config_cache = mcps_config or {}
tools, errors = discover_mcp_tools(mcps_config)
with _mcp_tools_cache_lock:
_mcp_tools_cache = tools
if verbose and _mcp_tools_cache:
debug_log(f"MCP tools cache initialized with {len(_mcp_tools_cache)} tools", "mcp")
return _mcp_tools_cache.copy(), errors
if verbose and tools:
debug_log(f"MCP tools cache initialized with {len(tools)} tools", "mcp")
return tools.copy(), errors
def get_cached_mcp_tools() -> Dict[str, "ToolSpec"]:
@@ -103,28 +110,53 @@ def get_cached_mcp_tools() -> Dict[str, "ToolSpec"]:
def refresh_mcp_tools(verbose: bool = True) -> Tuple[Dict[str, "ToolSpec"], Dict[str, str]]:
"""
Refresh MCP tools cache by rediscovering all tools.
Refresh MCP tools cache by rediscovering all tools (outside the cache lock, like
``initialize_mcp_tools``).
Returns:
Tuple of (discovered_tools, errors) where errors maps server name to error message.
"""
global _mcp_tools_cache
with _mcp_tools_cache_lock:
if not _mcp_config_cache:
with _mcp_discovery_lock:
with _mcp_tools_cache_lock:
config = _mcp_config_cache
if not config:
debug_log("No MCP config cached, skipping refresh", "mcp")
return {}, {}
if verbose:
print("🔄 Refreshing MCP tools...", flush=True)
_mcp_tools_cache, errors = discover_mcp_tools(_mcp_config_cache)
tools, errors = discover_mcp_tools(config)
with _mcp_tools_cache_lock:
_mcp_tools_cache = tools
if verbose:
print(f" ✅ Found {len(_mcp_tools_cache)} MCP tools", flush=True)
if verbose:
print(f" ✅ Found {len(tools)} MCP tools", flush=True)
debug_log(f"MCP tools cache refreshed with {len(_mcp_tools_cache)} tools", "mcp")
return _mcp_tools_cache.copy(), errors
debug_log(f"MCP tools cache refreshed with {len(tools)} tools", "mcp")
return tools.copy(), errors
_mcp_background_refresh = threading.Lock()
def refresh_mcp_tools_in_background() -> None:
"""Refresh the MCP tools on a thread of its own and return at once; the cache keeps serving
the previous tools meanwhile. No second one starts while one runs."""
if not _mcp_background_refresh.acquire(blocking=False):
return
def run() -> None:
try:
refresh_mcp_tools(verbose=False)
except Exception as e: # noqa: BLE001 - the previous tools stay
debug_log(f"MCP background refresh failed: {e}", "mcp")
finally:
_mcp_background_refresh.release()
threading.Thread(target=run, name="mcp-refresh", daemon=True).start()
def is_mcp_cache_initialized() -> bool:

View File

@@ -37,6 +37,11 @@ def main() -> int:
print("JARVIS_VOICE_TOKEN is not set", file=sys.stderr)
return 2
# The MCP servers' secrets leave the environment before any child process (MeloTTS) starts;
# only the brain gets them (voice_worker.spec.md, "Tools").
from .brain import take_mcp_env
mcp_env = take_mcp_env()
from .server import VoiceWorker, is_loopback
from .stt_whisper import WhisperTranscriber
from .vad import SileroVad
@@ -59,7 +64,8 @@ def main() -> int:
history = HistoryStore(args.history)
if args.brain:
from .brain import JarvisBrain
brain = JarvisBrain(language=args.tool_language or None, reply_language=args.reply_language or None)
brain = JarvisBrain(language=args.tool_language or None, reply_language=args.reply_language or None,
mcp_env=mcp_env)
async def run() -> None:
worker = VoiceWorker(token, transcriber, vad.stream, tts, history=history, brain=brain)

View File

@@ -152,7 +152,7 @@ MCP_ENV_VAR = "JARVIS_MCP_ENV"
V2_HOST_TOOLS = ("localFiles", "screenshot")
def _take_mcp_env() -> dict:
def take_mcp_env() -> dict:
"""The app's MCP environment, removed from this process's environment so no child process
(MCP servers included) inherits another server's secrets."""
import json
@@ -209,7 +209,8 @@ class JarvisBrain:
tool carry-over follows the person who asked.
"""
def __init__(self, language: Optional[str] = "ko", reply_language: Optional[str] = "Korean"):
def __init__(self, language: Optional[str] = "ko", reply_language: Optional[str] = "Korean",
mcp_env: Optional[dict] = None):
from jarvis.config import load_settings
from jarvis.memory.db import Database
@@ -223,7 +224,7 @@ class JarvisBrain:
self.cfg = dataclasses.replace(
base, tts_engine="melo", stream_browser=False,
disabled_tools=tuple(dict.fromkeys((*base.disabled_tools, *V2_HOST_TOOLS))),
mcps=_with_mcp_env(base.mcps, _take_mcp_env()))
mcps=_with_mcp_env(base.mcps, take_mcp_env() if mcp_env is None else mcp_env))
self.db = Database(self.cfg.db_path, self.cfg.sqlite_vss_path)
# ``language``: the ISO code tools get (e.g. the Wikipedia host); ``reply_language``: replies
# come in it unless the asker explicitly asks for another language (None: the asker's).

View File

@@ -257,10 +257,13 @@ which carry Discord's own time.
registered chat channel asks, so they stay off until M7 brings screen viewing with its own
permissions. The jarvis settings' `mcps` are connected on a thread of their own when the brain
starts, so a slow server does not hold up the voice; their tools are offered once discovered.
Discovery starts the servers, so it runs outside the tool cache's lock: a turn reading the cached
tools never waits for a slow server, and a new conversation refreshes the MCP tools in the
background (the turn uses the tools already cached; one refresh at a time).
The app passes the servers' environment values (secrets) in `JARVIS_MCP_ENV`, JSON `{server:
{NAME: value}}`, never in the settings file; the brain removes that variable from its own
environment, so no child process inherits it, and adds each server's values to that server's
environment only. Each server's outcome is printed without debug logging (category `llm`):
{NAME: value}}`, never in the settings file; the worker removes that variable from its
environment at start, before any child process (MeloTTS) runs, hands it to the brain, and the
brain adds each server's values to that server's environment only. Each server's outcome is printed without debug logging (category `llm`):
`MCP server <name>: <n> tool(s)`, or `Warning: MCP server <name> failed: <reason>`.
- `prepare` tells the brain that `user` is saying a call whose partial transcript is `text` (the app
sends it while the speaker is still talking, `app/src/conversation.spec.md`). The brain runs the