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:
javis-bot
2026-11-13 09:56:17 +09:00
parent d4bd4acfe9
commit 3ef4281180
23 changed files with 717 additions and 39 deletions

View File

@@ -3,7 +3,7 @@ import sys
import json
from dataclasses import dataclass
from pathlib import Path
from typing import Any, Dict, Optional
from typing import Any, Dict, Optional, Tuple
from dotenv import load_dotenv
@@ -272,6 +272,9 @@ class Settings:
# MCP Integration
mcps: Dict[str, Any]
# Built-in tools that are neither offered nor run (v2 feature switches).
disabled_tools: Tuple[str, ...] = ()
def default_config_path() -> Path:
@@ -563,6 +566,8 @@ def get_default_config() -> Dict[str, Any]:
# MCP Integration (external servers Jarvis can use). No defaults.
"mcps": {},
# Built-in tools that are neither offered nor run.
"disabled_tools": [],
}
@@ -766,6 +771,8 @@ def load_settings() -> Settings:
raw_dict = merged.get("dictation_custom_dictionary", [])
dictation_custom_dictionary = list(raw_dict) if isinstance(raw_dict, list) else []
mcps = _ensure_dict(merged.get("mcps"))
_disabled_raw = merged.get("disabled_tools") or []
disabled_tools = tuple(str(t) for t in _disabled_raw) if isinstance(_disabled_raw, list) else ()
whisper_min_confidence = float(merged.get("whisper_min_confidence", 0.4))
whisper_no_speech_threshold = float(merged.get("whisper_no_speech_threshold", 0.5))
whisper_min_audio_duration = float(merged.get("whisper_min_audio_duration", 0.3))
@@ -913,4 +920,5 @@ def load_settings() -> Settings:
# MCP Integration
mcps=mcps,
disabled_tools=disabled_tools,
)

View File

@@ -17,7 +17,7 @@ from ..system_prompt import (
reply_language_directive,
tool_honesty_reminder,
)
from ..tools.registry import run_tool_with_retries, generate_tools_description, generate_tools_json_schema, BUILTIN_TOOLS
from ..tools.registry import run_tool_with_retries, generate_tools_description, generate_tools_json_schema, BUILTIN_TOOLS, enabled_builtin_tools
from ..tools.builtin.stop import STOP_SIGNAL
from ..debug import debug_log
from ..llm import chat_with_messages, extract_text_from_response, ToolsNotSupportedError
@@ -1051,18 +1051,10 @@ def _recent_messages(cfg, dialogue_memory) -> list:
return dialogue_memory.get_recent_messages()
# The on-screen browser tools work only in screen-share mode (cfg.stream_browser); without it they
# only refuse, and offered anyway the router picked them for unrelated asks (field run 2026-11-12,
# v2: "피곤하다" routed to browseAndPlay).
_SCREEN_SHARE_TOOLS = ("controlBrowser", "browseAndPlay", "setBroadcast")
def _offered_builtins(cfg, chat_available: bool) -> dict:
"""The built-in tools this turn can offer: chatChannels only with a chat backend
(chat_channels.spec.md), the screen-share tools only in screen-share mode."""
stream = getattr(cfg, "stream_browser", True)
return {k: v for k, v in BUILTIN_TOOLS.items()
if (k != "chatChannels" or chat_available) and (stream or k not in _SCREEN_SHARE_TOOLS)}
"""The built-in tools this turn can offer: the enabled ones (``enabled_builtin_tools``), and
chatChannels only with a chat backend (chat_channels.spec.md)."""
return {k: v for k, v in enabled_builtin_tools(cfg).items() if k != "chatChannels" or chat_available}
def _route_tools(cfg, redacted: str, builtin_tools: dict, mcp_tools: dict, recent_messages: list):

View File

@@ -306,7 +306,7 @@ Turn 4: LLM → {content: "Here's a comprehensive comparison of the iPhone 15 mo
- `memory_digest_enabled` (default `null` = auto-on for SMALL models ≤7B, off for LARGE) distils the combined diary + graph dump into a short relevance-filtered note via a cheap LLM pass before injecting into the system prompt. See **Memory Digest for Small Models** below.
- `tool_result_digest_enabled` (default `null` = auto-on for SMALL models ≤7B) distils raw tool-result payloads (especially webSearch UNTRUSTED WEB EXTRACT blocks and fetch_web_page responses) into a short attributed fact note before appending as a tool-role message. Auto-on for small models mitigates large payloads (fetch_web_page truncates at 50,000 chars) blowing the 8192 num_ctx window. Set to `true` to force on, `false` to force off. See **Tool-Result Digest for Small Models** below.
- Tools and MCP:
- All builtin tools are always available; MCP servers added from `cfg.mcps`.
- Every builtin tool is available except those in `cfg.disabled_tools` (default none) and, outside screen-share mode (`cfg.stream_browser`), the screen-share tools (`controlBrowser`, `browseAndPlay`, `setBroadcast`). `enabled_builtin_tools(cfg)` (`src/jarvis/tools/registry.py`) is the one list the router, the planner's catalogue, `toolSearchTool` and the executor use: a tool outside it is neither offered nor run, also when the model names it (the executor answers that the tool is turned off). MCP servers are added from `cfg.mcps`.
- Agentic loop:
- `agentic_max_turns` maximum turns in the agentic loop (default 8)
- `tool_search_max_calls` (default 3) caps `toolSearchTool` invocations per reply. Extra calls return a tool-error nudging the model to decide with what is already available.

View File

@@ -76,7 +76,7 @@ class ToolSearchTool(Tool):
cfg = context.cfg
# Local imports to avoid circulars at module load time.
from ..registry import BUILTIN_TOOLS, get_cached_mcp_tools
from ..registry import BUILTIN_TOOLS, enabled_builtin_tools, get_cached_mcp_tools
try:
strategy = ToolSelectionStrategy(getattr(cfg, "tool_selection_strategy", "llm"))
@@ -92,7 +92,7 @@ class ToolSearchTool(Tool):
try:
selected = select_tools(
query=query,
builtin_tools=BUILTIN_TOOLS,
builtin_tools=enabled_builtin_tools(cfg),
mcp_tools=mcp_tools,
strategy=strategy,
llm_base_url=getattr(cfg, "ollama_base_url", ""),

View File

@@ -16,7 +16,7 @@ Before each reply, `select_tools` runs once outside the loop and narrows the too
allow-list = <router's picks> + stop + toolSearchTool
```
When the model invokes `toolSearchTool(query=...)`, the tool re-runs the same routing logic (`select_tools` from `src/jarvis/tools/selection.py`) against the new query, and the returned tool names are merged into the loop's allow-list for subsequent turns. `stop` and `toolSearchTool` itself always remain in the allow-list.
When the model invokes `toolSearchTool(query=...)`, the tool re-runs the same routing logic (`select_tools` from `src/jarvis/tools/selection.py`) against the new query over the enabled built-in tools (`enabled_builtin_tools(cfg)`: none in `cfg.disabled_tools`, no screen-share tools outside screen-share mode; reply.spec.md, "Tools and MCP") and the MCP tools, and the returned tool names are merged into the loop's allow-list for subsequent turns. `stop` and `toolSearchTool` itself always remain in the allow-list.
### Contract

View File

@@ -49,6 +49,23 @@ BUILTIN_TOOLS = {
"chatChannels": ChatChannelsTool(),
}
# The on-screen browser tools work only in screen-share mode (cfg.stream_browser); without it they
# only refuse, and offered anyway the router picked them for unrelated asks (field run 2026-11-12,
# v2: "피곤하다" routed to browseAndPlay).
_SCREEN_SHARE_TOOLS = ("controlBrowser", "browseAndPlay", "setBroadcast")
def enabled_builtin_tools(cfg) -> Dict[str, Any]:
"""The built-in tools this configuration allows: none in ``cfg.disabled_tools``, and the
screen-share tools only in screen-share mode. The router, toolSearchTool and the executor all
use this, so a turned-off tool is neither offered nor run."""
disabled = getattr(cfg, "disabled_tools", ())
disabled = set(disabled) if isinstance(disabled, (list, tuple, set, frozenset)) else set()
stream = getattr(cfg, "stream_browser", True)
return {k: v for k, v in BUILTIN_TOOLS.items()
if k not in disabled and (stream or k not in _SCREEN_SHARE_TOOLS)}
# Global MCP tools cache
_mcp_tools_cache: Dict[str, "ToolSpec"] = {}
_mcp_tools_cache_lock = threading.Lock()
@@ -356,6 +373,10 @@ def run_tool_with_retries(
pass
# Check builtin tools first
if name in BUILTIN_TOOLS and name not in enabled_builtin_tools(cfg):
debug_log(f"turned-off tool requested: {name}", "tools")
return ToolExecutionResult(success=False, reply_text=None,
error_message=f"The {name} tool is turned off.")
if name in BUILTIN_TOOLS:
tool = BUILTIN_TOOLS[name]
return tool.execute(

View File

@@ -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

View File

@@ -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

View File

@@ -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