diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 95fefd5..c3495cb 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -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 `__`), 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::` (`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::`). 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 diff --git a/app/src/admin_api.rs b/app/src/admin_api.rs index c38f8ca..ed43585 100644 --- a/app/src/admin_api.rs +++ b/app/src/admin_api.rs @@ -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) -> 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"); diff --git a/app/src/features.rs b/app/src/features.rs new file mode 100644 index 0000000..3d2599f --- /dev/null +++ b/app/src/features.rs @@ -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 { + 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 { + 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 = 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 { + 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")]); + } +} diff --git a/app/src/lib.rs b/app/src/lib.rs index 354ad89..9e0a3d6 100644 --- a/app/src/lib.rs +++ b/app/src/lib.rs @@ -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; diff --git a/app/src/secrets.rs b/app/src/secrets.rs index deda1bd..b63ac09 100644 --- a/app/src/secrets.rs +++ b/app/src/secrets.rs @@ -68,6 +68,11 @@ impl Secrets { Ok(()) } + /// The names of the stored secrets. + pub fn names(&self) -> Result, SecretsError> { + Ok(self.load()?.keys().cloned().collect()) + } + /// Every stored value, for log redaction. pub fn values(&self) -> Vec { self.load().map(|m| m.values().filter_map(Value::as_str).map(str::to_owned).collect()).unwrap_or_default() diff --git a/app/src/services.rs b/app/src/services.rs index d569983..676e4e7 100644 --- a/app/src/services.rs +++ b/app/src/services.rs @@ -39,15 +39,18 @@ impl Services { pub async fn start_services(data_dir: &Path, llm: Arc) -> Result> { 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) -> Result p, Err(e) => return Err(after_llm_stop(&llm, e.to_string()).await.into()), diff --git a/app/src/settings.rs b/app/src/settings.rs index b9bbb43..5f258c5 100644 --- a/app/src/settings.rs +++ b/app/src/settings.rs @@ -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, + /// Names of the environment variables it gets (their values are secrets). + pub env: Vec, + 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, pub llm: LlmSettings, + pub features: FeatureSettings, + pub mcp_servers: Vec, } #[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 { 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 `__`). +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) -> Result, 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 = 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, d: &LlmSettings) -> Result { 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(); diff --git a/app/src/settings_edit.rs b/app/src/settings_edit.rs index fca277b..9a26830 100644 --- a/app/src/settings_edit.rs +++ b/app/src/settings_edit.rs @@ -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 { // 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)) } } diff --git a/app/src/strata.rs b/app/src/strata.rs index d9c1561..c972c87 100644 --- a/app/src/strata.rs +++ b/app/src/strata.rs @@ -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 { +/// 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 { 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)] diff --git a/app/ui/app.js b/app/ui/app.js index a8ab246..cd76842 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -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); diff --git a/app/ui/index.html b/app/ui/index.html index fe2611c..865e681 100644 --- a/app/ui/index.html +++ b/app/ui/index.html @@ -17,6 +17,7 @@ +
diff --git a/docs/llm_contexts.md b/docs/llm_contexts.md index 90fad66..3481e22 100644 --- a/docs/llm_contexts.md +++ b/docs/llm_contexts.md @@ -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`. diff --git a/docs/v2/roadmap.md b/docs/v2/roadmap.md index 8e67cd4..7781203 100644 --- a/docs/v2/roadmap.md +++ b/docs/v2/roadmap.md @@ -10,7 +10,7 @@ | M3 | 두뇌 연결 | 기존 jarvis를 Ollama 대신 Strata 주소로 연결. 대화 기록 저장소와 지난 대화 전체 검색(본인 기록 + 등록한 채팅 채널 + 같은 음성 채널의 다른 사람 말). 채팅 채널 도구(읽기·검색·보내기·수정·반응·삭제·고정). 메모리, 날씨, 웹 검색, 식단, MCP 기존 테스트와 평가(evals) 통과. 1단계 완료(2026-11-11): LLM 주소가 `/v1`로 끝나면 OpenAI 호환 방식(`/chat/completions`, `/embeddings`)으로 부름. 형식 변환은 `src/jarvis/llm.py` 한곳에서 하고 두뇌의 나머지 코드는 그대로 씀. 대화, 도구 호출, 스트리밍, 의도 판정, 받아쓰기 정리, 미리 불러오기가 모두 이 방식으로 감. 이 서버 Ollama의 `/v1` 주소와 qwen2.5:7b로 실제 두뇌 한 턴을 돌려 "서울 날씨 어때?"에 날씨 도구를 부르고 그 결과로 답하는 것을 확인함. Strata에는 임베딩 모델이 없어 지난 기록 검색은 낱말 검색으로 함. 2단계 완료(2026-11-11): 대화 기록 저장소 `src/jarvis/memory/history.py`(스펙 [history.spec.md](../../src/jarvis/memory/history.spec.md)). 음성 전사, 자비스의 답, 채팅 채널 글, 음성 채널 출입 시간을 저장하고, 묻는 사람이 볼 수 있는 기록(본인 기록, 채팅 채널, 함께 있던 동안의 다른 사람 말)만 찾음. 전체 기간에서 관련도 순으로 찾고, 기록 10만 개에서 검색 48~143ms. 두뇌는 찾은 기록을 받아 지시문에 참고 자료로 넣음(평가 `evals/test_history_context_recall.py`, qwen2.5:7b에서 3번 모두 통과). 3단계 완료(2026-11-11): 앱이 음성 워커에 음성 채널 입장·퇴장, 사람 출입, 등록한 채팅 채널의 글·수정·삭제를 알리고, 워커가 최종 전사를 저장함. 워커는 `--history`로 저장소를, `--brain`으로 두뇌를 켜고, `reply` 요청에 묻는 사람의 범위로 찾은 기록을 넣어 답하고(`reply_text`) 음성이면 바로 말함. 실제 디스코드 시험(봇 두 개)에서 전사 8개가 이름과 함께 저장되고, 채팅 수정은 반영, 삭제한 글은 빠지고, 자비스가 나간 뒤 출입 기록이 모두 닫힘. 워커와 실제 두뇌(이 서버 Ollama `/v1`, qwen2.5:7b, 맥락 8천 토큰)로 다른 사람이 채팅에 남긴 약속을 4번 물어 4번 모두 맞게 답함. Ollama의 `/v1`은 맥락을 2,048토큰으로 고정해 지시문을 자르므로, Ollama로 시험할 때는 `num_ctx`를 넣은 모델 이름을 씀(Strata는 시작할 때 맥락을 정해 해당 없음). v2 두뇌는 한 사람용인 v1 장기 기억(프로필·일기·그래프)을 넣지 않고, 답하는 동안 원문이 로그에 찍히지 않게 함. 언제 `reply`를 보낼지(호출 판정)와 음성 답 재생 연결은 M4. 4단계 완료(2026-11-11): 채팅 채널 도구 `chatChannels`(목록·읽기·검색·보내기·수정·반응·삭제·고정, 스펙 [chat_channels.spec.md](../../src/jarvis/tools/builtin/chat_channels.spec.md)). 읽기·검색은 대화 기록 저장소에서, 나머지는 앱이 채널별 허용 설정을 확인하고 디스코드에서 실행. 삭제는 다음 메시지에서 사용자가 동의해야 실행하고, 채널 글은 명령이 아닌 자료로 표시. 실제 디스코드에서 수정(자기 글만)·반응·삭제·고정을 확인(음성 채널의 채팅은 디스코드가 고정을 막아 오류로 돌아옴). 평가(qwen2.5:7b) 3번에 12번 중 10번 통과, 글 속 명령을 따르지 않기와 같은 턴에 지우지 않기는 12번 모두 지킴. 식단 기록은 사람별로 나눔(v1 데이터는 그대로). 기존 테스트·평가 확인(2026-11-11): 단위 테스트는 2,215개 통과, 10개 실패이고, 실패 10개는 이 서버에 PortAudio가 없어 마이크 코드(음성 듣기·받아쓰기)가 꺼진 탓임. 갱신되지 않았던 테스트 4개(한국어 한 문장 날씨 3, 잡담 빠른 경로를 지나는 캐시 1)와 설치된 PyQt6를 가짜로 바꿔 다른 화면 테스트를 깨뜨리던 테스트 1곳을 고침. 평가(evals, qwen2.5:7b)는 145개 통과, 56개 실패, 60개 건너뜀. 실패 중 54개는 M3 이전 커밋(beaacb3)에서도 실패하거나, 3번씩 다시 돌린 통과 횟수가 양쪽이 같아 M3 때문에 생긴 실패는 없음. 나머지 2개는 새 채팅 도구 평가의 알려진 실패(12번 중 2번). 원래 실패하는 평가는 이 서버에 없는 모델(gpt-oss:20b, nomic-embed-text)을 쓰거나 qwen2.5:7b가 웹 검색·날씨 도구를 부르지 않는 경우가 대부분임. 실제로 쓸 모델로 평가 확인(2026-11-11): 게임PC의 Strata(Qwen3.6-35B-A3B UD-Q4_K_XL, 맥락 32K, 평소 배치)에 SSH 터널로 붙어 이 서버에서 평가 전체를 돌림. 193개 통과, 12개 실패, 60개 건너뜀(의도 판정·도구 선택 평가는 gemma4 단계에서만 돌고, gemma4는 이 서버 Ollama에 없음), 8분 13초. 실패 12개를 3번씩 다시 돌리니 5개는 3번 모두 실패(알려진 위치를 날씨 도구 인자로 넣지 않음 2, 파리·런던 비교에서 날씨 도구를 한 번만 부름 1, 지식 그래프 갈래 분류 1, 맥락에 있는 위치를 기억 검색 질문에 다시 넣음 1)했고, 날씨 한 번 부르기 평가는 엔진의 정해진 날씨 경로(`_maybe_deterministic_weather`)가 평가가 바꿔 둔 도구 실행기를 거치지 않고 실제 날씨를 받아 한국어로 바로 답해 3번 모두 실패함(모델과 상관없음). 나머지 6개는 3번 중 1~3번 통과함. qwen2.5:7b에서 없던 실패는 기억 검색 질문 1개(3번 모두)와 날씨 다시 시도 2개(다시 돌리면 6번 중 4번 통과)임 실패 고침(2026-11-11): 엔진의 정해진 한국어 날씨 경로를 뺌(평가의 도구 실행기를 거치지 않았고, 사용자가 말한 위치를 쓰지 못함, 큰 모델은 도구 결과를 한국어 한 문장으로 그대로 답함). 날씨 도구와 대화 지시문은 사용자가 대화나 기억에서 말한 위치를 넣고, 자동으로 잡힌 위치는 옮겨 적지 않게 함. "구, 시, 나라" 이름이 안 찾아지면 넓은 지역으로 다시 찾음. 계획 단계에 현재 시간·위치 줄을 주어, 위치를 모를 때만 기억에서 사용자 위치를 먼저 찾게 함. 같은 도구 반복 제한이 이전 답변의 호출까지 세어 사용자가 다시 해 달라고 해도 막던 버그를 고침. 기억 검색어 지시문에서 평가와 같은 문장의 예시를 바꾸고 현재 맥락 블록을 예시 뒤로 옮김(위치를 모를 때는 여전히 묻는지 보는 평가 추가, qwen2.5:7b는 바꾸기 전에도 묻지 않음). 평가 전체 202개 통과, 4개 실패, 9분 3초. 이 전체 실행의 날씨 실패 1개는 장소를 말하지 않은 "what's the weather this week"에 자동으로 잡힌 위치(`Hackney, England, UK`)를 인자로 옮겨 적은 것으로, 그 뒤 날씨 도구와 지시문을 사용자가 말한 위치만 넣도록 좁혀 고침. 고친 뒤 날씨 평가 12개를 따로 3번 돌려 36번 중 34번 통과(이 평가는 3번 모두 통과, 실패 2번은 날씨 한 번 부르기 평가가 파리 날씨 답에 도시 이름을 다시 말하지 않은 것). 전체 실행의 나머지 실패는 지식 그래프 갈래 분류 1개(모델이 "사용자가 물었다"를 사용자 사실로 하나 더 남김, 지시문을 두 번 고쳐도 같아 되돌림, v2는 v1 장기 기억을 쓰지 않음)와 다시 돌리면 통과하는 2개(유명인 두 턴 대화, 최근 일기 반영) | | M4 | 왕복 완성과 지연 튜닝 | 호출어·호출 방식·지정한 사람 설정, 동시 대화 응답 정책 4가지(기본 "처음 대화만")와 정책별 끼어들기 규칙. 말 끝부터 첫 소리까지 실측 1.5초 이내, 10명 채널 부하 테스트. 1단계 완료(2026-11-11): 앱의 호출 판정 `app/src/calls.rs`와 응답 정책 `app/src/policy.rs`(스펙 [conversation.spec.md](../../app/src/conversation.spec.md)), 설정 `call`·`response`. 비슷한 발음은 유니코드 NFKD로 한글을 자모로 나눠 편집 거리로 판단(기본 0.2: "자비즈"는 호출, "서비스"는 아님). 정책은 말이 끝난 시각 순서, 먼저 끝난 말의 전사 대기(최대 0.8초), 끼어들기, 놓친 요청 사유를 가짜 시각으로 시험함. 2단계 완료(2026-11-11): 대화 루프 `app/src/conversation.rs`가 최종 전사를 호출 판정과 응답 정책에 넣고, 정책의 결정대로 두뇌에 답을 요청해(`reply`, 답은 워커가 같은 id로 읽음) 앱의 재생 대기열에서 재생, 끼어들 때는 그 답만 멈춤, "자비스 멈춰"는 모든 말을 멈춤, 놓친 요청은 글 없이 최근 100개를 남김. 두뇌의 두 판정 `src/voice_worker/judges.py`(봇에게 하는 말인지, 중요도 순위)는 답과 따로 돌아 기다리지 않음. 평가 `evals/test_voice_judges.py` 12개를 qwen2.5:7b에서 모두 통과. 답을 만드는 중에 멈춘 요청은 말하지 않음. 실제 Python 워커(가짜 두뇌)와 앱의 통합 시험 통과. 3단계 완료(2026-11-11): 채팅 채널 호출. 채널마다 `answer`(호출어로 부를 때만 / 모든 메시지에 대답), 채팅 호출어(`call.chatWakeWords`, 없으면 음성과 같음)와 지정한 사람 설정은 음성과 같이 씀. 답은 같은 채널에 원래 메시지의 답글로 올리고 아무도 부르지 않음. 다른 봇의 글과 보내기가 꺼진 채널에는 답하지 않음. 음성 대화 순서와는 따로 감(워커가 음성 답과 채팅 답을 따로 써서 다른 사람의 채팅 답 때문에 음성 답이 기다리지 않음. 한 사람의 답은 물은 순서대로 하나씩 씀. 두 답의 LLM 호출이 동시에 돌려면 Strata를 `--parallel 2`로 띄움, 앱이 Strata를 띄우는 M5 전까지). 5분 넘게 늦은 채팅 답은 올리지 않음. 실제 디스코드 시험과 지연 측정은 4단계. 4단계 첫 측정(2026-11-12): 앱의 실제 서비스(`start_services`: 대화 루프, 응답 정책, 워커, 두뇌)를 게임PC Strata(`--parallel 2`)에 붙이고, 봇 두 개로 질문 5개를 2번씩 말해 잼(`app/tests/live_round_trip.rs`). 10개 모두 소리로 답했고, 말 끝부터 첫 소리까지 중앙값 3.5초(최소 2.8초, 날씨 도구 8.6초). 9명이 동시에 말하는 부하(워커의 두 번째 연결로 녹음 문장 9개를 실시간으로 넣음, 그동안 최종 전사 259개)에서는 중앙값 4.4초, 최종 전사가 0.6~0.9초에서 0.8~1.8초로 늦어졌고 1번은 "기분"을 "딥"으로 잘못 들어 날씨 도구를 불러 18.8초가 걸림. 짧은 답의 시간은 최종 전사 0.65~0.85초, 두뇌 2.0~2.9초(도구 고르기 0.42초, 계획 0.5초, 답 호출의 지시문 약 4,300토큰 읽기 1.1초와 생성), 재생 시작과 전달 약 0.4초. Strata의 Qwen3.6 엔진은 지시문 앞부분 재사용을 하지 않아(`--prompt-cache-every`는 "이 엔진의 옵션이 아님"으로 무시됨, 같은 대화를 그대로 이어 갈 때만 재사용) 매 호출을 처음부터 읽음. 생성은 0.2~0.5초라 문장 단위로 흘려도 짧은 답은 거의 빨라지지 않음. 1.5초 기준은 아직 못 맞춤. 같은 시험에서 찾아 고친 것: v1 TTS 설정(영어 전용 Piper) 때문에 한국어 질문에 영어로 답하던 것(v2 두뇌는 묻는 사람의 언어로 답함), 호출어 뒤에 쉬면 "자비스"만 따로 끊겨 그 이름에만 답하고 이어진 질문은 무시하던 것(이제 같은 사람이 이어서 하는 말과 합침, `call.followUpMs`). 4단계 지연 줄이기(사용자 결정, 2026-11-12): 부름을 받으면 "띠링" 효과음(앱이 만든 0.3초 소리, `call.earcon`, 이름만 부르고 쉬면 그때 바로), 답은 한국어 기본(영어 등은 따로 부탁할 때만), v2 두뇌의 짧은 지시문(성격 설명 7.4천 자를 1.3천 자로, 답은 최대한 짧게, 화면공유 도구는 v2에 없어 뺌: 인사의 답 지시문 4,500토큰이 1,400토큰), 답 전에 판단 한 번(도구 고르기로 도구가 필요한지 정하고, 필요할 때만 계획. 계획 하나로 합치거나 계획을 아예 빼 보니 날씨나 여러 단계 질문이 틀려 이 방식으로 정함), 말하는 중의 중간 전사가 호출로 읽히면 도구 고르기를 미리 해 둠(워커 `prepare`). 평가 전체(v2 설정, 마지막 지시문 수정 전) 219개 통과, 6개 실패: 파리·런던 비교와 지식 그래프 갈래 분류는 전부터 실패, 3개는 v2가 쓰지 않는 v1 개인 기억(그래프·일기) 평가, 1개는 새 답 길이 평가("하늘은 왜 파래"의 답이 72자로 기준 70자를 넘음). 그 뒤 "왜·어떻게" 질문은 핵심 이유만 말하도록 지시문을 고치고 답 길이 평가를 따로 3번 돌려 3번 모두 통과(v2 답 합계 185~205자, 예전 315~356자), 한국어 기본·지난 대화·채팅 채널·건너뛴 도구 평가 22개도 모두 통과(전체 평가는 이 수정 뒤 다시 돌리지 않음). 실제 디스코드 재측정(2026-11-12, `app/tests/live_round_trip.rs`, 질문 5개 2번): 첫 소리(효과음)는 이름 뒤에 쉬면 질문이 끝나기 전에, 쉬지 않으면 0.94~1.10초. 답의 첫 소리는 중앙값 1.9초(1.56~2.30초, 날씨 도구 5.75~5.85초), 9명이 동시에 말할 때 2.8초(2.13~3.41초, "기분"을 "딥"으로 잘못 들은 1번은 웹 검색으로 13.3초). 혼자일 때는 미리 해 둔 판단이 5번 모두 쓰여 말 끝 뒤 두뇌 시간이 0.6~0.74초였고, 9명 부하에서는 중간 전사가 밀려 미리 판단이 한 번도 되지 않음(두뇌 1.4초). 같은 시험에서 찾아 고친 것: 모델이 "10시 37분"을 오후로 읽음(시간 줄에 12시간 표기 추가), 없는 타이머 도구 호출 글자(``)를 답으로 내 TTS가 읽을 뻔함(도구 호출로 읽음) | | M5 | 관리 앱 기본 | 첫 실행 마법사, 데이터 폴더, 런타임·모델 자동 설치, 대시보드, 봇/채널·호출/채팅 채널(디스코드 채널 이름·주제 반영 포함)/대화 기억/모델 설정, 로그 화면(보기·복사·다운로드). 단계: 1 관리 기능(화면 없음), 2 서비스 제어와 대시보드 자료, 3 Tauri 화면, 4 런타임·모델 자동 설치, 5 Windows 빌드와 확인. 1단계 완료(2026-11-12): `app/src/datadir.rs`(데이터 폴더와 위치 기억 파일, 남은 용량), `settings_edit.rs`(화면 5개의 항목 36개, 기본값과 다른 값만 저장, 모르는 키 보존, 앱 검사를 통과해야만 저장), `secrets.rs`(봇 토큰, Windows는 사용자 계정 DPAPI 암호화), `logs.rs`(서비스별 탭, 날짜별 파일 14일 보관, 최근 오류 복사, 10MB 이하 zip, 비밀값·토큰 모양 가림), 앱 설정에 대화 기억(`memory`) 칸을 넣어 워커에 넘김. 스펙 [admin.spec.md](../../app/src/admin.spec.md). Windows용 코드는 Windows 대상으로 컴파일만 확인(실행 확인은 5단계). 2단계 완료(2026-11-12): `control.rs`(서비스 시작·정지·재시작 규칙, 실패는 비밀값을 가린 오류로 남기고 아무것도 켜 두지 않음, 앱 실행 파일도 같은 제어기를 씀), `dashboard.rs`(디스코드 이벤트만으로 만드는 대시보드 자료: 연결 상태, 음성 채널과 참가자, 실시간 자막 30줄(화면에만, 기록하지 않음, 나가거나 정지하면 지움), 답 20개의 단계별 지연(말 끝→최종 전사, 두뇌, 목소리, 전체)과 중앙값, 놓친 요청 20개(글 없이)), `system.rs`(RAM, `nvidia-smi`로 GPU 사용률·VRAM). 성능 단계(평소/게임 중/일시정지)는 게임 감지와 함께 M7. 3단계 완료(2026-11-12): 화면 `app/ui/`(빌드 도구 없는 HTML/CSS/JS, 어두운 테마, 한국어)와 화면이 부르는 명령 `admin_api.rs`(설정, 대시보드, 시작·정지, 로그 조회·복사·zip, PC 점검, 디스코드 토큰 확인·초대 링크·서버/채널 목록 `discord_setup.rs`). 첫 실행 마법사(데이터 폴더, PC 점검, 모델 안내, 봇 연결, 서버·음성 채널, 호출어, 시작), 대시보드, 설정 5개, 로그. 개발용 서버 `jarvis-admin-dev`로 이 서버의 브라우저에서 실제 테스트 봇과 음성 워커를 켜고 확인: 마법사 각 단계, 시작 뒤 "실행 중 · 테스트봇#9029 · 워커 연결됨", 다시 시작·정지, 설정 저장(바뀐 값만, 모르는 키 보존), 채팅 채널 추가, 로그 실시간 보기와 zip 내보내기. Tauri 창(셸)은 이 서버에서 빌드할 수 없어(webkit2gtk 없음) Windows 빌드 단계에서 붙임. 디스코드 채널 이름·주제 반영은 아직. 4단계 첫 부분 완료(2026-11-12): 설치 `install.rs`·`download.rs`(이어받기, SHA-256 확인), M0 키트와 같은 방식으로 uv 0.11.20 → 워커·두뇌 Python 3.12 환경(v2 전용 패키지 목록 `requirements-brain.txt`) → MeloTTS Python 3.11 환경 → Whisper large-v3-turbo → MeloTTS 한국어 음성 → Strata를 모두 데이터 폴더 안에 설치하고, 끝나면 다운로드 캐시를 비우고 워커 설정을 설치된 Python으로 바꿈. 마법사 "모델" 단계에서 진행·취소·다시 시도. 이 서버(Linux)에서 빈 폴더부터 전부 설치해 보고 그 런타임으로 서비스를 켜 워커 연결, 받아 적기·음성 준비까지 확인했고, 설치 중 데이터 폴더 밖에는 아무것도 쓰지 않음. 대화 모델(약 23GB)은 앱이 Strata를 직접 띄우는 다음 부분에서 받음. 4단계 뒷부분 완료(2026-11-12): 서비스를 켜면 앱이 먼저 데이터 폴더의 Strata를 띄움(`app/src/strata.rs`, M0와 같은 모델과 평소 배치, 처음 켤 때 대화 모델 약 23GB를 받음, 대시보드에 진행률과 Strata의 마지막 줄, 켜는 중에도 정지 가능, 서비스를 끄면 Strata도 끔). 동시 요청은 1개(모든 메시지에 답하는 채팅 채널이 있으면 2개), 그림 읽기는 v2에서 아직 쓰지 않아 끔. 시작할 때마다 두뇌 설정 `config/brain.json`(Strata 주소, Strata가 알려 준 모델 이름, 데이터 폴더 안의 기억 DB)을 써서 워커에 넘김. 이미 떠 있는 서버를 쓰려면 설정 파일의 `llm.url`. 확인: 가짜 Strata로 진행률·준비·정지·다운로드 중 취소·실패를 단위 시험, 게임PC의 Strata 0.1.59가 앱의 실행 옵션을 그대로 받아들임(`--plan`), 앱 서비스를 `llm.url`로 게임PC Strata에 붙여 실제 디스코드 왕복 10개 모두 소리로 답함. 앱이 Strata를 직접 띄워 모델을 받는 실제 확인은 이 서버에서 할 수 없어(메모리) Windows 빌드 단계에서 게임PC로 함. 5단계 완료(2026-11-12): Tauri 2 창 `app/shell`(`jarvis.exe`, 화면의 명령을 같은 `AdminApi`로 넘김, 창을 닫으면 서비스와 Strata를 끄고 끝날 때까지 기다림, 창의 브라우저 자료는 위치 기억 파일 옆)과 Windows 빌드 `app/shell/package.sh`(이 서버에서 `x86_64-pc-windows-gnu`로 빌드, `Jarvis/` 폴더에 실행 파일·WebView2Loader.dll·Python 소스 `python-src`, zip 11MB). 시험용 Windows VM에서: 창과 마법사, PC 점검, uv·워커 환경 설치, 설치 취소 뒤 남은 프로세스 없음, 봇 토큰 DPAPI 암호화 저장, 시작 실패 이유 표시, 로그 화면·오류 복사·zip, 창 닫기로 종료, %APPDATA%·%LOCALAPPDATA%에 아무것도 안 남김, 앱 핵심 단위 테스트(Windows 빌드) 통과. 게임PC(RTX 5070 Ti, C:\JarvisM0 안에서만)에서 같은 관리 명령으로: 전체 설치 7단계 6분 40초, 앱이 직접 띄운 Strata가 엔진과 대화 모델 22.9GB를 약 6분에 받고 준비, 워커(GPU 받아 적기·음성) 연결, 디스코드 음성 채널 입장, 시험 봇이 말한 질문 5개에 모두 소리로 답함(앱이 잰 전체 중앙값 3.36초, 처음 질문 6.4초, 날씨 11.6초), 정지 8초에 GPU 메모리 반환. 같은 시험에서 찾아 고친 것: Windows는 닫힌 로컬 포트의 연결 거부가 약 2초 늦어 정지 확인이 실패로 나오던 것, Strata가 모델 크기(`X of Y GB`)로만 진행을 알려 진행률이 앞 단계의 80%에 멈춰 있던 것, Strata와 NVIDIA 셰이더 캐시가 %APPDATA%에 쓰던 것(데이터 폴더로). 마무리(2026-11-12): 채팅 채널 이름·주제 반영 `app/src/channel_sync.rs`(채널마다 "디스코드에도 반영", 기본 켜짐; 등록하면 디스코드의 이름·주제로 채움, 저장하면 바뀐 채널만 디스코드에 반영하고 디스코드가 바꾼 이름(공백은 `-`)을 화면에 다시 보여 줌, 주제 1,024자 초과는 저장 전에 거절, 10분에 2번 제한에 걸리면 "잠시 뒤 반영" 후 디스코드가 알려 준 시간 뒤 마지막 저장값으로 저절로 다시 시도, 권한이 없으면 이유를 보여 주고 앱에만 저장). 실제 디스코드 시험 채널에서 채움·반영·제한(587초 대기)·자동 재시도까지 확인 후 채널 삭제. 모델 화면에 TTS 말하기 속도(MeloTTS, 0.5~2.0, 기본 1.5; 한국어 모델은 목소리가 KR 하나뿐이라 목소리 선택은 없음). 창을 닫을 때 설치 중이면 취소하고 끝날 때까지 기다림, 정리를 확인하지 못하면 창을 닫지 않고 이유를 보여 줌(한 번 더 닫으면 종료), 실패한 실행이 남긴 Strata도 정리. 창의 WebView 자료는 데이터 폴더(`cache/webview`), 폴더를 고르기 전에는 임시 폴더에 두었다가 다음 시작 때 지움(`%APPDATA%\JarvisBot`에는 위치 파일 하나만). Windows의 UTF-8 옵션이 꺼진 PC의 CP949 출력도 끝까지 읽음. VM에서 다시 확인: 설치 중 창 닫기 뒤 남은 프로세스 없음, `--location` 없이 실행 시 위치 파일 하나만, Windows용 단위 테스트 168개 통과. 게임PC에서 UTF-8 옵션을 끈 상태(코드 페이지 949)로 다시 확인: 전체 설치 7단계, Strata의 대화 모델 22.9GB 다운로드(진행률 10.9%→90%로 표시)와 준비, 워커·디스코드 연결, 시험 봇 질문 5개 모두 소리로 답함(앱이 잰 전체 중앙값 4.0초), 정지 7초에 GPU 메모리 반환, 로그 485줄에 깨진 글자 없음. 남은 것: 설치 파일(NSIS), Strata가 VRAM을 거의 다 써서(15.8/16.3GB) 받아 적기와 GPU를 나누는 문제(M0의 STT 자리 남기기 배치, M7 성능 단계와 함께) | -| M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인 | +| M6 | 기능 화면과 브라우저 | 기능 켜기/끄기, MCP 관리, 봇용 크롬(가상 모니터에 둠, Virtual Display Driver 포함), 예약 수집 틀(대상은 비움). 디스코드 "화면" 탭 공유, 커서, 모니터 해제 때 창 위치 확인. 1단계 완료(2026-11-13): 관리 앱 "기능" 화면(`app/src/features.rs`, 스펙 [admin.spec.md](../../app/src/admin.spec.md) "Features and MCP servers"). 날씨·웹 검색·식단 기록 켜기/끄기(끄면 그 도구는 두뇌가 제안하지도 실행하지도 않음, 모델이 이름을 대도, 도구 찾기 도구로도 안 나옴), MCP 서버 추가·삭제·켜기/끄기(이름, 명령, 인자, 환경 변수 이름). API 키 같은 환경 변수 값은 암호화 저장소에만 두고 화면에는 저장 여부만, 로그에서는 가림, 서버를 지우면 값도 지움. 앱이 켤 때 값을 워커 환경으로만 넘기고 두뇌는 그 변수를 자기 환경에서 빼서 각 서버에 자기 값만 줌. 서버마다 연결 결과(도구 수, 실패 이유)는 디버그 없이도 LLM 로그 탭에 남음. 같은 작업에서 v2 두뇌가 v1의 PC 파일 도구(홈 폴더 읽기·쓰기·지우기)와 화면 캡처 도구를 쓰던 것을 뺌(음성·채팅 채널의 누구든 요청할 수 있었음, 화면 보기는 M7에서 권한과 함께). 이 서버에서 확인: 개발용 서버의 브라우저로 날씨를 끄고 MCP 서버(시험용 서버)와 키를 저장, 실제 서비스를 켜니 `brain.json`에 끈 도구와 서버만 있고 키는 없음, 워커가 "MCP server fake: 1 tool(s)"를 남기고 MCP 서버 프로세스만 키를 받음, 로그·설정 파일에 키 없음, 정지 때 MCP 서버도 꺼짐. 남은 것: 봇용 크롬과 가상 모니터, 예약 수집 틀, 나머지 기능 스위치(브라우저 제어·PC 제어·화면 보기·백그라운드 수집, 각 기능과 함께) | | M7 | PC 제어와 화면 보기 | 아래 목록에 있습니다. | | M8 | 배포 | 설치 파일, 자동 업데이트, 깨끗한 Windows에서 설치부터 첫 대화까지 확인 | diff --git a/src/jarvis/config.py b/src/jarvis/config.py index 51db433..43457f9 100644 --- a/src/jarvis/config.py +++ b/src/jarvis/config.py @@ -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, ) diff --git a/src/jarvis/reply/engine.py b/src/jarvis/reply/engine.py index 67255e6..1da788d 100644 --- a/src/jarvis/reply/engine.py +++ b/src/jarvis/reply/engine.py @@ -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): diff --git a/src/jarvis/reply/reply.spec.md b/src/jarvis/reply/reply.spec.md index 8ee9fef..ca2f857 100644 --- a/src/jarvis/reply/reply.spec.md +++ b/src/jarvis/reply/reply.spec.md @@ -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. diff --git a/src/jarvis/tools/builtin/tool_search.py b/src/jarvis/tools/builtin/tool_search.py index ffa7445..4a4b003 100644 --- a/src/jarvis/tools/builtin/tool_search.py +++ b/src/jarvis/tools/builtin/tool_search.py @@ -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", ""), diff --git a/src/jarvis/tools/builtin/tool_search.spec.md b/src/jarvis/tools/builtin/tool_search.spec.md index 46e1f1c..69f381e 100644 --- a/src/jarvis/tools/builtin/tool_search.spec.md +++ b/src/jarvis/tools/builtin/tool_search.spec.md @@ -16,7 +16,7 @@ Before each reply, `select_tools` runs once outside the loop and narrows the too allow-list = + 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 diff --git a/src/jarvis/tools/registry.py b/src/jarvis/tools/registry.py index 9b5d7fb..a6e8fe1 100644 --- a/src/jarvis/tools/registry.py +++ b/src/jarvis/tools/registry.py @@ -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( diff --git a/src/voice_worker/brain.py b/src/voice_worker/brain.py index 40887d1..c4bdc14 100644 --- a/src/voice_worker/brain.py +++ b/src/voice_worker/brain.py @@ -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 diff --git a/src/voice_worker/log.py b/src/voice_worker/log.py index 03ed144..5136084 100644 --- a/src/voice_worker/log.py +++ b/src/voice_worker/log.py @@ -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 diff --git a/src/voice_worker/voice_worker.spec.md b/src/voice_worker/voice_worker.spec.md index 2d80d4a..22b1156 100644 --- a/src/voice_worker/voice_worker.spec.md +++ b/src/voice_worker/voice_worker.spec.md @@ -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 : 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 intent judge's tool pick for it on its own thread, with the asker's dialogue memory and the tool diff --git a/tests/test_v2_features.py b/tests/test_v2_features.py new file mode 100644 index 0000000..1aaabc1 --- /dev/null +++ b/tests/test_v2_features.py @@ -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()