From 8b3905f1c294791ed5961a27b3b19636069e135f Mon Sep 17 00:00:00 2001 From: javis-bot Date: Fri, 13 Nov 2026 10:07:52 +0900 Subject: [PATCH] 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 --- app/src/admin.spec.md | 10 +++- app/src/logs.rs | 31 +++++++++- src/jarvis/reply/engine.py | 9 +-- src/jarvis/tools/registry.py | 62 ++++++++++++++----- src/voice_worker/__main__.py | 8 ++- src/voice_worker/brain.py | 7 ++- src/voice_worker/voice_worker.spec.md | 9 ++- tests/test_v2_features.py | 86 +++++++++++++++++++++++++++ 8 files changed, 191 insertions(+), 31 deletions(-) diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index c3495cb..ddbaf64 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -110,8 +110,11 @@ STT, LLM and TTS lines go to `stt`, `llm`, `tts` by their worker category), `bro - `export_zip(from, to, out)`: the log files of those days in a zip, at most 10 MB (Discord's file limit): when larger, the oldest lines by the time they were logged, across every tab's file, are left out and a note says how many. -- Every copy and export runs through `redact`: each stored secret's value, and anything shaped like - a Discord bot token (also with sentence dots around it), becomes `[비밀값]`. +- Every line runs through `redact` before it is kept or written to a file, and every copy and + export again: each stored secret's value, and anything shaped like a Discord bot token (also with + sentence dots around it), becomes `[비밀값]`. So a secret replaced or removed later (the hub then + no longer knows the old value) never shows on the screen, in a copy, a file or an export, also + after a restart. - Errors the voice worker reports to the app (`error` messages: code and request id) are always logged, debug logging or not, so the log screen and the error report show them. @@ -362,7 +365,8 @@ the TTS speed reaching the worker's arguments; features and MCP servers (read an the key, the feature tools named as the brain names them, only enabled servers in the brain's settings without values, stored values passed for enabled servers only, values of removed servers and names deleted, a value refused for an unsaved server, kept out of the settings file and masked -in logs, also by a new app on the same folder); chat channel names and topics (only new or edited +in logs, also by a new app on the same folder, and a value replaced or removed later still masked +in lines written before); chat channel names and topics (only new or edited syncing channels sent, the topic limit refused before saving, Discord's form of the name written back, a missing permission failing with the reason and the text kept, a rate-limited edit pending and retried once with the latest text, a new channel never clearing Discord (also on its retry), a diff --git a/app/src/logs.rs b/app/src/logs.rs index 5d98b6e..d15e4d0 100644 --- a/app/src/logs.rs +++ b/app/src/logs.rs @@ -91,7 +91,7 @@ impl LogHub { self.cleanup(Local::now().date_naive()); } - /// The stored secrets' values, masked in every copy and export. + /// The stored secrets' values, masked in every line from now on (and again in copies and exports). pub fn set_secrets(&self, values: Vec) { self.state.lock().unwrap().secrets = values; } @@ -118,7 +118,10 @@ impl LogHub { fn push_at(&self, at: DateTime, level: Level, tab: &str, text: &str) { let mut s = self.state.lock().unwrap(); - let line = LogLine { seq: s.next_seq, at_ms: at.timestamp_millis(), level, tab: tab.into(), text: text.into() }; + // Masked before it is kept or written, so a secret replaced or removed later (the hub then + // no longer knows the old value) never shows on the screen, in a copy, a file or an export. + let text = redact(text, &s.secrets); + let line = LogLine { seq: s.next_seq, at_ms: at.timestamp_millis(), level, tab: tab.into(), text }; s.next_seq += 1; if let Some(dir) = s.dir.clone() { let day = at.date_naive(); @@ -479,6 +482,30 @@ mod tests { assert!(!all.contains("late on the first") && all.contains("early on the second")); } + #[test] + fn a_secret_is_masked_when_the_line_is_written_so_removing_or_replacing_it_later_shows_nothing() { + let dir = temp_dir("logwrite"); + let hub = LogHub::new(Some(&dir)); + hub.set_secrets(vec!["old-api-key-1".into()]); + hub.push_at(Local::now(), Level::Error, "llm", "server refused old-api-key-1"); + // The key is replaced (or its server removed): the hub no longer knows the old value. + hub.set_secrets(vec!["new-api-key-2".into()]); + let shown: String = hub.query(None, Level::Debug, None, None, 100).iter().map(|l| l.text.clone()).collect(); + assert!(shown.contains("server refused [비밀값]") && !shown.contains("old-api-key-1"), "{shown}"); + assert!(!hub.recent_error_report("0.1.0").unwrap().contains("old-api-key-1")); + // After a restart a new hub reads the files: the value was never written. + // Today's file (a new hub removes files older than the retention). + let today = Local::now().date_naive(); + let file = std::fs::read_to_string(dir.join(format!("llm-{today}.log"))).unwrap(); + assert!(!file.contains("old-api-key-1"), "{file}"); + let out = dir.join("after.zip"); + LogHub::new(Some(&dir)).export_zip(today, today, &out).unwrap(); + let mut z = zip::ZipArchive::new(std::fs::File::open(&out).unwrap()).unwrap(); + let mut text = String::new(); + std::io::Read::read_to_string(&mut z.by_name(&format!("llm-{today}.log")).unwrap(), &mut text).unwrap(); + assert!(!text.contains("old-api-key-1")); + } + #[test] fn the_zip_stays_under_the_limit_by_leaving_out_the_oldest_lines() { let dir = temp_dir("logzip"); diff --git a/src/jarvis/reply/engine.py b/src/jarvis/reply/engine.py index 1da788d..ed48974 100644 --- a/src/jarvis/reply/engine.py +++ b/src/jarvis/reply/engine.py @@ -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") diff --git a/src/jarvis/tools/registry.py b/src/jarvis/tools/registry.py index a6e8fe1..0328cc6 100644 --- a/src/jarvis/tools/registry.py +++ b/src/jarvis/tools/registry.py @@ -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: diff --git a/src/voice_worker/__main__.py b/src/voice_worker/__main__.py index 4591955..e343e96 100644 --- a/src/voice_worker/__main__.py +++ b/src/voice_worker/__main__.py @@ -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) diff --git a/src/voice_worker/brain.py b/src/voice_worker/brain.py index c4bdc14..ff4a9d3 100644 --- a/src/voice_worker/brain.py +++ b/src/voice_worker/brain.py @@ -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). diff --git a/src/voice_worker/voice_worker.spec.md b/src/voice_worker/voice_worker.spec.md index 22b1156..c473f13 100644 --- a/src/voice_worker/voice_worker.spec.md +++ b/src/voice_worker/voice_worker.spec.md @@ -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 : tool(s)`, or `Warning: MCP server failed: `. - `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 diff --git a/tests/test_v2_features.py b/tests/test_v2_features.py index 1aaabc1..aa1d5eb 100644 --- a/tests/test_v2_features.py +++ b/tests/test_v2_features.py @@ -130,3 +130,89 @@ def test_the_v2_brain_offers_no_host_files_or_screen_and_connects_mcp_with_the_a assert "s3cret" not in err # The config file the app wrote never holds the secret. assert "s3cret" not in (tmp_path / "config.json").read_text() + + +@pytest.mark.unit +def test_a_slow_mcp_server_never_holds_up_a_turn_reading_the_tools(monkeypatch): + """Discovery (which starts the servers) runs outside the cache lock: a turn reading the cached + tools, and a new conversation's refresh, never wait for a slow server.""" + import threading + + from jarvis.tools import registry + + release = threading.Event() + calls = [] + + def slow_discover(cfg): + calls.append(cfg) + release.wait(10) + return {}, {} + + monkeypatch.setattr(registry, "discover_mcp_tools", slow_discover) + monkeypatch.setattr(registry, "_mcp_tools_cache", {}) + monkeypatch.setattr(registry, "_mcp_config_cache", {}) + t = threading.Thread(target=registry.initialize_mcp_tools, args=({"slow": {"command": "x"}}, False)) + t.start() + try: + deadline = time.monotonic() + 5 + while not calls and time.monotonic() < deadline: + time.sleep(0.01) + t0 = time.monotonic() + assert registry.get_cached_mcp_tools() == {} + assert registry.is_mcp_cache_initialized() + # A new conversation's refresh starts in the background and returns at once. + registry.refresh_mcp_tools_in_background() + assert time.monotonic() - t0 < 1 + finally: + release.set() + t.join(10) + # Let the background refresh end while the fake discovery is still in place. + assert registry._mcp_background_refresh.acquire(timeout=10) + registry._mcp_background_refresh.release() + assert len(calls) == 2 # the start's discovery and the refresh's + + +@pytest.mark.unit +def test_the_tts_child_never_inherits_the_mcp_secrets(monkeypatch): + """The worker takes the app's MCP environment before it starts any child process (MeloTTS) and + hands it to the brain.""" + import os + + import voice_worker.__main__ as main_mod + from voice_worker import brain as brain_mod + + seen = {} + + class Stop(Exception): + pass + + class FakeTranscriber: + def __init__(self, *a): + pass + + def warm_up(self): + pass + + class FakeMelo: + def __init__(self, *a): + seen["tts_env"] = brain_mod.MCP_ENV_VAR in os.environ + + class FakeBrain: + def __init__(self, **kw): + seen["brain_env"] = kw.get("mcp_env") + raise Stop + + import voice_worker.stt_whisper as stt + import voice_worker.tts_melo as melo + import voice_worker.vad as vad + monkeypatch.setattr(stt, "WhisperTranscriber", FakeTranscriber) + monkeypatch.setattr(vad, "SileroVad", lambda: None) + monkeypatch.setattr(melo, "MeloEngine", FakeMelo) + monkeypatch.setattr(brain_mod, "JarvisBrain", FakeBrain) + monkeypatch.setenv("JARVIS_VOICE_TOKEN", "t") + monkeypatch.setenv(brain_mod.MCP_ENV_VAR, json.dumps({"fake": {"FAKE_KEY": "s3cret"}})) + monkeypatch.setattr(sys, "argv", ["voice_worker", "--melo-python", "py", "--history", ":memory:", "--brain"]) + with pytest.raises(Stop): + main_mod.main() + assert seen["tts_env"] is False + assert seen["brain_env"] == {"fake": {"FAKE_KEY": "s3cret"}}