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:
@@ -38,9 +38,9 @@ that is not absolute, or is a file, is refused with a message.
|
||||
`config/settings.json` keeps the format of `discord_core.spec.md` and `conversation.spec.md`.
|
||||
|
||||
- `fields()` describes every key the screens edit: its dotted path (`call.mode`), screen
|
||||
(`bot`, `channels`, `chat`, `memory`, `model`), kind (bool, integer with a range, number with a
|
||||
(`bot`, `channels`, `chat`, `memory`, `model`, `features`), kind (bool, integer with a range, number with a
|
||||
range, text, text list, choice with its values, Discord ID, Discord ID list, ID to number map,
|
||||
chat channel list, free object), its default and a Korean label. The screens are built from this
|
||||
chat channel list, MCP server list, free object), its default and a Korean label. The screens are built from this
|
||||
list, so a key is added in one place.
|
||||
- `view(dir)` returns every field's current value: the file's value, or the default when the file
|
||||
does not set it. A file that does not parse is reported, not overwritten.
|
||||
@@ -53,12 +53,39 @@ that is not absolute, or is a file, is refused with a message.
|
||||
`chat`, `others`, `off`, `since_days`, `recent_minutes`, `recent_records`, `matches`,
|
||||
`budget_tokens`), sent in the worker `hello` as `memory`. Default `{}` (the worker's defaults).
|
||||
|
||||
## Features and MCP servers (`app/src/features.rs`)
|
||||
|
||||
`docs/v2/desktop-app.md`, "기능". The 기능 screen turns the brain's built-in features on and off and
|
||||
manages the MCP servers it connects.
|
||||
|
||||
- `features` (new section): `weather` (`getWeather`), `webSearch` (`webSearch`, `fetchWebPage`) and
|
||||
`meals` (`logMeal`, `fetchMeals`, `deleteMeal`), each on by default. The tools of a feature that
|
||||
is off go into the brain's `disabled_tools`: they are neither offered nor run
|
||||
(`voice_worker.spec.md`, "Tools"). The other features of the 기능 screen (browser control, PC
|
||||
control, screen viewing, background collection) come with their milestones (M6, M7).
|
||||
- `mcpServers` (new list): each `{name, command, args, env, enabled}`. `name` is 1-32 letters,
|
||||
digits, `-` or `_` without `__` (the brain names a server's tools `<name>__<tool>`), not listed
|
||||
twice; `command` is not empty; `args` a list of strings; `env` the names of the environment
|
||||
variables the server gets (each a letter or `_`, then letters, digits or `_`; not listed twice);
|
||||
`enabled` on by default. Only enabled servers reach the brain's `mcps` (stdio).
|
||||
- **Environment values are secrets** (API keys): never in the settings file or `config/brain.json`.
|
||||
Each is stored in the secrets as `mcp:<server>:<NAME>` (`mcp_env_set`, only for a server and name
|
||||
already saved; an empty value removes it), shown on the screen only as stored or not, and masked
|
||||
in logs like every secret. Saving `mcpServers` removes the values of servers and names no longer
|
||||
listed. On start the app passes the enabled servers' stored values to the worker in its
|
||||
environment, `JARVIS_MCP_ENV` (`{server: {NAME: value}}`); the brain takes that variable out of
|
||||
its own environment and gives each server only its own values.
|
||||
- Each server's outcome (its tool count, or why it failed) is a worker line in the LLM log tab,
|
||||
also without debug logging. MCP servers are programs the PC runs; the screen says to add only
|
||||
trusted ones.
|
||||
|
||||
## Secrets (`app/src/secrets.rs`)
|
||||
|
||||
`config/secrets.dat` holds a JSON object of named secrets (`discordToken`). On Windows the bytes are
|
||||
`config/secrets.dat` holds a JSON object of named secrets (`discordToken`, the MCP servers'
|
||||
environment values `mcp:<server>:<NAME>`). On Windows the bytes are
|
||||
encrypted with DPAPI for the current Windows user (`CryptProtectData`, no prompt), so the file is
|
||||
useless copied to another account or PC. Elsewhere (development only) the file is plain JSON with
|
||||
owner-only permissions (0600). Writes are atomic. `get`, `set`, `remove`; `masked(value)` shows only
|
||||
owner-only permissions (0600). Writes are atomic. `get`, `set`, `remove`, `names`; `masked(value)` shows only
|
||||
the last 4 characters for the screens (`••••abcd`).
|
||||
|
||||
The app's token comes from the secrets (`discordToken`), else from `JARVIS_DISCORD_TOKEN` (tests,
|
||||
@@ -206,7 +233,7 @@ start it first, so nothing answers before the brain can, and stop it last.
|
||||
(default 8080) on the model screen; `llm.url` (default none).
|
||||
- **The brain's settings**: on every start the app writes `config/brain.json` (it owns the file):
|
||||
`ollama_base_url` the LLM's `/v1`, `ollama_chat_model` the listed id, `db_path`
|
||||
`memory/jarvis.db`; the worker gets it as `JARVIS_CONFIG_PATH`. Loading it writes nothing to the
|
||||
`memory/jarvis.db`, `disabled_tools` and `mcps` (above, "Features and MCP servers"); the worker gets it as `JARVIS_CONFIG_PATH`. Loading it writes nothing to the
|
||||
home folder.
|
||||
|
||||
## Chat channel names and topics (`app/src/channel_sync.rs`)
|
||||
@@ -251,12 +278,14 @@ back as Korean messages for the screen. The Tauri shell passes the screens' `inv
|
||||
| `settings_fields` / `settings_view` / `settings_apply` `{changes}` | the settings editor above; `restartNeeded` when the services run; `sync` with the chat channels sent to Discord (below) |
|
||||
| `service_start` / `service_stop` / `service_restart` / `dashboard` | the controller and its snapshot; start and restart run in the background, stop also cancels a start |
|
||||
| `discord_channel_info` `{id}` / `channel_sync_status` | a channel's Discord name and topic / each synced chat channel's last result (above) |
|
||||
| `mcp_env_status` / `mcp_env_set` `{server, name, value}` | which MCP environment values are stored (`{server: {NAME: bool}}`, never the values) / store one (an empty value removes it); only for a saved server and name |
|
||||
| `install_status` / `install_start` / `install_cancel` | the install steps and their state, bytes and last line / run what is not done in the background / stop it |
|
||||
| `logs_query` `{tab, level, find, after, limit}` / `logs_error_report` / `logs_export` `{from, to}` | the log hub; the zip goes to `logs/` and its path comes back |
|
||||
|
||||
The invite link asks for: view channels, send messages, read history, add reactions, manage
|
||||
messages, manage channels, connect, speak, voice activity, and the slash command scope; never
|
||||
administrator. The log hub writes to the data folder's `logs/` as soon as a folder is chosen
|
||||
administrator. Stored secrets are masked in the log hub from the moment the app finds or chooses
|
||||
its data folder, and again after each one is saved. The log hub writes to the data folder's `logs/` as soon as a folder is chosen
|
||||
(`folder_choose` points it there; before that, memory only).
|
||||
|
||||
## Screens (`app/ui/`)
|
||||
@@ -274,10 +303,13 @@ Plain HTML, CSS and an ES module, no build step, dark theme after `DESIGN.md`. A
|
||||
Strata's last line, and stop in the header; the header with start, restart and stop is rebuilt
|
||||
only when the state changes, so a click is never lost to the refresh. Every screen change starts
|
||||
a new generation: an answer that arrives after the user moved to another screen is dropped.
|
||||
- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델): built from `settings_fields`; only
|
||||
- **Settings screens** (봇, 채널·호출, 채팅 채널, 대화 기억, 모델, 기능): built from `settings_fields`; only
|
||||
changed fields are sent; the server and voice channel are pickers (choosing another server clears
|
||||
the voice channel and lists only that server's channels); the chat channels are a table
|
||||
with their switches; the bot screen also changes the token.
|
||||
with their switches; the bot screen also changes the token; the 기능 screen has the feature
|
||||
switches and one card per MCP server (name, command, arguments and environment variable names
|
||||
one per line, on/off, delete), and for a saved server a password box per environment variable
|
||||
that stores its value on its own.
|
||||
- **Logs**: tab, level and text filters, pause, live follow (lines after the last seen), "최근 오류
|
||||
복사" (to the clipboard; over 2,000 characters it suggests the zip), and the zip export by days.
|
||||
|
||||
@@ -326,7 +358,11 @@ a stop right after a background start running no launch at all, and the next sta
|
||||
closing the app (the controller's shutdown after a failed stop: clean-up failing keeps it failed,
|
||||
succeeding stops it; an install in progress cancelled and waited for); command output that is not
|
||||
UTF-8 read on to the end; the window data folder (data folder, or a scratch folder removed later);
|
||||
the TTS speed reaching the worker's arguments; chat channel names and topics (only new or edited
|
||||
the TTS speed reaching the worker's arguments; features and MCP servers (read and refused with
|
||||
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
|
||||
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
|
||||
|
||||
@@ -46,6 +46,10 @@ impl AdminApi {
|
||||
/// `location_file`: where the data folder is remembered; `hub`: the app's log hub.
|
||||
pub fn new(location_file: &Path, hub: Arc<LogHub>) -> Self {
|
||||
let dir = DataDir::locate(location_file);
|
||||
// Stored secrets are masked in every copy and export from the start, not only once saved again.
|
||||
if let Some(d) = &dir {
|
||||
hub.set_secrets(Secrets::new(&d.secrets_file()).values());
|
||||
}
|
||||
Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None),
|
||||
syncer: Mutex::new(None), hub }
|
||||
}
|
||||
@@ -171,6 +175,7 @@ impl AdminApi {
|
||||
let dir = DataDir::choose(&path, &self.location_file).map_err(|e| e.to_string())?;
|
||||
// Log files go to the chosen folder from now on, not only after a restart.
|
||||
self.hub.set_dir(&dir.logs());
|
||||
self.hub.set_secrets(Secrets::new(&dir.secrets_file()).values());
|
||||
*self.dir.lock().unwrap() = Some(dir);
|
||||
*self.controller.lock().unwrap() = None;
|
||||
*self.installer.lock().unwrap() = None;
|
||||
@@ -236,6 +241,12 @@ impl AdminApi {
|
||||
None => vec![],
|
||||
};
|
||||
crate::settings_edit::apply(&file, &changes).map_err(|e| e.0)?;
|
||||
if changes.contains_key("mcpServers") {
|
||||
// Values of removed servers and names go with them.
|
||||
let servers = crate::settings::load_settings(&file).map_err(|e| e.0)?.mcp_servers;
|
||||
crate::features::prune(&self.secrets()?, &servers).map_err(|e| e.to_string())?;
|
||||
self.hub.set_secrets(self.secrets()?.values());
|
||||
}
|
||||
let mut sync = vec![];
|
||||
if chats.is_some() {
|
||||
let new = crate::settings::load_settings(&file).map_err(|e| e.0)?.chat_channels;
|
||||
@@ -251,6 +262,25 @@ impl AdminApi {
|
||||
Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running,
|
||||
"sync": sync}))
|
||||
}
|
||||
"mcp_env_status" => {
|
||||
let servers = crate::settings::load_settings(&self.dir()?.settings_file()).map_err(|e| e.0)?.mcp_servers;
|
||||
crate::features::env_status(&self.secrets()?, &servers).map_err(|e| e.to_string())
|
||||
}
|
||||
"mcp_env_set" => {
|
||||
let (server, name) = (arg_str(&args, "server")?, arg_str(&args, "name")?);
|
||||
let value = arg_str(&args, "value")?.trim();
|
||||
let servers = crate::settings::load_settings(&self.dir()?.settings_file()).map_err(|e| e.0)?.mcp_servers;
|
||||
if !servers.iter().any(|s| s.name == server && s.env.iter().any(|v| v == name)) {
|
||||
return Err("저장된 MCP 서버의 환경 변수가 아닙니다. 서버 목록을 먼저 저장해 주세요".into());
|
||||
}
|
||||
let secrets = self.secrets()?;
|
||||
let key = crate::features::secret_name(server, name);
|
||||
if value.is_empty() { secrets.remove(&key) } else { secrets.set(&key, value) }.map_err(|e| e.to_string())?;
|
||||
self.hub.set_secrets(secrets.values());
|
||||
crate::info_log!("admin", "mcp value {} for {server}", if value.is_empty() { "removed" } else { "saved" });
|
||||
Ok(json!({"set": !value.is_empty(),
|
||||
"restartNeeded": self.controller()?.state() == crate::control::State::Running}))
|
||||
}
|
||||
"channel_sync_status" => Ok(Value::Object(self.syncer()?.status().into_iter()
|
||||
.map(|(id, s)| (id.to_string(), json!(s))).collect())),
|
||||
"discord_channel_info" => {
|
||||
@@ -362,6 +392,36 @@ mod tests {
|
||||
assert!(a.call("nope", json!({})).await.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_values_are_stored_encrypted_shown_only_as_set_masked_in_logs_and_go_with_their_server() {
|
||||
let (a, base) = api("api-mcp");
|
||||
let data = base.join("d");
|
||||
a.call("folder_choose", json!({"path": data.to_string_lossy()})).await.unwrap();
|
||||
let server = json!([{"name": "brave", "command": "npx", "env": ["BRAVE_API_KEY"]}]);
|
||||
// A value for a server that is not saved yet is refused.
|
||||
assert!(a.call("mcp_env_set", json!({"server": "brave", "name": "BRAVE_API_KEY", "value": "k"})).await.is_err());
|
||||
a.call("settings_apply", json!({"changes": {"mcpServers": server}})).await.unwrap();
|
||||
a.call("mcp_env_set", json!({"server": "brave", "name": "BRAVE_API_KEY", "value": "brave-key-123"})).await.unwrap();
|
||||
assert_eq!(a.call("mcp_env_status", json!({})).await.unwrap(), json!({"brave": {"BRAVE_API_KEY": true}}));
|
||||
for f in ["settings.json", "secrets.dat"] {
|
||||
let bytes = std::fs::read(data.join("config").join(f)).unwrap();
|
||||
if cfg!(windows) || f == "settings.json" {
|
||||
assert!(!String::from_utf8_lossy(&bytes).contains("brave-key-123"), "{f}");
|
||||
}
|
||||
}
|
||||
a.hub.push(Level::Error, "llm", "server said brave-key-123");
|
||||
let report = a.call("logs_error_report", json!({})).await.unwrap()["report"].as_str().unwrap().to_owned();
|
||||
assert!(report.contains("server said") && !report.contains("brave-key-123"));
|
||||
// A new app on the same folder masks it too, before anything is saved again.
|
||||
let b = AdminApi::new(&a.location_file, LogHub::new(None));
|
||||
b.hub.push(Level::Error, "llm", "again brave-key-123");
|
||||
assert!(!b.call("logs_error_report", json!({})).await.unwrap()["report"].as_str().unwrap().contains("brave-key-123"));
|
||||
// Removing the server removes its value.
|
||||
a.call("settings_apply", json!({"changes": {"mcpServers": []}})).await.unwrap();
|
||||
let secrets = Secrets::new(&data.join("config").join("secrets.dat"));
|
||||
assert!(secrets.names().unwrap().iter().all(|n| !n.starts_with("mcp:")));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn the_dashboard_answers_before_anything_runs() {
|
||||
let (a, base) = api("api3");
|
||||
|
||||
135
app/src/features.rs
Normal file
135
app/src/features.rs
Normal file
@@ -0,0 +1,135 @@
|
||||
//! The brain's features and MCP servers (`app/src/admin.spec.md`, "Features and MCP servers"):
|
||||
//! what the app writes into the brain's settings, and the MCP servers' environment values, which
|
||||
//! are secrets and reach the worker only through its environment.
|
||||
|
||||
use serde_json::{json, Map, Value};
|
||||
|
||||
use crate::secrets::{Secrets, SecretsError};
|
||||
use crate::settings::{FeatureSettings, McpServerSettings};
|
||||
|
||||
/// The worker's environment variable with the MCP servers' environment values
|
||||
/// (`voice_worker/brain.py`, `MCP_ENV_VAR`).
|
||||
pub const MCP_ENV_VAR: &str = "JARVIS_MCP_ENV";
|
||||
|
||||
/// The brain's built-in tools behind each feature switch (`jarvis/tools/registry.py`).
|
||||
pub const FEATURE_TOOLS: &[(&str, &[&str])] = &[
|
||||
("weather", &["getWeather"]),
|
||||
("webSearch", &["webSearch", "fetchWebPage"]),
|
||||
("meals", &["logMeal", "fetchMeals", "deleteMeal"]),
|
||||
];
|
||||
|
||||
/// The built-in tools of the features that are off.
|
||||
pub fn disabled_tools(f: &FeatureSettings) -> Vec<&'static str> {
|
||||
let on = |key: &str| match key {
|
||||
"weather" => f.weather,
|
||||
"webSearch" => f.web_search,
|
||||
_ => f.meals,
|
||||
};
|
||||
FEATURE_TOOLS.iter().filter(|(k, _)| !on(k)).flat_map(|(_, tools)| tools.iter().copied()).collect()
|
||||
}
|
||||
|
||||
/// The brain's `mcps`: the enabled servers, without their environment values.
|
||||
pub fn brain_mcps(servers: &[McpServerSettings]) -> Value {
|
||||
Value::Object(servers.iter().filter(|s| s.enabled)
|
||||
.map(|s| (s.name.clone(), json!({"transport": "stdio", "command": s.command, "args": s.args})))
|
||||
.collect())
|
||||
}
|
||||
|
||||
/// Where one environment value of a server is kept in the secrets.
|
||||
pub fn secret_name(server: &str, var: &str) -> String {
|
||||
format!("mcp:{server}:{var}")
|
||||
}
|
||||
|
||||
/// `{server: {NAME: value}}` for the enabled servers, with the values that are stored.
|
||||
pub fn mcp_env(secrets: &Secrets, servers: &[McpServerSettings]) -> Result<Value, SecretsError> {
|
||||
let mut out = Map::new();
|
||||
for s in servers.iter().filter(|s| s.enabled) {
|
||||
let mut vars = Map::new();
|
||||
for var in &s.env {
|
||||
if let Some(v) = secrets.get(&secret_name(&s.name, var))? {
|
||||
vars.insert(var.clone(), Value::String(v));
|
||||
}
|
||||
}
|
||||
if !vars.is_empty() {
|
||||
out.insert(s.name.clone(), Value::Object(vars));
|
||||
}
|
||||
}
|
||||
Ok(Value::Object(out))
|
||||
}
|
||||
|
||||
/// Which environment values are stored: `{server: {NAME: true|false}}` (never the values).
|
||||
pub fn env_status(secrets: &Secrets, servers: &[McpServerSettings]) -> Result<Value, SecretsError> {
|
||||
let names = secrets.names()?;
|
||||
Ok(Value::Object(servers.iter().map(|s| {
|
||||
let vars = s.env.iter().map(|v| (v.clone(), Value::Bool(names.contains(&secret_name(&s.name, v))))).collect();
|
||||
(s.name.clone(), Value::Object(vars))
|
||||
}).collect()))
|
||||
}
|
||||
|
||||
/// Remove the stored values of servers and names no longer listed.
|
||||
pub fn prune(secrets: &Secrets, servers: &[McpServerSettings]) -> Result<(), SecretsError> {
|
||||
let keep: Vec<String> = servers.iter().flat_map(|s| s.env.iter().map(|v| secret_name(&s.name, v))).collect();
|
||||
for name in secrets.names()? {
|
||||
if name.starts_with("mcp:") && !keep.contains(&name) {
|
||||
secrets.remove(&name)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::datadir::temp_dir;
|
||||
use crate::settings::parse_settings;
|
||||
|
||||
fn servers(v: Value) -> Vec<McpServerSettings> {
|
||||
parse_settings(&json!({"mcpServers": v})).unwrap().mcp_servers
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_feature_tools_are_the_brains_tool_names() {
|
||||
let registry = std::fs::read_to_string(
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../src/jarvis/tools/registry.py")).unwrap();
|
||||
for (_, tools) in FEATURE_TOOLS {
|
||||
for t in *tools {
|
||||
assert!(registry.contains(&format!("\"{t}\":")), "{t} is not a built-in tool");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn features_that_are_off_turn_their_tools_off() {
|
||||
let all_on = FeatureSettings { weather: true, web_search: true, meals: true };
|
||||
assert!(disabled_tools(&all_on).is_empty());
|
||||
let off = disabled_tools(&FeatureSettings { weather: false, web_search: true, meals: false });
|
||||
assert_eq!(off, vec!["getWeather", "logMeal", "fetchMeals", "deleteMeal"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_enabled_servers_reach_the_brain_and_their_values_only_through_the_environment() {
|
||||
let s = servers(json!([
|
||||
{"name": "brave", "command": "npx", "args": ["-y", "brave"], "env": ["BRAVE_API_KEY", "UNSET"]},
|
||||
{"name": "off", "command": "uvx", "env": ["K"], "enabled": false}]));
|
||||
assert_eq!(brain_mcps(&s), json!({"brave": {"transport": "stdio", "command": "npx", "args": ["-y", "brave"]}}));
|
||||
let secrets = Secrets::new(&temp_dir("mcpenv").join("secrets.dat"));
|
||||
secrets.set(&secret_name("brave", "BRAVE_API_KEY"), "key-1").unwrap();
|
||||
secrets.set(&secret_name("off", "K"), "key-2").unwrap();
|
||||
assert_eq!(mcp_env(&secrets, &s).unwrap(), json!({"brave": {"BRAVE_API_KEY": "key-1"}}));
|
||||
assert_eq!(env_status(&secrets, &s).unwrap(),
|
||||
json!({"brave": {"BRAVE_API_KEY": true, "UNSET": false}, "off": {"K": true}}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn values_of_removed_servers_and_names_are_deleted() {
|
||||
let secrets = Secrets::new(&temp_dir("mcpprune").join("secrets.dat"));
|
||||
secrets.set(crate::secrets::DISCORD_TOKEN, "tok").unwrap();
|
||||
for (srv, var) in [("a", "K1"), ("a", "K2"), ("b", "K")] {
|
||||
secrets.set(&secret_name(srv, var), "v").unwrap();
|
||||
}
|
||||
prune(&secrets, &servers(json!([{"name": "a", "command": "x", "env": ["K1"]}]))).unwrap();
|
||||
let mut left = secrets.names().unwrap();
|
||||
left.sort();
|
||||
assert_eq!(left, vec![crate::secrets::DISCORD_TOKEN.to_string(), secret_name("a", "K1")]);
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ pub mod discord;
|
||||
pub mod discord_setup;
|
||||
pub mod download;
|
||||
pub mod earcon;
|
||||
pub mod features;
|
||||
pub mod frames;
|
||||
pub mod install;
|
||||
pub mod logs;
|
||||
|
||||
@@ -68,6 +68,11 @@ impl Secrets {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The names of the stored secrets.
|
||||
pub fn names(&self) -> Result<Vec<String>, SecretsError> {
|
||||
Ok(self.load()?.keys().cloned().collect())
|
||||
}
|
||||
|
||||
/// Every stored value, for log redaction.
|
||||
pub fn values(&self) -> Vec<String> {
|
||||
self.load().map(|m| m.values().filter_map(Value::as_str).map(str::to_owned).collect()).unwrap_or_default()
|
||||
|
||||
@@ -39,15 +39,18 @@ impl Services {
|
||||
pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let settings = load_settings(&data_dir.join("config").join("settings.json"))?;
|
||||
// The stored token (the setup wizard keeps it encrypted, admin.spec.md), else the environment.
|
||||
let stored = crate::secrets::Secrets::new(&data_dir.join("config").join("secrets.dat"))
|
||||
.get(crate::secrets::DISCORD_TOKEN)?;
|
||||
let secrets = crate::secrets::Secrets::new(&data_dir.join("config").join("secrets.dat"));
|
||||
let stored = secrets.get(crate::secrets::DISCORD_TOKEN)?;
|
||||
// The MCP servers' environment values stay encrypted on disk: they reach the brain only in the
|
||||
// worker's environment (admin.spec.md, "Features and MCP servers").
|
||||
let mcp_env = crate::features::mcp_env(&secrets, &settings.mcp_servers)?;
|
||||
let token = match stored {
|
||||
Some(t) => t,
|
||||
None => std::env::var("JARVIS_DISCORD_TOKEN").map_err(|_| "no bot token: set it in the app or JARVIS_DISCORD_TOKEN")?,
|
||||
};
|
||||
|
||||
let (base_url, model) = llm.start(&settings).await?;
|
||||
let brain_config = match crate::strata::write_brain_config(data_dir, &base_url, &model) {
|
||||
let brain_config = match crate::strata::write_brain_config(data_dir, &base_url, &model, &settings) {
|
||||
Ok(f) => f,
|
||||
Err(e) => return Err(after_llm_stop(&llm, format!("could not write the brain settings: {e}")).await.into()),
|
||||
};
|
||||
@@ -60,6 +63,7 @@ pub async fn start_services(data_dir: &Path, llm: Arc<Llm>) -> Result<Services,
|
||||
wopts.env.extend(layout.env());
|
||||
}
|
||||
wopts.env.insert("JARVIS_CONFIG_PATH".into(), brain_config.to_string_lossy().into_owned());
|
||||
wopts.env.insert(crate::features::MCP_ENV_VAR.into(), mcp_env.to_string());
|
||||
let worker_process = match WorkerProcess::new(wopts) {
|
||||
Ok(p) => p,
|
||||
Err(e) => return Err(after_llm_stop(&llm, e.to_string()).await.into()),
|
||||
|
||||
@@ -85,6 +85,25 @@ pub struct LlmSettings {
|
||||
pub context: u32,
|
||||
}
|
||||
|
||||
/// The brain's built-in features (admin.spec.md, "Features and MCP servers"); each is on by default.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct FeatureSettings {
|
||||
pub weather: bool,
|
||||
pub web_search: bool,
|
||||
pub meals: bool,
|
||||
}
|
||||
|
||||
/// An MCP server the brain starts (stdio). The values of `env` are in the secrets, never here.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct McpServerSettings {
|
||||
pub name: String,
|
||||
pub command: String,
|
||||
pub args: Vec<String>,
|
||||
/// Names of the environment variables it gets (their values are secrets).
|
||||
pub env: Vec<String>,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Settings {
|
||||
pub discord: DiscordSettings,
|
||||
@@ -100,6 +119,8 @@ pub struct Settings {
|
||||
/// `hello`; the worker validates them, the settings screens check them first (admin.spec.md).
|
||||
pub memory: Map<String, Value>,
|
||||
pub llm: LlmSettings,
|
||||
pub features: FeatureSettings,
|
||||
pub mcp_servers: Vec<McpServerSettings>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -143,6 +164,8 @@ impl Default for Settings {
|
||||
response: PolicySettings::default(),
|
||||
memory: Map::new(),
|
||||
llm: LlmSettings { url: None, port: 8080, context: 32768 },
|
||||
features: FeatureSettings { weather: true, web_search: true, meals: true },
|
||||
mcp_servers: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -454,9 +477,70 @@ pub fn parse_settings(raw: &Value) -> Result<Settings, SettingsError> {
|
||||
Some(_) => return err("memory must be an object"),
|
||||
},
|
||||
llm: parse_llm(raw, &d.llm)?,
|
||||
features: {
|
||||
let f = section(raw, "features")?;
|
||||
FeatureSettings {
|
||||
weather: get_bool(f, "weather", "features", d.features.weather)?,
|
||||
web_search: get_bool(f, "webSearch", "features", d.features.web_search)?,
|
||||
meals: get_bool(f, "meals", "features", d.features.meals)?,
|
||||
}
|
||||
},
|
||||
mcp_servers: parse_mcp_servers(raw)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// An MCP server name: 1-32 letters, digits, `-` or `_`, without `__` (the brain names a server's
|
||||
/// tools `<server>__<tool>`).
|
||||
fn valid_mcp_name(s: &str) -> bool {
|
||||
(1..=32).contains(&s.len()) && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') && !s.contains("__")
|
||||
}
|
||||
|
||||
/// An environment variable name: a letter or `_`, then letters, digits or `_`.
|
||||
fn valid_env_name(s: &str) -> bool {
|
||||
let mut b = s.bytes();
|
||||
b.next().is_some_and(|c| c.is_ascii_alphabetic() || c == b'_') && b.all(|c| c.is_ascii_alphanumeric() || c == b'_')
|
||||
&& s.len() <= 64
|
||||
}
|
||||
|
||||
fn parse_mcp_servers(raw: &Map<String, Value>) -> Result<Vec<McpServerSettings>, SettingsError> {
|
||||
let list = match raw.get("mcpServers") {
|
||||
None => return Ok(vec![]),
|
||||
Some(Value::Array(a)) => a,
|
||||
Some(_) => return err("mcpServers must be a list"),
|
||||
};
|
||||
let mut out: Vec<McpServerSettings> = Vec::new();
|
||||
for (i, v) in list.iter().enumerate() {
|
||||
let path = format!("mcpServers[{i}]");
|
||||
let Value::Object(m) = v else { return err(format!("{path} must be an object")) };
|
||||
let name = get_str(Some(m), "name", &path, "")?.trim().to_owned();
|
||||
if !valid_mcp_name(&name) {
|
||||
return err(format!("{path}.name must be 1-32 letters, digits, - or _ (no __)"));
|
||||
}
|
||||
if out.iter().any(|s| s.name == name) {
|
||||
return err(format!("{path}.name is listed twice"));
|
||||
}
|
||||
let command = get_str(Some(m), "command", &path, "")?.trim().to_owned();
|
||||
if command.is_empty() {
|
||||
return err(format!("{path}.command must not be empty"));
|
||||
}
|
||||
let env = clean_words(get_str_list(Some(m), "env", &path, &[])?);
|
||||
if let Some(bad) = env.iter().find(|n| !valid_env_name(n)) {
|
||||
return err(format!("{path}.env has a name that is not an environment variable: {bad}"));
|
||||
}
|
||||
if env.iter().enumerate().any(|(j, n)| env[..j].contains(n)) {
|
||||
return err(format!("{path}.env lists a name twice"));
|
||||
}
|
||||
out.push(McpServerSettings {
|
||||
name,
|
||||
command,
|
||||
args: get_str_list(Some(m), "args", &path, &[])?,
|
||||
env,
|
||||
enabled: get_bool(Some(m), "enabled", &path, true)?,
|
||||
});
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn parse_llm(raw: &Map<String, Value>, d: &LlmSettings) -> Result<LlmSettings, SettingsError> {
|
||||
let l = section(raw, "llm")?;
|
||||
let url = match l.and_then(|m| m.get("url")) {
|
||||
@@ -631,6 +715,38 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn features_and_mcp_servers_are_read_and_checked() {
|
||||
let s = parse_settings(&json!({}));
|
||||
assert_eq!(s.unwrap().features, FeatureSettings { weather: true, web_search: true, meals: true });
|
||||
let s = parse_settings(&json!({
|
||||
"features": {"weather": false, "meals": false},
|
||||
"mcpServers": [{"name": "brave", "command": "npx", "args": ["-y", "brave"], "env": ["BRAVE_API_KEY", " "]},
|
||||
{"name": "time-2", "command": "uvx", "enabled": false}]
|
||||
})).unwrap();
|
||||
assert_eq!(s.features, FeatureSettings { weather: false, web_search: true, meals: false });
|
||||
assert_eq!(s.mcp_servers, vec![
|
||||
McpServerSettings { name: "brave".into(), command: "npx".into(), args: vec!["-y".into(), "brave".into()],
|
||||
env: vec!["BRAVE_API_KEY".into()], enabled: true },
|
||||
McpServerSettings { name: "time-2".into(), command: "uvx".into(), args: vec![], env: vec![], enabled: false },
|
||||
]);
|
||||
let cases = [
|
||||
(json!({"features": {"weather": "no"}}), "features.weather"),
|
||||
(json!({"mcpServers": {}}), "mcpServers"),
|
||||
(json!({"mcpServers": [{"name": "a__b", "command": "x"}]}), "mcpServers[0].name"),
|
||||
(json!({"mcpServers": [{"name": "", "command": "x"}]}), "mcpServers[0].name"),
|
||||
(json!({"mcpServers": [{"name": "a b", "command": "x"}]}), "mcpServers[0].name"),
|
||||
(json!({"mcpServers": [{"name": "a", "command": "x"}, {"name": "a", "command": "y"}]}), "mcpServers[1].name"),
|
||||
(json!({"mcpServers": [{"name": "a", "command": " "}]}), "mcpServers[0].command"),
|
||||
(json!({"mcpServers": [{"name": "a", "command": "x", "env": ["1KEY"]}]}), "mcpServers[0].env"),
|
||||
(json!({"mcpServers": [{"name": "a", "command": "x", "env": ["K", "K"]}]}), "mcpServers[0].env"),
|
||||
];
|
||||
for (raw, key) in cases {
|
||||
let e = parse_settings(&raw).unwrap_err();
|
||||
assert!(e.0.contains(key), "{raw} -> {e}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_ids_clear_them() {
|
||||
let s = parse_settings(&json!({"discord": {"guildId": null, "voiceChannelId": null}})).unwrap();
|
||||
|
||||
@@ -19,6 +19,7 @@ pub enum Screen {
|
||||
Chat,
|
||||
Memory,
|
||||
Model,
|
||||
Features,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
|
||||
@@ -42,6 +43,8 @@ pub enum Kind {
|
||||
IdNumberMap,
|
||||
/// The registered chat channels (their own rules are checked by `parse_settings`).
|
||||
ChatChannels,
|
||||
/// The MCP servers (their own rules are checked by `parse_settings`; values are secrets).
|
||||
McpServers,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
|
||||
@@ -112,6 +115,11 @@ pub fn fields() -> Vec<Field> {
|
||||
// The LLM (admin.spec.md, "LLM"); `llm.url` (a server the app does not start) is file-only.
|
||||
f("llm.context", Model, Int { min: 4096, max: 262144 }, json!(32768), "대화 모델이 한 번에 기억하는 양(토큰)"),
|
||||
f("llm.port", Model, Int { min: 1024, max: 65535 }, json!(8080), "대화 모델 포트"),
|
||||
// The brain's features (admin.spec.md, "Features and MCP servers").
|
||||
f("features.weather", Features, Bool, json!(true), "날씨"),
|
||||
f("features.webSearch", Features, Bool, json!(true), "웹 검색"),
|
||||
f("features.meals", Features, Bool, json!(true), "식단 기록"),
|
||||
f("mcpServers", Features, McpServers, json!([]), "MCP 서버"),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -201,7 +209,7 @@ fn check(field: &Field, v: &Value) -> Result<(), String> {
|
||||
Kind::IdList => v.as_array().is_some_and(|a| a.iter().all(is_id)),
|
||||
Kind::IdNumberMap => v.as_object().is_some_and(|m| m.iter()
|
||||
.all(|(k, n)| is_id(&Value::String(k.clone())) && n.as_i64().is_some())),
|
||||
Kind::ChatChannels => v.is_array(),
|
||||
Kind::ChatChannels | Kind::McpServers => v.is_array(),
|
||||
};
|
||||
if ok { Ok(()) } else { Err(format!("{} has a value it cannot take", field.path)) }
|
||||
}
|
||||
|
||||
@@ -117,14 +117,19 @@ pub async fn wait_ready(base: &str, timeout: Duration, cancel: &AtomicBool) -> R
|
||||
}
|
||||
}
|
||||
|
||||
/// The brain's settings (`config/brain.json`, the worker's `JARVIS_CONFIG_PATH`): the LLM and the
|
||||
/// memory database inside the data folder. The app owns this file and writes it on every start.
|
||||
pub fn write_brain_config(data: &Path, base_url: &str, model: &str) -> Result<std::path::PathBuf, String> {
|
||||
/// The brain's settings (`config/brain.json`, the worker's `JARVIS_CONFIG_PATH`): the LLM, the
|
||||
/// memory database inside the data folder, the tools of the features that are off and the enabled
|
||||
/// MCP servers (without their environment values, `features.rs`). The app owns this file and writes
|
||||
/// it on every start.
|
||||
pub fn write_brain_config(data: &Path, base_url: &str, model: &str, settings: &crate::settings::Settings)
|
||||
-> Result<std::path::PathBuf, String> {
|
||||
let file = data.join("config").join("brain.json");
|
||||
let cfg = json!({
|
||||
"ollama_base_url": base_url,
|
||||
"ollama_chat_model": model,
|
||||
"db_path": data.join("memory").join("jarvis.db").to_string_lossy(),
|
||||
"disabled_tools": crate::features::disabled_tools(&settings.features),
|
||||
"mcps": crate::features::brain_mcps(&settings.mcp_servers),
|
||||
"_config_version": 1,
|
||||
});
|
||||
let mut text = serde_json::to_string_pretty(&cfg).unwrap();
|
||||
@@ -375,11 +380,15 @@ mod tests {
|
||||
#[test]
|
||||
fn the_brain_config_points_at_the_llm_and_keeps_memory_in_the_data_folder() {
|
||||
let l = layout("llm2");
|
||||
let f = write_brain_config(&l.data, "http://127.0.0.1:8080/v1", "m").unwrap();
|
||||
let s = parse_settings(&json!({"features": {"weather": false},
|
||||
"mcpServers": [{"name": "brave", "command": "npx", "env": ["BRAVE_API_KEY"]}]})).unwrap();
|
||||
let f = write_brain_config(&l.data, "http://127.0.0.1:8080/v1", "m", &s).unwrap();
|
||||
let v: Value = serde_json::from_str(&std::fs::read_to_string(f).unwrap()).unwrap();
|
||||
assert_eq!(v["ollama_base_url"], "http://127.0.0.1:8080/v1");
|
||||
assert_eq!(v["ollama_chat_model"], "m");
|
||||
assert!(Path::new(v["db_path"].as_str().unwrap()).starts_with(&l.data));
|
||||
assert_eq!(v["disabled_tools"], json!(crate::features::disabled_tools(&s.features)));
|
||||
assert_eq!(v["mcps"], crate::features::brain_mcps(&s.mcp_servers));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
|
||||
@@ -121,6 +121,8 @@ function editor(f, value) {
|
||||
break;
|
||||
case "chatChannels":
|
||||
return chatChannelsEditor(f, value);
|
||||
case "mcpServers":
|
||||
return mcpServersEditor(f, value);
|
||||
default:
|
||||
el = h("span", { class: "muted" }, JSON.stringify(value));
|
||||
read = () => value;
|
||||
@@ -181,6 +183,66 @@ function chatChannelsEditor(f, value) {
|
||||
return { el: h("div", {}, table, h("button", { class: "btn", onclick: () => addRow() }, "채널 추가")), read, wide: true };
|
||||
}
|
||||
|
||||
// One card per MCP server. Environment values (API keys) are secrets: they are typed here and stored
|
||||
// encrypted by the app on their own (mcp_env_set), and only "stored" or not ever comes back.
|
||||
function mcpServersEditor(f, value) {
|
||||
const list = h("div");
|
||||
const saved = new Set((value || []).map((s) => s.name));
|
||||
let status = {};
|
||||
const addServer = (s = {}) => {
|
||||
const name = h("input", { type: "text", value: s.name ?? "", placeholder: "이름 (영문, 숫자, - _)", "data-k": "name" });
|
||||
const command = h("input", { type: "text", value: s.command ?? "", placeholder: "명령 (예: npx, uvx)", "data-k": "command" });
|
||||
const args = h("textarea", { placeholder: "인자, 한 줄에 하나", "data-k": "args" }, (s.args || []).join("\n"));
|
||||
const env = h("textarea", { placeholder: "환경 변수 이름, 한 줄에 하나 (예: BRAVE_API_KEY)", "data-k": "env" }, (s.env || []).join("\n"));
|
||||
const enabled = h("input", { type: "checkbox", class: "switch", "data-k": "enabled" });
|
||||
enabled.checked = s.enabled ?? true;
|
||||
const values = h("div", { class: "small" });
|
||||
const fillValues = () => {
|
||||
values.replaceChildren();
|
||||
if (!saved.has(s.name)) {
|
||||
if ((s.env || []).length || env.value.trim()) values.append(h("div", { class: "muted" }, "환경 변수 값은 서버를 저장한 뒤 넣을 수 있습니다."));
|
||||
return;
|
||||
}
|
||||
for (const v of s.env || []) {
|
||||
const box = h("input", { type: "password", placeholder: status[s.name]?.[v] ? "저장됨 (바꾸려면 입력)" : "값 없음", autocomplete: "off" });
|
||||
const put = async (val) => {
|
||||
try {
|
||||
const r = await api("mcp_env_set", { server: s.name, name: v, value: val });
|
||||
status[s.name] = { ...(status[s.name] || {}), [v]: r.set };
|
||||
box.value = "";
|
||||
fillValues();
|
||||
toast(r.restartNeeded ? "저장했습니다. 다시 시작하면 적용됩니다." : "저장했습니다.");
|
||||
} catch (e) { fail(e); }
|
||||
};
|
||||
values.append(h("div", { class: "field" }, h("label", {}, v), box,
|
||||
h("button", { class: "btn", onclick: () => box.value.trim() ? put(box.value) : toast("값을 입력해 주세요", true) }, "값 저장"),
|
||||
status[s.name]?.[v] ? h("button", { class: "btn", onclick: () => put("") }, "값 지우기") : null));
|
||||
}
|
||||
};
|
||||
const card = h("div", { class: "card mcp" },
|
||||
h("div", { class: "field" }, h("label", {}, "이름"), name),
|
||||
h("div", { class: "field" }, h("label", {}, "명령"), command),
|
||||
h("div", { class: "field" }, h("label", {}, "인자"), args),
|
||||
h("div", { class: "field" }, h("label", {}, "환경 변수"), env),
|
||||
h("div", { class: "field" }, h("label", {}, "켜기"), enabled),
|
||||
values,
|
||||
h("button", { class: "btn", onclick: () => card.remove() }, "서버 삭제"));
|
||||
card.fillValues = fillValues;
|
||||
list.append(card);
|
||||
fillValues();
|
||||
};
|
||||
(value || []).forEach(addServer);
|
||||
api("mcp_env_status").then((st) => { status = st; for (const c of list.children) c.fillValues(); }).catch(() => {});
|
||||
const lines = (t) => t.split("\n").map((x) => x.trim()).filter(Boolean);
|
||||
const read = () => [...list.children].map((card) => {
|
||||
const k = (key) => card.querySelector(`[data-k="${key}"]`);
|
||||
return { name: k("name").value.trim(), command: k("command").value.trim(), args: lines(k("args").value),
|
||||
env: lines(k("env").value), enabled: k("enabled").checked };
|
||||
});
|
||||
return { el: h("div", {}, h("div", { class: "hint" }, "MCP 서버는 이 PC에서 프로그램으로 실행됩니다. 믿을 수 있는 서버만 추가해 주세요."),
|
||||
list, h("button", { class: "btn", onclick: () => addServer() }, "서버 추가")), read, wide: true };
|
||||
}
|
||||
|
||||
async function settingsScreen(screen, title, extra) {
|
||||
const [all, view] = await Promise.all([fields(), api("settings_view")]);
|
||||
const list = all.filter((f) => f.screen === screen);
|
||||
@@ -205,6 +267,7 @@ async function settingsScreen(screen, title, extra) {
|
||||
return;
|
||||
}
|
||||
toast(r.restartNeeded ? "저장했습니다. 다시 시작하면 적용됩니다." : "저장했습니다.");
|
||||
if (changes.mcpServers) show(current); // the saved servers' value inputs
|
||||
} catch (e) { fail(e); }
|
||||
};
|
||||
const view_ = h("div", {}, h("h1", {}, title), extra,
|
||||
@@ -413,7 +476,7 @@ async function show(name) {
|
||||
try {
|
||||
if (name === "dashboard") { screen.replaceChildren(); await refresh(); ticker = setInterval(refresh, 1000); return; }
|
||||
if (name === "logs") { const l = logsScreen(); screen.replaceChildren(l.view); ticker = setInterval(l.tick, 1000); return; }
|
||||
const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델" };
|
||||
const titles = { bot: "봇", channels: "채널·호출", chat: "채팅 채널", memory: "대화 기억", model: "모델", features: "기능" };
|
||||
const extra = name === "bot" ? await tokenCard() : null;
|
||||
const view = await settingsScreen(name, titles[name], extra);
|
||||
if (my === gen) screen.replaceChildren(view);
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
<button data-screen="chat" class="nav">채팅 채널</button>
|
||||
<button data-screen="memory" class="nav">대화 기억</button>
|
||||
<button data-screen="model" class="nav">모델</button>
|
||||
<button data-screen="features" class="nav">기능</button>
|
||||
<button data-screen="logs" class="nav">로그</button>
|
||||
<div class="side-foot" id="version"></div>
|
||||
</nav>
|
||||
|
||||
@@ -96,7 +96,7 @@ Every distinct LLM call in Jarvis, what feeds it, what consumes it, and how it i
|
||||
## 7. Tool Router (pre-loop tool selection)
|
||||
|
||||
- **File**: [src/jarvis/tools/selection.py](src/jarvis/tools/selection.py) — `select_tools_with_llm()` (~line 331).
|
||||
- **Trigger**: once per reply, **at the very front of the flow before the planner (#12)**. Always runs — the router is the authoritative tool picker, and its narrowed catalogue is what the planner sees. When the planner later references tools, those names are unioned into the router's allow-list but never replace it; small models tend to default to `webSearch` where a dedicated tool like `getWeather` should win, and the router is tuned for that classification. `tool_selection_strategy == "llm"` is the default; other strategies (`all`, `keyword`, `embedding`) also run here. **v2 brain** (`run_reply_engine(intent_judge=True)`): the router is the turn's judgement; the planner (#12) runs only when it picked a tool other than the sentinels `stop` and `toolSearchTool`. `prepare_intent()` runs the same pick ahead on a partial transcript while the user is still talking, and the reply uses it (`prepared_tools`) without a router call of its own (planner.spec.md, "Intent judge (v2)"). Without `stream_browser` the screen-share tools (`controlBrowser`, `browseAndPlay`, `setBroadcast`) are not in the router's or the chat model's catalogue.
|
||||
- **Trigger**: once per reply, **at the very front of the flow before the planner (#12)**. Always runs — the router is the authoritative tool picker, and its narrowed catalogue is what the planner sees. When the planner later references tools, those names are unioned into the router's allow-list but never replace it; small models tend to default to `webSearch` where a dedicated tool like `getWeather` should win, and the router is tuned for that classification. `tool_selection_strategy == "llm"` is the default; other strategies (`all`, `keyword`, `embedding`) also run here. **v2 brain** (`run_reply_engine(intent_judge=True)`): the router is the turn's judgement; the planner (#12) runs only when it picked a tool other than the sentinels `stop` and `toolSearchTool`. `prepare_intent()` runs the same pick ahead on a partial transcript while the user is still talking, and the reply uses it (`prepared_tools`) without a router call of its own (planner.spec.md, "Intent judge (v2)"). Without `stream_browser` the screen-share tools (`controlBrowser`, `browseAndPlay`, `setBroadcast`) are not in the router's or the chat model's catalogue. Neither are the tools in `cfg.disabled_tools` (the v2 app's feature switches; the v2 brain also adds `localFiles` and `screenshot`), also not through `toolSearchTool` (#7's re-run), and the executor refuses them (`enabled_builtin_tools`, reply.spec.md).
|
||||
- **Model / gating**: `resolve_tool_router_model(cfg)` chain — `tool_router_model → intent_judge_model → ollama_chat_model`.
|
||||
- **Inputs**: user query, tool catalogue (builtin + MCP with descriptions), optional narrow-down hint.
|
||||
- **System prompt**: inline (~lines 260-315). Teaches pick up-to-5 tools or `none`.
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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", ""),
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
132
tests/test_v2_features.py
Normal file
132
tests/test_v2_features.py
Normal file
@@ -0,0 +1,132 @@
|
||||
"""Turning tools off and the MCP servers the v2 brain connects (voice_worker.spec.md, "Tools";
|
||||
reply.spec.md, "Tools and MCP").
|
||||
|
||||
Behaviours: a tool in ``disabled_tools`` is neither offered nor run, also through toolSearchTool;
|
||||
the v2 brain never offers v1's host file and screen tools; it connects the configured MCP servers
|
||||
with the environment the app passes outside the config file, and keeps that out of its own
|
||||
environment.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
import sys
|
||||
import textwrap
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _settings(tmp_path, monkeypatch, **extra):
|
||||
from jarvis.config import load_settings
|
||||
|
||||
cfg = tmp_path / "config.json"
|
||||
cfg.write_text(json.dumps({"db_path": str(tmp_path / "jarvis.db"), **extra}))
|
||||
monkeypatch.setenv("JARVIS_CONFIG_PATH", str(cfg))
|
||||
return load_settings()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_disabled_tools_are_read_from_the_settings(tmp_path, monkeypatch):
|
||||
assert _settings(tmp_path, monkeypatch).disabled_tools == ()
|
||||
s = _settings(tmp_path, monkeypatch, disabled_tools=["getWeather", "webSearch"])
|
||||
assert set(s.disabled_tools) == {"getWeather", "webSearch"}
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_disabled_tool_is_not_offered(tmp_path, monkeypatch):
|
||||
from jarvis.reply.engine import _offered_builtins
|
||||
|
||||
s = _settings(tmp_path, monkeypatch, disabled_tools=["getWeather"])
|
||||
offered = _offered_builtins(s, chat_available=False)
|
||||
assert "getWeather" not in offered
|
||||
assert "webSearch" in offered
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_a_disabled_tool_does_not_run_even_when_the_model_names_it(tmp_path, monkeypatch):
|
||||
from jarvis.tools.registry import run_tool_with_retries
|
||||
|
||||
monkeypatch.setenv("HOME", str(tmp_path))
|
||||
monkeypatch.setenv("USERPROFILE", str(tmp_path))
|
||||
s = _settings(tmp_path, monkeypatch, disabled_tools=["localFiles"])
|
||||
r = run_tool_with_retries(None, s, "localFiles", {"operation": "write", "path": "x.txt", "content": "hi"},
|
||||
"", "", "")
|
||||
assert r.success is False
|
||||
assert not (tmp_path / "x.txt").exists()
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_tool_search_never_surfaces_a_disabled_tool(tmp_path, monkeypatch):
|
||||
from jarvis.tools.base import ToolContext
|
||||
from jarvis.tools.builtin import tool_search
|
||||
|
||||
# A router that picks every tool it is shown: what it is shown is the catalogue.
|
||||
monkeypatch.setattr(tool_search, "select_tools", lambda builtin_tools, **kw: list(builtin_tools))
|
||||
s = _settings(tmp_path, monkeypatch, disabled_tools=["localFiles", "screenshot"])
|
||||
ctx = ToolContext(db=None, cfg=s, system_prompt="", original_prompt="", redacted_text="",
|
||||
max_retries=0, user_print=lambda m: None)
|
||||
r = tool_search.ToolSearchTool().run({"query": "files on my computer"}, ctx)
|
||||
assert r.success
|
||||
names = {line.split(":", 1)[0].strip() for line in r.reply_text.splitlines() if ":" in line}
|
||||
assert "getWeather" in names
|
||||
assert not {"localFiles", "screenshot"} & names
|
||||
|
||||
|
||||
FAKE_SERVER = textwrap.dedent("""
|
||||
import os
|
||||
from mcp.server.fastmcp import FastMCP
|
||||
|
||||
app = FastMCP("fake")
|
||||
|
||||
@app.tool()
|
||||
def secret_echo() -> str:
|
||||
\"\"\"Says the key it was started with.\"\"\"
|
||||
return "key=" + os.environ.get("FAKE_KEY", "")
|
||||
|
||||
app.run()
|
||||
""")
|
||||
|
||||
|
||||
@pytest.mark.unit
|
||||
def test_the_v2_brain_offers_no_host_files_or_screen_and_connects_mcp_with_the_apps_env(tmp_path, monkeypatch, capfd):
|
||||
pytest.importorskip("mcp") # the real brain needs the jarvis dependencies (--brain)
|
||||
from jarvis.reply.engine import _offered_builtins
|
||||
from jarvis.tools import registry
|
||||
from voice_worker import brain as brain_mod
|
||||
|
||||
server = tmp_path / "fake_server.py"
|
||||
server.write_text(FAKE_SERVER)
|
||||
_settings(tmp_path, monkeypatch, disabled_tools=["getWeather"],
|
||||
mcps={"fake": {"command": sys.executable, "args": [str(server)]},
|
||||
"broken": {"command": str(tmp_path / "no-such-program")}})
|
||||
monkeypatch.setenv(brain_mod.MCP_ENV_VAR, json.dumps({"fake": {"FAKE_KEY": "s3cret"}}))
|
||||
monkeypatch.setattr(registry, "_mcp_tools_cache", {})
|
||||
|
||||
b = brain_mod.JarvisBrain()
|
||||
# The secrets are taken out of the worker's environment, so no other child process inherits them.
|
||||
import os
|
||||
assert brain_mod.MCP_ENV_VAR not in os.environ
|
||||
offered = _offered_builtins(b.cfg, chat_available=False)
|
||||
assert not {"localFiles", "screenshot", "getWeather"} & set(offered)
|
||||
assert "webSearch" in offered
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
while "fake__secret_echo" not in registry.get_cached_mcp_tools() and time.monotonic() < deadline:
|
||||
time.sleep(0.1)
|
||||
assert "fake__secret_echo" in registry.get_cached_mcp_tools()
|
||||
r = registry.run_tool_with_retries(None, b.cfg, "fake__secret_echo", {}, "", "", "")
|
||||
assert r.success and "key=s3cret" in (r.reply_text or "")
|
||||
# Each server's outcome reaches the app's log without debug logging, never the secret.
|
||||
deadline = time.monotonic() + 10
|
||||
err = ""
|
||||
while "broken" not in err and time.monotonic() < deadline:
|
||||
time.sleep(0.1)
|
||||
err += capfd.readouterr().err
|
||||
assert "MCP server fake: 1 tool(s)" in err
|
||||
assert "Warning: MCP server broken failed" in err
|
||||
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()
|
||||
Reference in New Issue
Block a user