feat(app): features screen with tool switches and MCP servers; v2 drops host file and screen tools
- Settings `features` (weather, webSearch, meals) and `mcpServers` (name, command, args, env names, enabled), edited on the new 기능 screen. The tools of a feature that is off go into the brain's `disabled_tools`; only enabled MCP servers go into its `mcps`. - MCP environment values (API keys) live only in the encrypted secrets (`mcp:<server>:<NAME>`), shown as stored or not, masked in logs, removed with their server, and reach the worker only in `JARVIS_MCP_ENV`, which the brain takes out of its environment before giving each server its own. - `enabled_builtin_tools(cfg)` is the one list the router, toolSearchTool and the executor use, so a turned-off tool is neither offered nor run, also when the model names it. - The v2 brain never offers v1's `localFiles` (home folder read/write/delete) and `screenshot`: anyone in the voice or chat channels could ask for them. Screen viewing comes in M7. - The brain connects MCP servers on its own thread and logs each outcome without debug logging. - Stored secrets are masked in the log hub as soon as the data folder is found. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -12,7 +12,7 @@ import time
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional, Protocol
|
||||
|
||||
from .log import debug_log
|
||||
from .log import debug_log, notice
|
||||
from jarvis.memory.history import HistoryContext, Scope
|
||||
|
||||
|
||||
@@ -143,6 +143,64 @@ class _Prepared:
|
||||
tools: Optional[list] = None # the intent judge's pick; None: none made
|
||||
|
||||
|
||||
# The app passes the MCP servers' environment values (API keys, kept in its encrypted secrets)
|
||||
# here, as JSON ``{server: {NAME: value}}``, never in the config file.
|
||||
MCP_ENV_VAR = "JARVIS_MCP_ENV"
|
||||
# v1's host tools: the PC owner's home folder (read, write, delete) and screen. In v2 anyone in the
|
||||
# voice channel or a registered chat channel asks, so they are never offered (M7 brings screen
|
||||
# viewing with its own permissions).
|
||||
V2_HOST_TOOLS = ("localFiles", "screenshot")
|
||||
|
||||
|
||||
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
|
||||
import os
|
||||
|
||||
raw = os.environ.pop(MCP_ENV_VAR, None)
|
||||
if not raw:
|
||||
return {}
|
||||
try:
|
||||
env = json.loads(raw)
|
||||
except ValueError:
|
||||
notice("Warning: the MCP environment from the app is not JSON; ignored", "llm")
|
||||
return {}
|
||||
if not isinstance(env, dict):
|
||||
return {}
|
||||
return {str(k): {str(n): str(v) for n, v in vars_.items()} for k, vars_ in env.items()
|
||||
if isinstance(vars_, dict)}
|
||||
|
||||
|
||||
def _with_mcp_env(mcps: dict, env: dict) -> dict:
|
||||
out = {}
|
||||
for name, server in mcps.items():
|
||||
server = dict(server)
|
||||
if env.get(name):
|
||||
server["env"] = {**(server.get("env") or {}), **env[name]}
|
||||
out[name] = server
|
||||
return out
|
||||
|
||||
|
||||
def _connect_mcp(mcps: dict) -> None:
|
||||
"""Discover the MCP servers' tools into the registry's cache (the reply engine offers them
|
||||
from there). Runs on its own thread so a slow server does not hold up the voice."""
|
||||
from jarvis.tools.registry import initialize_mcp_tools
|
||||
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
tools, errors = initialize_mcp_tools(mcps, verbose=False)
|
||||
except Exception as e: # noqa: BLE001 - the brain answers without MCP tools
|
||||
notice(f"Warning: MCP servers could not be connected: {type(e).__name__}", "llm")
|
||||
return
|
||||
for name in mcps:
|
||||
if name in errors:
|
||||
notice(f"Warning: MCP server {name} failed: {errors[name]}", "llm")
|
||||
else:
|
||||
notice(f"MCP server {name}: {sum(1 for t in tools if t.startswith(f'{name}__'))} tool(s)", "llm")
|
||||
debug_log(f"mcp ready: {len(tools)} tool(s) ms={(time.perf_counter() - t0) * 1000:.0f}", "llm")
|
||||
|
||||
|
||||
class JarvisBrain:
|
||||
"""The existing jarvis reply engine with the user's history context.
|
||||
|
||||
@@ -160,7 +218,12 @@ class JarvisBrain:
|
||||
# not spoken; the brain answers in ``reply_language`` (an OUTPUT_LANGUAGE lock still wins).
|
||||
# stream_browser: v1's screen-share browser (controlBrowser, browseAndPlay, setBroadcast and
|
||||
# browser-first web search) needs v1's Node bot; v2 has no on-screen browser until M6.
|
||||
self.cfg = dataclasses.replace(load_settings(), tts_engine="melo", stream_browser=False)
|
||||
# disabled_tools: the app's feature switches plus v1's host tools (V2_HOST_TOOLS).
|
||||
base = load_settings()
|
||||
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()))
|
||||
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).
|
||||
@@ -170,6 +233,9 @@ class JarvisBrain:
|
||||
self._prepared: dict[str, _Prepared] = {}
|
||||
self._lock = threading.Lock()
|
||||
debug_log(f"brain ready: llm={self.cfg.ollama_base_url} model={self.cfg.ollama_chat_model}", "llm")
|
||||
if self.cfg.mcps:
|
||||
threading.Thread(target=_connect_mcp, args=(self.cfg.mcps,), name="mcp-connect",
|
||||
daemon=True).start()
|
||||
|
||||
def _memory(self, user: str):
|
||||
from jarvis.memory.conversation import DialogueMemory
|
||||
|
||||
@@ -15,3 +15,12 @@ def debug_log(message: str, category: str = "debug") -> None:
|
||||
print(f"[{category:^10}] {message}", file=sys.__stderr__, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def notice(message: str, category: str = "debug") -> None:
|
||||
"""A line the user needs also without debug logging (the app's log screen shows every worker
|
||||
line; a ``Warning`` in it marks it as a warning there)."""
|
||||
try:
|
||||
print(f"[{category:^10}] {message}", file=sys.__stderr__, flush=True)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
@@ -250,6 +250,18 @@ which carry Discord's own time.
|
||||
router judges whether the turn needs tools and which, and the planner runs only when it does;
|
||||
`planner.spec.md`, "Intent judge (v2)"). v1's screen-share browser (`stream_browser`) is off: it
|
||||
needs v1's Node bot (M6 brings the v2 one), so its tools are not offered.
|
||||
- Tools: the brain offers and runs no built-in tool in the jarvis settings' `disabled_tools` (the
|
||||
app writes the tools of the features turned off on its 기능 screen, `app/src/admin.spec.md`,
|
||||
"Features and MCP servers"), and never v1's host tools `localFiles` (the PC owner's home folder:
|
||||
read, write, delete) and `screenshot` (the PC's screen): in v2 anyone in the voice channel or a
|
||||
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.
|
||||
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`):
|
||||
`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
|
||||
intent judge's tool pick for it on its own thread, with the asker's dialogue memory and the tool
|
||||
|
||||
Reference in New Issue
Block a user