feat(app): features screen with tool switches and MCP servers; v2 drops host file and screen tools

- Settings `features` (weather, webSearch, meals) and `mcpServers` (name, command, args, env names,
  enabled), edited on the new 기능 screen. The tools of a feature that is off go into the brain's
  `disabled_tools`; only enabled MCP servers go into its `mcps`.
- MCP environment values (API keys) live only in the encrypted secrets (`mcp:<server>:<NAME>`),
  shown as stored or not, masked in logs, removed with their server, and reach the worker only in
  `JARVIS_MCP_ENV`, which the brain takes out of its environment before giving each server its own.
- `enabled_builtin_tools(cfg)` is the one list the router, toolSearchTool and the executor use, so
  a turned-off tool is neither offered nor run, also when the model names it.
- The v2 brain never offers v1's `localFiles` (home folder read/write/delete) and `screenshot`:
  anyone in the voice or chat channels could ask for them. Screen viewing comes in M7.
- The brain connects MCP servers on its own thread and logs each outcome without debug logging.
- Stored secrets are masked in the log hub as soon as the data folder is found.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
javis-bot
2026-11-13 09:56:17 +09:00
parent d4bd4acfe9
commit 3ef4281180
23 changed files with 717 additions and 39 deletions

View File

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

View File

@@ -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
View 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")]);
}
}

View File

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

View File

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

View File

@@ -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()),

View File

@@ -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();

View File

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

View File

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