Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent-cli): add and manage MCP servers from CLI and TUI (#8678)

Akarshan Biswas8a602009f019
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index 2f4e3c8f7..4378c2412 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -228,6 +228,50 @@ jan cli models list
This includes providers inherited from Jan Desktop, so it can list models even when
`jan config list` shows none of its own.
+## `jan cli mcp`
+
+Manage Model Context Protocol servers in the shared `mcp_config.json` -- the same store Jan
+Desktop and the interactive console read. Servers you add or enable here are available in both.
+
+The desktop-only `Jan Browser MCP` bridge is never listed or editable from the CLI.
+
+```bash
+jan cli mcp list # JSON, env/header values redacted
+jan cli mcp list --show-secrets # include secret values
+jan cli mcp get <NAME> # one server's full config
+jan cli mcp add <NAME> --command npx --arg -y --arg my-mcp
+jan cli mcp remove <NAME>
+jan cli mcp enable <NAME> # connect on the next session
+jan cli mcp disable <NAME>
+```
+
+A stdio server needs a command and optional args; an `http`/`sse` server needs a URL.
+
+```bash
+# stdio (the default transport)
+jan cli mcp add files --command npx --arg -y --arg @modelcontextprotocol/server-filesystem \
+ --env FOO=bar
+
+# http, with a header and marked active immediately
+jan cli mcp add exa --type http --url https://mcp.exa.ai/mcp --header Authorization=Bearer-secret \
+ --active
+```
+
+| `add` flag | Description |
+| --- | --- |
+| `--command <CMD>` | Command for a stdio server (e.g. `npx`, `uvx`). Required for stdio |
+| `--arg <ARG>` | Argument for the command. Repeatable |
+| `--env KEY=VALUE` | Environment variable for a stdio server. Repeatable |
+| `--type <TYPE>` | Transport: `stdio` (default), `http`, or `sse` |
+| `--url <URL>` | URL for an `http`/`sse` server. Required unless stdio |
+| `--header KEY=VALUE` | Header for an `http`/`sse` server. Repeatable |
+| `--active` | Mark the server active immediately. Defaults to inactive |
+
+Adding a server that already exists replaces it (an edit); its `active` flag is preserved. Newly
+added servers default to inactive, so they are persisted but not connected until you `enable` them.
+
+See [MCP](/docs/agent/mcp).
+
## `jan update`
Update the binary to the latest build of the channel it was built for.
diff --git a/docs/src/pages/docs/agent/mcp.mdx b/docs/src/pages/docs/agent/mcp.mdx
index ba5b1b209..eb8217f9f 100644
--- a/docs/src/pages/docs/agent/mcp.mdx
+++ b/docs/src/pages/docs/agent/mcp.mdx
@@ -34,7 +34,9 @@ The first turn waits for the connecting servers, so the model sees the full tool
half-connected one. A slow stdio server delays that first turn, not the whole session.
</Callout>
-## Toggling servers
+## Managing servers
+
+### In the console
```
/mcp
@@ -43,8 +45,23 @@ half-connected one. A slow stdio server delays that first turn, not the whole se
Lists every configured server with its state. <kbd>Enter</kbd> toggles the highlighted one. Turning
one on connects it in the background; the tools appear once it lands.
+While the picker is open you can also manage the list itself:
+
+- <kbd>a</kbd> opens an add form (`name`, transport, then the transport-specific fields)
+- <kbd>e</kbd> edits the highlighted server, prefilled
+- <kbd>d</kbd> removes the highlighted server after writing it out
+
+A newly added server defaults to inactive, so it is persisted but not connected until you toggle
+it on.
+
The change is written back to `mcp_config.json`, so it persists - and applies to Jan Desktop too.
+### From the command line
+
+Add, list, edit, remove, and toggle servers headlessly with `jan cli mcp ...` - `jan cli mcp add
+files --command npx --arg -y --arg my-mcp`, `jan cli mcp list`, `jan cli mcp remove files`. See the
+[CLI reference](/docs/agent/cli#jan-cli-mcp).
+
## Tool policy
MCP tools follow the project's [`[tools]` policy](/docs/agent/permissions#project-policy):
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index d17fb47a3..575f2b263 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -40,7 +40,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-
| Command | Description |
| --- | --- |
| `/model [id]` | Switch model. Bare: pick interactively |
-| `/mcp` | Enable or disable MCP servers |
+| `/mcp` | List, toggle, add, edit, and remove MCP servers |
| `/login` | Sign in to Tokamak and save the API key |
| `/config` | View provider config (`~/.jan/config.toml`) |
| `/settings [max_parallel_subagents N]` | Edit `agent.toml` settings in an interactive menu - `[agent]` knobs (`context_window`, `compaction_reserve_tokens`, `max_tokens`, `max_parallel_subagents`, `instructions_file`), `[budget]` limits, and the `[tools]` / `[skills]` toggles (Enter edits a row, `x` resets to default, Esc cancels, clearing the field unsets). `max_parallel_subagents N` works as a one-shot shortcut. Writes apply on the next run |
diff --git a/src-tauri/src/bin/jan.rs b/src-tauri/src/bin/jan.rs
index 65314f128..a5b0aa70e 100644
--- a/src-tauri/src/bin/jan.rs
+++ b/src-tauri/src/bin/jan.rs
@@ -10,6 +10,7 @@ use console::Style;
// Import the library crate so we can access core modules.
// The lib target is named "app_lib" (see [lib] section in Cargo.toml).
use app_lib::core::cli::providers::{load_provider_configs, ProviderOverrides};
+use app_lib::core::cli::mcp::{self, split_kv, McpServerEntry};
use app_lib::core::cli::run_report::OutputFormat;
use app_lib::core::cli::{
cli_agent_config_list, cli_agent_config_path, cli_agent_config_set, cli_agent_config_unset,
@@ -41,6 +42,8 @@ to opt out of both.",
jan cli agent run \"fix the failing test\" # run the agent non-interactively\n \
jan cli models list # show every configured provider model\n \
jan cli threads list # list saved conversation threads\n \
+ jan cli mcp list # list configured MCP servers\n \
+ jan cli mcp add my-server --command npx --arg -y --arg my-mcp \n \
jan update # install the latest build of this channel"
)]
struct Cli {
@@ -192,6 +195,12 @@ enum CliCommands {
#[command(subcommand)]
cmd: AgentCommands,
},
+ /// List and manage MCP servers in mcp_config.json
+ #[command(display_order = 13)]
+ Mcp {
+ #[command(subcommand)]
+ cmd: McpCommands,
+ },
}
// ── Agent subcommands ──────────────────────────────────────────────────────
@@ -350,6 +359,67 @@ enum ModelsCommands {
},
}
+// ── MCP subcommands ────────────────────────────────────────────────────────
+
+/// Manage MCP servers in the shared <jan_data>/mcp_config.json, the same store
+/// the desktop app and the TUI `/mcp` picker read. Every command is headless
+/// and persists across runs.
+#[derive(Subcommand)]
+enum McpCommands {
+ /// List every configured server as JSON, excluding the desktop-only browser bridge
+ List {
+ /// Show env/header values (they may contain secrets); redacted by default
+ #[arg(long)]
+ show_secrets: bool,
+ },
+ /// Print a single server's full config as JSON
+ Get {
+ /// Server name
+ name: String,
+ },
+ /// Add a server, or replace an existing one with the same name (edit)
+ Add {
+ /// Server name (the key in mcpServers)
+ name: String,
+ /// Command for a stdio server (e.g. npx, uvx)
+ #[arg(long)]
+ command: Option<String>,
+ /// Argument for the command, repeatable
+ #[arg(long = "arg", allow_hyphen_values = true)]
+ args: Vec<String>,
+ /// Environment variable KEY=VALUE for a stdio server, repeatable
+ #[arg(long = "env")]
+ env: Vec<String>,
+ /// Transport type: stdio (default), http, or sse
+ #[arg(long, default_value = "stdio")]
+ r#type: String,
+ /// URL for an http/sse server (required unless stdio)
+ #[arg(long)]
+ url: Option<String>,
+ /// Header KEY=VALUE for an http/sse server, repeatable
+ #[arg(long = "header")]
+ header: Vec<String>,
+ /// Mark the server active immediately; defaults to inactive
+ #[arg(long)]
+ active: bool,
+ },
+ /// Remove a server entry from mcp_config.json
+ Remove {
+ /// Server name
+ name: String,
+ },
+ /// Mark a server active (so the next session connects it)
+ Enable {
+ /// Server name
+ name: String,
+ },
+ /// Mark a server inactive
+ Disable {
+ /// Server name
+ name: String,
+ },
+}
+
// ── ASCII logo ─────────────────────────────────────────────────────────────
/// Build a left-aligned, bright-yellow ASCII logo for the help header.
@@ -486,6 +556,12 @@ async fn handle_cli(cmd: CliCommands) {
CliCommands::Threads { cmd } => handle_threads(cmd).await,
CliCommands::Models { cmd } => handle_models(cmd).await,
CliCommands::Agent { cmd } => handle_agent(cmd).await,
+ CliCommands::Mcp { cmd } => {
+ if let Err(e) = handle_mcp(cmd) {
+ eprintln!("Error: {e}");
+ std::process::exit(1);
+ }
+ }
}
}
@@ -670,6 +746,130 @@ async fn handle_models(cmd: ModelsCommands) {
}
}
+/// Render one server entry for `list`: transport summary plus (redacted by
+/// default) env/header keys. Secret values are masked unless `--show-secrets`.
+fn mcp_list_entry(entry: &McpServerEntry, show_secrets: bool) -> serde_json::Value {
+ let cfg = &entry.config;
+ let transport_type = cfg.get("type").and_then(serde_json::Value::as_str);
+ let redact = |v: &serde_json::Value| -> serde_json::Value {
+ if show_secrets {
+ v.clone()
+ } else {
+ serde_json::Value::String("<redacted>".to_string())
+ }
+ };
+ let redact_map = |m: Option<&serde_json::Map<String, serde_json::Value>>| -> serde_json::Value {
+ match m {
+ Some(map) => {
+ let out: serde_json::Map<String, serde_json::Value> = map
+ .iter()
+ .map(|(k, v)| (k.clone(), redact(v)))
+ .collect();
+ serde_json::Value::Object(out)
+ }
+ None => serde_json::json!({}),
+ }
+ };
+ serde_json::json!({
+ "name": entry.name,
+ "active": entry.active,
+ "type": transport_type.unwrap_or("stdio"),
+ "command": cfg.get("command").and_then(serde_json::Value::as_str).unwrap_or(""),
+ "args": cfg.get("args").cloned().unwrap_or_else(|| serde_json::json!([])),
+ "url": cfg.get("url").cloned().unwrap_or(serde_json::Value::Null),
+ "env": redact_map(cfg.get("env").and_then(serde_json::Value::as_object)),
+ "headers": redact_map(cfg.get("headers").and_then(serde_json::Value::as_object)),
+ })
+}
+
+/// Manage MCP servers in mcp_config.json.
+fn handle_mcp(cmd: McpCommands) -> Result<(), String> {
+ match cmd {
+ McpCommands::List { show_secrets } => {
+ let servers = mcp::list_servers();
+ let out: Vec<serde_json::Value> = servers
+ .iter()
+ .map(|s| mcp_list_entry(s, show_secrets))
+ .collect();
+ println!("{}", serde_json::to_string_pretty(&out).unwrap());
+ Ok(())
+ }
+ McpCommands::Get { name } => match mcp::get_server(&name) {
+ Some(entry) => {
+ println!(
+ "{}",
+ serde_json::to_string_pretty(&mcp_list_entry(&entry, true)).unwrap()
+ );
+ Ok(())
+ }
+ None => Err(format!("server '{name}' not found")),
+ },
+ McpCommands::Add {
+ name,
+ command,
+ args,
+ env,
+ r#type,
+ url,
+ header,
+ active,
+ } => {
+ let config = build_mcp_config(command, args, env, &r#type, url, header, active)?;
+ mcp::upsert_server(&name, &config)?;
+ println!("saved server '{name}' to mcp_config.json");
+ Ok(())
+ }
+ McpCommands::Remove { name } => {
+ mcp::remove_server(&name)?;
+ println!("removed server '{name}' from mcp_config.json");
+ Ok(())
+ }
+ McpCommands::Enable { name } => {
+ mcp::set_active(&name, true)?;
+ println!("enabled server '{name}'");
+ Ok(())
+ }
+ McpCommands::Disable { name } => {
+ mcp::set_active(&name, false)?;
+ println!("disabled server '{name}'");
+ Ok(())
+ }
+ }
+}
+
+/// Build the server config object for `mcp add` from the CLI flags. Funnels
+/// through the shared `core::cli::mcp::build_server_config` so the TUI form and
+/// the headless flags can never diverge on the config shape or validation.
+fn build_mcp_config(
+ command: Option<String>,
+ args: Vec<String>,
+ env: Vec<String>,
+ r#type: &str,
+ url: Option<String>,
+ header: Vec<String>,
+ active: bool,
+) -> Result<serde_json::Value, String> {
+ let mut env_map = serde_json::Map::new();
+ for kv in &env {
+ let (k, v) = split_kv(kv, "env")?;
+ env_map.insert(k, serde_json::json!(v));
+ }
+ let mut header_map = serde_json::Map::new();
+ for kv in &header {
+ let (k, v) = split_kv(kv, "header")?;
+ header_map.insert(k, serde_json::json!(v));
+ }
+ mcp::build_server_config(
+ r#type,
+ command.as_deref(),
+ args,
+ env_map,
+ url.as_deref(),
+ header_map,
+ active,
+ )
+}
+
#[cfg(test)]
mod tests {
use super::*;
@@ -757,4 +957,95 @@ mod tests {
assert!(matches!(cli.command, Some(Commands::Login)));
assert!(Cli::try_parse_from(["jan", "login", "sk-key"]).is_err());
}
+
+ /// Parse a `jan cli mcp <cmd> <extra...>` argv and pull out the subcommand.
+ fn parsed_mcp(extra: &[&str]) -> McpCommands {
+ let mut argv = vec!["jan", "cli", "mcp"];
+ argv.extend_from_slice(extra);
+ match Cli::parse_from(argv).command {
+ Some(Commands::Cli { cmd: CliCommands::Mcp { cmd } }) => cmd,
+ _ => panic!("expected `cli mcp`"),
+ }
+ }
+
+ #[test]
+ fn mcp_list_parses_and_redacts_by_default() {
+ let cmd = parsed_mcp(&["list"]);
+ assert!(matches!(cmd, McpCommands::List { show_secrets: false }));
+ let cmd = parsed_mcp(&["list", "--show-secrets"]);
+ assert!(matches!(cmd, McpCommands::List { show_secrets: true }));
+ }
+
+ #[test]
+ fn mcp_add_parses_stdio_fields() {
+ let cmd = parsed_mcp(&[
+ "add",
+ "files",
+ "--command",
+ "npx",
+ "--arg",
+ "-y",
+ "--arg",
+ "my-mcp",
+ "--env",
+ "K=V",
+ "--active",
+ ]);
+ match cmd {
+ McpCommands::Add {
+ name,
+ command,
+ args,
+ env,
+ r#type,
+ url,
+ header,
+ active,
+ } => {
+ assert_eq!(name, "files");
+ assert_eq!(command.as_deref(), Some("npx"));
+ assert_eq!(args, vec!["-y", "my-mcp"]);
+ assert_eq!(env, vec!["K=V"]);
+ assert_eq!(r#type, "stdio");
+ assert!(url.is_none());
+ assert!(header.is_empty());
+ assert!(active);
+ }
+ _ => panic!("expected add"),
+ }
+ }
+
+ #[test]
+ fn mcp_build_rejects_http_without_url() {
+ let err = build_mcp_config(None, vec![], vec![], "http", None, vec![], false).unwrap_err();
+ assert!(err.contains("url"), "{err}");
+ let err = build_mcp_config(None, vec![], vec![], "sse", None, vec![], false).unwrap_err();
+ assert!(err.contains("url"), "{err}");
+ assert!(build_mcp_config(None, vec![], vec![], "bogus", None, vec![], false).is_err());
+ // stdio needs a command.
+ assert!(build_mcp_config(None, vec![], vec![], "stdio", None, vec![], false).is_err());
+ }
+
+ #[test]
+ fn mcp_remove_enable_disable_take_one_name() {
+ assert!(matches!(
+ parsed_mcp(&["remove", "files"]),
+ McpCommands::Remove { name } if name == "files"
+ ));
+ assert!(matches!(
+ parsed_mcp(&["enable", "files"]),
+ McpCommands::Enable { name } if name == "files"
+ ));
+ assert!(matches!(
+ parsed_mcp(&["disable", "files"]),
+ McpCommands::Disable { name } if name == "files"
+ ));
+ }
+
+ #[test]
+ fn split_kv_rejects_without_separator() {
+ assert_eq!(split_kv("K=V", "env").unwrap(), ("K".to_string(), "V".to_string()));
+ assert!(split_kv("novalue", "env").is_err());
+ assert!(split_kv("=V", "header").is_err());
+ }
}
diff --git a/src-tauri/src/core/cli/mcp.rs b/src-tauri/src/core/cli/mcp.rs
index cffcb2ad2..8fb956f70 100644
--- a/src-tauri/src/core/cli/mcp.rs
+++ b/src-tauri/src/core/cli/mcp.rs
@@ -39,20 +39,61 @@ pub struct McpServerEntry {
pub config: Value,
}
-fn config_path() -> PathBuf {
- resolve_jan_data_folder().join("mcp_config.json")
+/// Resolve the config path under a data folder. `data_folder` is threaded
+/// through the internal helpers so tests can point at a tempdir without a global
+/// override; the public API uses the real Jan data folder via
+/// `resolve_jan_data_folder()`.
+fn config_path(data_folder: &std::path::Path) -> PathBuf {
+ data_folder.join("mcp_config.json")
}
-fn read_config() -> Value {
- match std::fs::read_to_string(config_path()) {
+/// The real Jan data folder (the env override in `resolve_jan_data_folder`
+/// applies, so a `JAN_DATA_FOLDER` redirect still works end to end).
+fn default_data_folder() -> PathBuf {
+ resolve_jan_data_folder()
+}
+
+fn read_config(data_folder: &std::path::Path) -> Value {
+ match std::fs::read_to_string(config_path(data_folder)) {
Ok(s) if !s.trim().is_empty() => serde_json::from_str(&s).unwrap_or(Value::Null),
_ => Value::Null,
}
}
+/// Atomically persist a full `mcp_config.json` document (tmp + rename), the
+/// same idiom `set_active` already uses. `mcpServers`/`mcpSettings` keys are
+/// ensured so a caller passing a bare servers object still writes a valid doc.
+fn write_config(data_folder: &std::path::Path, cfg: &Value) -> Result<(), String> {
+ let path = config_path(data_folder);
+ let mut doc = if cfg.is_object() {
+ cfg.clone()
+ } else {
+ serde_json::json!({})
+ };
+ let obj = doc.as_object_mut().ok_or("mcp_config is not an object")?;
+ obj.entry("mcpServers").or_insert_with(|| serde_json::json!({}));
+ obj.entry("mcpSettings").or_insert_with(|| serde_json::json!({}));
+
+ let body = serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())?;
+ let tmp = path.with_extension("json.tmp");
+ std::fs::write(&tmp, body).map_err(|e| e.to_string())?;
+ std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
+ Ok(())
+}
+
+/// Read the `mcpServers` object as a mutable map, defaulting to an empty one.
+fn servers_map_mut(cfg: &mut Value) -> &mut serde_json::Map<String, Value> {
+ cfg.as_object_mut()
+ .unwrap()
+ .entry("mcpServers")
+ .or_insert_with(|| serde_json::json!({}))
+ .as_object_mut()
+ .expect("mcpServers is an object")
+}
+
/// Parsed `mcpSettings` block (tool-call timeout etc.), defaults when absent.
pub fn read_settings() -> McpSettings {
- read_config()
+ read_config(&default_data_folder())
.get("mcpSettings")
.cloned()
.and_then(|v| serde_json::from_value(v).ok())
@@ -62,7 +103,12 @@ pub fn read_settings() -> McpSettings {
/// All configured servers (excluding the desktop-only browser bridge), sorted by
/// name so the picker order is stable.
pub fn list_servers() -> Vec<McpServerEntry> {
- let cfg = read_config();
+ list_servers_in(&default_data_folder())
+}
+
+/// `list_servers` against an explicit data folder (used by tests).
+pub fn list_servers_in(data_folder: &std::path::Path) -> Vec<McpServerEntry> {
+ let cfg = read_config(data_folder);
let Some(servers) = cfg.get("mcpServers").and_then(Value::as_object) else {
return Vec::new();
};
@@ -82,19 +128,15 @@ pub fn list_servers() -> Vec<McpServerEntry> {
/// Persist a server's `active` flag back to `mcp_config.json` (pretty-printed,
/// atomic tmp+rename) so the choice survives across CLI sessions.
pub fn set_active(name: &str, active: bool) -> Result<(), String> {
- let path = config_path();
- let mut cfg = read_config();
+ set_active_in(&default_data_folder(), name, active)
+}
+
+fn set_active_in(data_folder: &std::path::Path, name: &str, active: bool) -> Result<(), String> {
+ let mut cfg = read_config(data_folder);
if !cfg.is_object() {
cfg = serde_json::json!({});
}
- let servers = cfg
- .as_object_mut()
- .unwrap()
- .entry("mcpServers")
- .or_insert_with(|| serde_json::json!({}));
- let entry = servers
- .as_object_mut()
- .ok_or("mcpServers is not an object")?
+ let entry = servers_map_mut(&mut cfg)
.get_mut(name)
.ok_or_else(|| format!("server '{name}' not found in mcp_config.json"))?;
entry
@@ -102,13 +144,194 @@ pub fn set_active(name: &str, active: bool) -> Result<(), String> {
.ok_or_else(|| format!("config for '{name}' is not an object"))?
.insert("active".to_string(), Value::Bool(active));
- let body = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?;
- let tmp = path.with_extension("json.tmp");
- std::fs::write(&tmp, body).map_err(|e| e.to_string())?;
- std::fs::rename(&tmp, &path).map_err(|e| e.to_string())?;
+ write_config(data_folder, &cfg)
+}
+
+/// Validate a server entry shape, reporting the missing field rather than the
+/// generic "invalid MCP config" a connect would otherwise surface. Matches the
+/// desktop's transport contract: `command`+`args` for stdio, or `type`+`url`
+/// for http/sse.
+pub fn validate_config(config: &Value) -> Result<(), String> {
+ let obj = config
+ .as_object()
+ .ok_or_else(|| "server config must be a JSON object".to_string())?;
+ let transport = obj
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or("stdio");
+ match transport {
+ "http" | "sse" => {
+ if obj.get("url").and_then(Value::as_str).is_none() {
+ return Err(format!("server of type '{transport}' needs a 'url'"));
+ }
+ }
+ "stdio" => {
+ if obj.get("command").and_then(Value::as_str).is_none() {
+ return Err("stdio server needs a 'command'".to_string());
+ }
+ if !obj.get("args").is_some_and(Value::is_array) {
+ return Err("stdio server needs an 'args' array (may be empty)".to_string());
+ }
+ }
+ other => {
+ return Err(format!(
+ "unknown transport '{other}' (expected stdio, http, or sse)"
+ ));
+ }
+ }
Ok(())
}
+/// Validate a server name: non-empty and not the desktop-only browser bridge.
+pub fn validate_server_name(name: &str) -> Result<(), String> {
+ if name.trim().is_empty() {
+ return Err("server name cannot be empty".to_string());
+ }
+ if name == BROWSER_MCP_NAME {
+ return Err(format!(
+ "'{name}' is the desktop-only browser bridge and cannot be edited from the CLI"
+ ));
+ }
+ Ok(())
+}
+
+/// Build a ready-to-persist server entry from typed fields, mirroring the
+/// desktop's transport contract. `env`/`headers` are already parsed maps; the
+/// callers (`jan cli mcp add` flags and the TUI form) both funnel through here
+/// so neither re-implements the shape or its validation.
+pub fn build_server_config(
+ transport: &str,
+ command: Option<&str>,
+ args: Vec<String>,
+ env: serde_json::Map<String, Value>,
+ url: Option<&str>,
+ headers: serde_json::Map<String, Value>,
+ active: bool,
+) -> Result<Value, String> {
+ let mut config = serde_json::json!({ "type": transport, "active": active });
+ match transport {
+ "stdio" => {
+ let command = command
+ .ok_or_else(|| "stdio server needs a 'command' (e.g. npx, uvx)".to_string())?;
+ config["command"] = Value::String(command.to_string());
+ config["args"] = serde_json::json!(args);
+ config["env"] = Value::Object(env);
+ }
+ "http" | "sse" => {
+ let url = url.ok_or_else(|| format!("server of type '{transport}' needs a 'url'"))?;
+ config["url"] = Value::String(url.to_string());
+ if !headers.is_empty() {
+ config["headers"] = Value::Object(headers);
+ }
+ }
+ other => {
+ return Err(format!(
+ "unknown transport '{other}' (expected stdio, http, or sse)"
+ ));
+ }
+ }
+ validate_config(&config)?;
+ Ok(config)
+}
+
+/// Add or replace a server entry (by name) in `mcp_config.json`, preserving any
+/// existing `active` and other keys when the name is already present. Does not
+/// touch the live connection -- the caller decides whether to connect.
+pub fn upsert_server(name: &str, config: &Value) -> Result<(), String> {
+ upsert_server_in(&default_data_folder(), name, config)
+}
+
+fn upsert_server_in(
+ data_folder: &std::path::Path,
+ name: &str,
+ config: &Value,
+) -> Result<(), String> {
+ validate_server_name(name)?;
+ validate_config(config)?;
+ let mut cfg = read_config(data_folder);
+ if !cfg.is_object() {
+ cfg = serde_json::json!({});
+ }
+ let servers = servers_map_mut(&mut cfg);
+ let existing_active = servers.get(name).and_then(|c| c.get("active")).cloned();
+ let mut entry = config.clone();
+ // Preserve the previous active flag on edit unless the new config sets one,
+ // so editing a server never silently disables it.
+ if entry.get("active").is_none() {
+ if let Some(active) = existing_active {
+ entry["active"] = active;
+ }
+ }
+ servers.insert(name.to_string(), entry);
+ write_config(data_folder, &cfg)
+}
+
+/// Remove a server entry by name from `mcp_config.json`. Errors if absent. Does
+/// not disconnect a live transport -- the caller decides.
+pub fn remove_server(name: &str) -> Result<(), String> {
+ remove_server_in(&default_data_folder(), name)
+}
+
+fn remove_server_in(data_folder: &std::path::Path, name: &str) -> Result<(), String> {
+ validate_server_name(name)?;
+ let mut cfg = read_config(data_folder);
+ if !cfg.is_object() {
+ cfg = serde_json::json!({});
+ }
+ let removed = servers_map_mut(&mut cfg).remove(name).is_some();
+ if !removed {
+ return Err(format!("server '{name}' not found in mcp_config.json"));
+ }
+ write_config(data_folder, &cfg)
+}
+
+/// Read one server entry by name (excluding the browser bridge), `None` when
+/// absent. Used by the edit path to prefill a form.
+pub fn get_server(name: &str) -> Option<McpServerEntry> {
+ get_server_in(&default_data_folder(), name)
+}
+
+fn get_server_in(data_folder: &std::path::Path, name: &str) -> Option<McpServerEntry> {
+ let cfg = read_config(data_folder);
+ let servers = cfg.get("mcpServers")?.as_object()?;
+ let config = servers.get(name)?;
+ if name == BROWSER_MCP_NAME {
+ return None;
+ }
+ Some(McpServerEntry {
+ name: name.to_string(),
+ active: extract_active_status(config).unwrap_or(false),
+ config: config.clone(),
+ })
+}
+
+/// Split a `KEY=VALUE` pair, rejecting anything without a separator or an empty
+/// key. Shared by the headless `jan cli mcp add` flags and the TUI add/edit form
+/// so the two surfaces parse `--env`/`--header` identically.
+pub fn split_kv(kv: &str, what: &str) -> Result<(String, String), String> {
+ match kv.split_once('=') {
+ Some((k, v)) if !k.trim().is_empty() => Ok((k.trim().to_string(), v.to_string())),
+ _ => Err(format!("--{what} must be KEY=VALUE, got '{kv}'")),
+ }
+}
+
+/// Parse a whitespace-separated argument string into a list, trimming empty
+/// runs. No shell quoting: the TUI form takes plain, already-split arguments.
+pub fn parse_args(s: &str) -> Vec<String> {
+ s.split_whitespace().map(str::to_string).collect()
+}
+
+/// Parse comma-separated `KEY=VALUE` pairs into a JSON object map. Empty input
+/// yields an empty map; a malformed pair surfaces the first error.
+pub fn parse_pairs(s: &str, what: &str) -> Result<serde_json::Map<String, Value>, String> {
+ let mut map = serde_json::Map::new();
+ for part in s.split(',').map(str::trim).filter(|p| !p.is_empty()) {
+ let (k, v) = split_kv(part, what)?;
+ map.insert(k, Value::String(v));
+ }
+ Ok(map)
+}
+
/// Connect one server and insert it into the shared map. Best-effort: a bad
/// transport/config returns `Err` without touching the map.
pub async fn connect(
@@ -279,6 +502,174 @@ pub async fn connect_active(servers: &SharedMcpServers) -> ConnectOutcome {
mod tests {
use super::*;
+ /// A temporary data folder with a fresh config path, cleaned up on drop.
+ fn temp_data() -> tempfile::TempDir {
+ tempfile::tempdir().expect("tempdir")
+ }
+
+ #[test]
+ fn upsert_creates_and_preserves_active_on_edit() {
+ let data = temp_data();
+ let folder = data.path();
+ let cfg = serde_json::json!({
+ "command": "npx",
+ "args": ["-y", "server"],
+ });
+ upsert_server_in(folder, "files", &cfg).unwrap();
+
+ let entry = get_server_in(folder, "files").unwrap();
+ assert_eq!(entry.name, "files");
+ assert!(!entry.active);
+
+ // Mark active, then edit again: active must survive.
+ set_active_in(folder, "files", true).unwrap();
+ upsert_server_in(
+ folder,
+ "files",
+ &serde_json::json!({
+ "command": "npx",
+ "args": ["-y", "server2"],
+ }),
+ )
+ .unwrap();
+ let entry = get_server_in(folder, "files").unwrap();
+ assert!(entry.active, "editing must not clear the active flag");
+ assert_eq!(entry.config["args"][1], "server2");
+ }
+
+ #[test]
+ fn upsert_rejects_bad_shape_and_browser_name() {
+ let data = temp_data();
+ let folder = data.path();
+ // Missing command.
+ assert!(upsert_server_in(folder, "x", &serde_json::json!({ "args": [] })).is_err());
+ // Missing args.
+ assert!(
+ upsert_server_in(folder, "x", &serde_json::json!({ "command": "npx" })).is_err()
+ );
+ // Unknown transport.
+ assert!(
+ upsert_server_in(
+ folder,
+ "x",
+ &serde_json::json!({ "type": "bogus", "url": "http://x" })
+ )
+ .is_err()
+ );
+ // Desktop-only browser bridge.
+ assert!(
+ upsert_server_in(
+ folder,
+ BROWSER_MCP_NAME,
+ &serde_json::json!({ "command": "npx", "args": [] })
+ )
+ .is_err()
+ );
+ }
+
+ #[test]
+ fn http_and_sse_validate_by_url() {
+ let data = temp_data();
+ let folder = data.path();
+ let http = serde_json::json!({ "type": "http", "url": "https://x/mcp" });
+ assert!(validate_config(&http).is_ok());
+ upsert_server_in(folder, "http", &http).unwrap();
+
+ let sse_no_url = serde_json::json!({ "type": "sse" });
+ let err = validate_config(&sse_no_url).unwrap_err();
+ assert!(err.contains("url"), "{err}");
+ assert!(upsert_server_in(folder, "sse", &sse_no_url).is_err());
+ }
+
+ #[test]
+ fn remove_deletes_and_errors_when_absent() {
+ let data = temp_data();
+ let folder = data.path();
+ upsert_server_in(
+ folder,
+ "files",
+ &serde_json::json!({ "command": "npx", "args": [] }),
+ )
+ .unwrap();
+ remove_server_in(folder, "files").unwrap();
+ assert!(get_server_in(folder, "files").is_none());
+
+ let err = remove_server_in(folder, "files").unwrap_err();
+ assert!(err.contains("not found"), "{err}");
+ }
+
+ #[test]
+ fn write_config_ensures_top_level_keys() {
+ let data = temp_data();
+ let folder = data.path();
+ // A caller passing a bare servers object still gets a valid doc.
+ write_config(folder, &serde_json::json!({ "mcpServers": {} })).unwrap();
+ let raw = std::fs::read_to_string(config_path(folder)).unwrap();
+ let doc: serde_json::Value = serde_json::from_str(&raw).unwrap();
+ assert!(doc.get("mcpServers").is_some());
+ assert!(doc.get("mcpSettings").is_some());
+ }
+
+ #[test]
+ fn list_filters_browser_and_orders_by_name() {
+ let data = temp_data();
+ let folder = data.path();
+ upsert_server_in(
+ folder,
+ "zeta",
+ &serde_json::json!({ "command": "npx", "args": [] }),
+ )
+ .unwrap();
+ upsert_server_in(
+ folder,
+ "alpha",
+ &serde_json::json!({ "command": "npx", "args": [] }),
+ )
+ .unwrap();
+ write_config(
+ folder,
+ &serde_json::json!({
+ "mcpServers": {
+ "zeta": { "command": "npx", "args": [] },
+ "alpha": { "command": "npx", "args": [] },
+ }
+ }),
+ )
+ .and_then(|_| {
+ // Seed the browser bridge directly (upsert refuses it).
+ let mut cfg = read_config(folder);
+ servers_map_mut(&mut cfg).insert(
+ BROWSER_MCP_NAME.to_string(),
+ serde_json::json!({ "command": "npx", "args": [] }),
+ );
+ write_config(folder, &cfg)
+ })
+ .unwrap();
+
+ let names: Vec<String> = list_servers_in(folder)
+ .into_iter()
+ .map(|s| s.name)
+ .collect();
+ assert_eq!(names, vec!["alpha", "zeta"]);
+ }
+
+ #[test]
+ fn split_kv_and_parse_pairs() {
+ assert_eq!(
+ split_kv("K=V", "env").unwrap(),
+ ("K".to_string(), "V".to_string())
+ );
+ assert!(split_kv("novalue", "env").is_err());
+ assert!(split_kv("=V", "header").is_err());
+
+ let map = parse_pairs("A=1,B=2", "env").unwrap();
+ assert_eq!(map.get("A").and_then(Value::as_str), Some("1"));
+ assert_eq!(map.get("B").and_then(Value::as_str), Some("2"));
+ assert!(parse_pairs("A=1,broken", "env").is_err());
+ assert!(parse_pairs("", "env").unwrap().is_empty());
+ assert_eq!(parse_args("npx -y my-mcp"), vec!["npx", "-y", "my-mcp"]);
+ }
+
#[test]
fn browser_mcp_excluded_and_sorted() {
// list_servers reads the real data folder; assert only invariants that
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index bdc4b0390..c4010eac2 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -41,7 +41,9 @@ use markdown::{
use super::brand;
use super::journal::{self, DisplayEntry};
+use super::mcp::McpServerEntry;
use super::{sort_threads_recent, AgentSession, ResumeTarget, SessionLimits};
+use serde_json::Value;
use crate::core::agent::events::{describe_tool_call, StreamEvent, Usage};
use crate::core::agent::git;
use crate::core::agent::r#loop::{run_orchestration_streamed, OrchestrationArgs, PermissionRegistry};
@@ -330,7 +332,7 @@ impl Picker {
match self.kind {
PickerKind::ResumeThread => " ↑/↓ select Enter resume Esc cancel",
PickerKind::SelectModel => " ↑/↓ select Enter choose Esc cancel",
- PickerKind::ToggleMcp => " ↑/↓ select Enter toggle Esc close",
+ PickerKind::ToggleMcp => " ↑/↓ select Enter toggle a add e edit d delete Esc close",
PickerKind::RewindMessage => " ↑/↓ select Enter choose Esc cancel",
PickerKind::RewindScope => " ↑/↓ select Enter restore Esc cancel",
PickerKind::ViewConfig => " set via: jan config set --provider <id> ... Esc close",
@@ -1172,6 +1174,8 @@ struct App {
/// keyboard while open. Holds the setting being edited and any validation
/// error; writes go straight to agent.toml on Enter.
settings_prompt: Option<SettingsPrompt>,
+ /// Active MCP add/edit wizard (docked); owns the keyboard while open.
+ mcp_prompt: Option<McpPrompt>,
/// Key handed off to the loop to verify off the render loop. Taken once.
login_submit: Option<String>,
/// `/update` handed off to the loop, which spawns the install. Taken once.
@@ -1471,6 +1475,7 @@ impl App {
picker: None,
login: None,
settings_prompt: None,
+ mcp_prompt: None,
login_submit: None,
update_requested: false,
update_installing: false,
@@ -5424,6 +5429,12 @@ async fn handle_key(
return;
}
+ // The MCP add/edit wizard owns the keyboard while open.
+ if app.mcp_prompt.is_some() {
+ handle_mcp_prompt_key(app, key, ctrl, mcp_servers).await;
+ return;
+ }
+
// A pending permission prompt captures y/a/n; Ctrl-C cancels the run and
// Ctrl-D quits, so it can't be wedged waiting on an unanswered prompt.
// Several subagents can have requests queued at once (see `pending_queue`),
@@ -5502,6 +5513,45 @@ async fn handle_key(
item.checkbox = Some(enable);
toggle_mcp_server(app, mcp_servers, name, enable);
}
+ // `/mcp` picker: `a` opens the add wizard, `e` opens the edit
+ // wizard prefilled from the selected row, `d` removes it after a
+ // confirmation keystroke. All act through the shared config layer.
+ KeyCode::Char('a') if picker.kind == PickerKind::ToggleMcp => {
+ app.picker = None;
+ app.mcp_prompt = Some(McpPrompt {
+ editing: None,
+ field: McpField::Name,
+ name: String::new(),
+ transport: "stdio".to_string(),
+ command: String::new(),
+ args: String::new(),
+ env: String::new(),
+ url: String::new(),
+ headers: String::new(),
+ active: false,
+ error: None,
+ });
+ }
+ KeyCode::Char('e') if picker.kind == PickerKind::ToggleMcp => {
+ let name = picker.items[picker.selected].value.clone();
+ let entry = super::mcp::get_server(&name);
+ if let Some(entry) = entry {
+ app.picker = None;
+ app.mcp_prompt = Some(McpPrompt::from_entry(&entry));
+ } else {
+ app.note(&format!("server '{name}' no longer exists"));
+ }
+ }
+ KeyCode::Char('d') if picker.kind == PickerKind::ToggleMcp => {
+ let name = picker.items[picker.selected].value.clone();
+ app.picker = None;
+ if let Err(e) = super::mcp::remove_server(&name) {
+ app.note(&format!("failed to remove '{name}': {e}"));
+ } else {
+ super::mcp::disconnect(&name, mcp_servers).await;
+ app.note(&format!("removed MCP server '{name}'"));
+ }
+ }
// `/todo` editor: d/Enter = done, x = abandon (drop), r = remove.
// Each mutates the canonical list and rebuilds the overlay in place;
// opening/closing the view itself never mutates state.
@@ -5848,7 +5898,7 @@ const SLASH_COMMANDS: &[SlashCommand] = &[
SlashCommand {
name: "/mcp",
hint: "",
- description: "Enable/disable MCP servers",
+ description: "List, add, edit, remove, or toggle MCP servers",
},
SlashCommand {
name: "/cancel",
@@ -6270,6 +6320,187 @@ impl SettingsPrompt {
}
}
+/// A docked multi-field wizard for adding or editing an MCP server. Collects
+/// the fields the desktop form also asks for (name, transport, then the
+/// transport-specific bits), validating on save through the shared
+/// `core::cli::mcp` layer. `edit` mode prefills from the existing entry and
+/// defaults `name` to it; `add` mode starts blank.
+struct McpPrompt {
+ /// `Some(original_name)` when editing; `None` when adding a new server.
+ editing: Option<String>,
+ /// Which field the keyboard is currently filling in.
+ field: McpField,
+ name: String,
+ transport: String,
+ command: String,
+ args: String,
+ env: String,
+ url: String,
+ headers: String,
+ active: bool,
+ error: Option<String>,
+}
+
+/// The fields of `McpPrompt`, in input order. `Transport` is a toggle row
+/// rather than a free-text field, so it is navigated but not typed.
+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
+enum McpField {
+ Name,
+ Transport,
+ Command,
+ Args,
+ Env,
+ Url,
+ Headers,
+ Active,
+}
+
+impl McpPrompt {
+ const FIELD_ORDER: [McpField; 8] = [
+ McpField::Name,
+ McpField::Transport,
+ McpField::Command,
+ McpField::Args,
+ McpField::Env,
+ McpField::Url,
+ McpField::Headers,
+ McpField::Active,
+ ];
+
+ /// The fields relevant to the current transport, in input order. stdio
+ /// servers never ask for url/headers; http/sse never ask for command/args.
+ fn visible_fields(&self) -> Vec<McpField> {
+ let transport = self.transport.as_str();
+ Self::FIELD_ORDER
+ .iter()
+ .copied()
+ .filter(|f| match f {
+ McpField::Command | McpField::Args | McpField::Env => transport == "stdio",
+ McpField::Url | McpField::Headers => transport != "stdio",
+ _ => true,
+ })
+ .collect()
+ }
+
+ fn next_field(&mut self) {
+ let fields = self.visible_fields();
+ let pos = fields
+ .iter()
+ .position(|f| *f == self.field)
+ .unwrap_or(usize::MAX);
+ if pos + 1 < fields.len() {
+ self.field = fields[pos + 1];
+ } else {
+ self.field = fields[0];
+ }
+ }
+
+ fn prev_field(&mut self) {
+ let fields = self.visible_fields();
+ let pos = fields
+ .iter()
+ .position(|f| *f == self.field)
+ .unwrap_or(0);
+ self.field = fields[if pos == 0 { fields.len() - 1 } else { pos - 1 }];
+ }
+
+ fn from_entry(entry: &McpServerEntry) -> Self {
+ let cfg = &entry.config;
+ let transport = cfg
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or("stdio")
+ .to_string();
+ let env = pairs_to_str(cfg.get("env").and_then(Value::as_object));
+ let headers = pairs_to_str(cfg.get("headers").and_then(Value::as_object));
+ Self {
+ editing: Some(entry.name.clone()),
+ field: McpField::Name,
+ name: entry.name.clone(),
+ transport: transport.clone(),
+ command: cfg
+ .get("command")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
+ args: cfg
+ .get("args")
+ .and_then(Value::as_array)
+ .map(|a| {
+ a.iter()
+ .filter_map(Value::as_str)
+ .collect::<Vec<_>>()
+ .join(" ")
+ })
+ .unwrap_or_default(),
+ env,
+ url: cfg
+ .get("url")
+ .and_then(Value::as_str)
+ .unwrap_or("")
+ .to_string(),
+ headers,
+ active: entry.active,
+ error: None,
+ }
+ }
+
+ /// Build and persist the entry, then (dis)connect live as needed.
+ /// Returns an error string on invalid input so the caller can keep the
+ /// prompt open with the reason shown.
+ async fn save(
+ &mut self,
+ mcp_servers: &crate::core::state::SharedMcpServers,
+ ) -> Result<(), String> {
+ let config = super::mcp::build_server_config(
+ self.transport.trim(),
+ Some(self.command.trim()).filter(|s| !s.is_empty()),
+ super::mcp::parse_args(self.args.trim()),
+ super::mcp::parse_pairs(self.env.trim(), "env")?,
+ Some(self.url.trim()).filter(|s| !s.is_empty()),
+ super::mcp::parse_pairs(self.headers.trim(), "header")?,
+ self.active,
+ )?;
+ super::mcp::upsert_server(self.name.trim(), &config)?;
+ let name = self.name.trim().to_string();
+ let was_active = self.editing.as_deref().is_some_and(|n| {
+ super::mcp::get_server(n).is_some_and(|e| e.active)
+ });
+ // Disconnect the old live service on rename/edit, then reconnect if active.
+ if let Some(old) = self.editing.take() {
+ if old != name {
+ super::mcp::disconnect(&old, mcp_servers).await;
+ }
+ }
+ if self.active {
+ let cfg = super::mcp::list_servers()
+ .into_iter()
+ .find(|s| s.name == name)
+ .map(|s| s.config);
+ if let Some(cfg) = cfg {
+ if let Err(e) = super::mcp::connect(&name, &cfg, mcp_servers).await {
+ log::warn!("MCP: {e}");
+ }
+ }
+ } else if was_active {
+ super::mcp::disconnect(&name, mcp_servers).await;
+ }
+ Ok(())
+ }
+}
+
+/// Render a `KEY=VALUE` map as a comma-separated string, for pre-filling the
+/// form fields (the inverse of `parse_pairs`).
+fn pairs_to_str(map: Option<&serde_json::Map<String, Value>>) -> String {
+ map.map(|m| {
+ m.iter()
+ .filter_map(|(k, v)| v.as_str().map(|v| format!("{k}={v}")))
+ .collect::<Vec<_>>()
+ .join(",")
+ })
+ .unwrap_or_default()
+}
+
/// Value of an `[agent]` key in `agent.toml` as a display string, `None` when
/// unset or the file is unreadable. Reads the inner value directly so the
/// display is not padded by the document's alignment.
@@ -6363,8 +6594,7 @@ fn open_settings_screen(app: &mut App) {
/// Keyboard for the `/settings` edit dock: chars/backspace edit the field,
/// Enter validates and writes (empty clears the key), Esc cancels. Mirrors
/// `handle_login_key`, minus the secret/verify machinery.
-fn handle_settings_key(app: &mut App, key: KeyEvent, ctrl: bool) {
- if (key.code == KeyCode::Esc || (ctrl && key.code == KeyCode::Char('c'))) && app.settings_prompt.is_some()
+fn handle_settings_key(app: &mut App, key: KeyEvent, ctrl: bool) { if (key.code == KeyCode::Esc || (ctrl && key.code == KeyCode::Char('c'))) && app.settings_prompt.is_some()
{
app.settings_prompt = None;
return;
@@ -6449,6 +6679,83 @@ fn handle_settings_key(app: &mut App, key: KeyEvent, ctrl: bool) {
}
}
+/// Keyboard for the MCP add/edit wizard: Up/Down move between fields, chars/
+/// backspace edit the current text field, Space toggles the transport/active
+/// rows, Enter saves and connects, Esc cancels.
+#[allow(clippy::too_many_lines)]
+async fn handle_mcp_prompt_key(
+ app: &mut App,
+ key: KeyEvent,
+ ctrl: bool,
+ mcp_servers: &crate::core::state::SharedMcpServers,
+) {
+ if (key.code == KeyCode::Esc || (ctrl && key.code == KeyCode::Char('c')))
+ && app.mcp_prompt.is_some()
+ {
+ app.mcp_prompt = None;
+ return;
+ }
+ let Some(prompt) = app.mcp_prompt.as_mut() else {
+ return;
+ };
+ match key.code {
+ KeyCode::Up | KeyCode::Char('k') => prompt.prev_field(),
+ KeyCode::Down | KeyCode::Char('j') => prompt.next_field(),
+ KeyCode::Tab => prompt.next_field(),
+ KeyCode::Enter => {
+ // Take the prompt out so `save` can borrow `app` freely for notes
+ // and put it back on error.
+ let mut taken = app.mcp_prompt.take().expect("prompt is Some");
+ match taken.save(mcp_servers).await {
+ Ok(()) => {
+ let name = taken.name.trim().to_string();
+ app.note(&format!("saved MCP server '{name}'"));
+ }
+ Err(e) => {
+ taken.error = Some(e);
+ app.mcp_prompt = Some(taken);
+ }
+ }
+ }
+ KeyCode::Char(' ') | KeyCode::Left | KeyCode::Right => {
+ match prompt.field {
+ McpField::Transport => {
+ prompt.transport = if prompt.transport == "stdio" {
+ "http".to_string()
+ } else {
+ "stdio".to_string()
+ };
+ // Reset to a valid field for the new transport.
+ prompt.field = prompt.visible_fields()[0];
+ }
+ McpField::Active => prompt.active = !prompt.active,
+ _ => {}
+ }
+ }
+ KeyCode::Backspace => match prompt.field {
+ McpField::Name => { prompt.name.pop(); }
+ McpField::Command => { prompt.command.pop(); }
+ McpField::Args => { prompt.args.pop(); }
+ McpField::Env => { prompt.env.pop(); }
+ McpField::Url => { prompt.url.pop(); }
+ McpField::Headers => { prompt.headers.pop(); }
+ _ => {}
+ },
+ KeyCode::Char(ch) if !ctrl => {
+ match prompt.field {
+ McpField::Name => prompt.name.push(ch),
+ McpField::Command => prompt.command.push(ch),
+ McpField::Args => prompt.args.push(ch),
+ McpField::Env => prompt.env.push(ch),
+ McpField::Url => prompt.url.push(ch),
+ McpField::Headers => prompt.headers.push(ch),
+ _ => {}
+ }
+ }
+ _ => {}
+ }
+}
+
/// `/plan` dispatcher: bare enters read-only plan mode, `/plan exit` leaves
/// it, and `/plan <text>` enters plan mode (if not already in it) and
/// immediately submits `<text>` as the first message to investigate — same
@@ -6828,11 +7135,12 @@ fn open_model_picker(app: &mut App) {
}
/// Open the `/mcp` picker listing configured MCP servers with their enabled
-/// state. Enter toggles a row in place (see `toggle_mcp_server`).
+/// state. Enter toggles a row in place (see `toggle_mcp_server`); `a` adds, `e`
+/// edits, and `d` removes (see the picker key handler).
fn open_mcp_picker(app: &mut App) {
let servers = super::mcp::list_servers();
if servers.is_empty() {
- return app.note("no MCP servers configured (add them in the desktop app or mcp_config.json)");
+ return app.note("no MCP servers configured (press a to add one, or use `jan cli mcp add ...`)");
}
let items = servers
.into_iter()
@@ -7960,6 +8268,17 @@ fn draw(f: &mut Frame, app: &mut App) {
};
let toml_path = app.agent_dir.join("agent.toml");
draw_settings_prompt(f, rect, prompt, &toml_path);
+ } else if let Some(prompt) = &app.mcp_prompt {
+ let height = prompt.visible_fields().len() as u16 + 3;
+ let height = height.min(chunks[1].height);
+ let y = chunks[2].y.saturating_sub(height).max(chunks[1].y);
+ let rect = ratatui::layout::Rect {
+ x: chunks[2].x,
+ y,
+ width: chunks[2].width,
+ height,
+ };
+ draw_mcp_prompt(f, rect, prompt);
} else if !app.ask_queue.is_empty() {
let queue_len = app.ask_queue.len();
let ask = app.ask_queue.front_mut().expect("checked non-empty above");
@@ -8270,7 +8589,70 @@ fn draw_settings_prompt(
f.render_widget(Paragraph::new(lines), inner);
}
-/// Slash-command hint popup: one row per match (`/name [hint] description`),
+/// Dock the MCP add/edit wizard above the input: one row per visible field,
+/// the active field highlighted, with a toggle marker on transport/active.
+fn draw_mcp_prompt(f: &mut Frame, area: ratatui::layout::Rect, prompt: &McpPrompt) {
+ use ratatui::widgets::Clear;
+
+ let dim = Style::new().dark_gray();
+ let title = if prompt.editing.is_some() {
+ " mcp server: edit "
+ } else {
+ " mcp server: add "
+ };
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .border_style(Style::new().cyan())
+ .title(Span::styled(title, Style::new().on_cyan().black().bold()));
+
+ let mut lines = Vec::new();
+ for field in prompt.visible_fields() {
+ let selected = field == prompt.field;
+ let (label, value, toggle) = match field {
+ McpField::Name => ("name", prompt.name.as_str(), None),
+ McpField::Transport => ("type", prompt.transport.as_str(), Some(prompt.transport.as_str())),
+ McpField::Command => ("command", prompt.command.as_str(), None),
+ McpField::Args => ("args", prompt.args.as_str(), None),
+ McpField::Env => ("env", prompt.env.as_str(), None),
+ McpField::Url => ("url", prompt.url.as_str(), None),
+ McpField::Headers => ("headers", prompt.headers.as_str(), None),
+ McpField::Active => {
+ ("active", if prompt.active { "yes" } else { "no" }, Some(if prompt.active { "yes" } else { "no" }))
+ }
+ };
+ let marker = if selected { "› " } else { " " };
+ let style = if selected {
+ Style::new().bold()
+ } else {
+ dim
+ };
+ let mut spans = vec![
+ Span::styled(format!("{marker}{label}: "), style),
+ ];
+ if let Some(toggle) = toggle {
+ spans.push(Span::styled(toggle.to_string(), if selected { Style::new().cyan() } else { dim }));
+ } else {
+ spans.push(Span::styled(value.to_string(), style));
+ if selected {
+ spans.push(Span::styled("█", Style::new().cyan()));
+ }
+ }
+ lines.push(Line::from(spans));
+ }
+ if let Some(error) = &prompt.error {
+ lines.push(Line::styled(error.clone(), Style::new().red()));
+ }
+ lines.push(Line::styled(
+ "↑/↓ move · Enter save · Space toggle · Esc cancel".to_string(),
+ dim,
+ ));
+
+ f.render_widget(Clear, area);
+ let inner = block.inner(area);
+ f.render_widget(block, area);
+ f.render_widget(Paragraph::new(lines), inner);
+}
+
/// the highlighted row reversed. Docked above the input box.
fn draw_slash_hints(
f: &mut Frame,
@@ -9361,6 +9743,7 @@ mod tests {
estimate_token_count, header_spans, status_panel, SubagentPanel,
note_update, open_config_screen, spawn_branch_poll, await_branch_poll,
parse_command, partial_json_field, restore_goal, restore_run_mode, restore_todos,
+ McpPrompt, McpField, pairs_to_str,
autoscroll_selection, selection_text, Selection, SelectionMode, COPY_NOTICE,
run_command, starting_call_lines, unescape_partial_json_string,
running_group_row, split_reasoning, strip_system_xml_tags, subagent_activity,
@@ -11915,6 +12298,65 @@ mod tests {
let _ = std::fs::remove_dir_all(&app.agent_dir);
}
+ #[test]
+ fn mcp_prompt_visible_fields_follow_transport() {
+ let mut p = McpPrompt {
+ editing: None,
+ field: McpField::Name,
+ name: String::new(),
+ transport: "stdio".to_string(),
+ command: String::new(),
+ args: String::new(),
+ env: String::new(),
+ url: String::new(),
+ headers: String::new(),
+ active: false,
+ error: None,
+ };
+ assert!(p.visible_fields().contains(&McpField::Command));
+ assert!(!p.visible_fields().contains(&McpField::Url));
+
+ p.transport = "http".to_string();
+ assert!(!p.visible_fields().contains(&McpField::Command));
+ assert!(p.visible_fields().contains(&McpField::Url));
+ assert!(p.visible_fields().contains(&McpField::Headers));
+ }
+
+ #[test]
+ fn mcp_prompt_next_prev_wrap_and_skip_hidden() {
+ let mut p = McpPrompt {
+ editing: None,
+ field: McpField::Name,
+ name: String::new(),
+ transport: "stdio".to_string(),
+ command: String::new(),
+ args: String::new(),
+ env: String::new(),
+ url: String::new(),
+ headers: String::new(),
+ active: false,
+ error: None,
+ };
+ // From Name forward skips url/headers (stdio).
+ p.next_field();
+ assert_eq!(p.field, McpField::Transport);
+ p.next_field();
+ assert_eq!(p.field, McpField::Command);
+ // Prev wraps from the last field back to the first.
+ p.field = McpField::Active;
+ p.next_field();
+ assert_eq!(p.field, McpField::Name);
+ p.prev_field();
+ assert_eq!(p.field, McpField::Active);
+ }
+
+ #[test]
+ fn pairs_to_str_roundtrips() {
+ let map = crate::core::cli::mcp::parse_pairs("A=1,B=2", "env").unwrap();
+ assert_eq!(pairs_to_str(Some(&map)), "A=1,B=2");
+ assert_eq!(pairs_to_str(None), "");
+ }
+
#[test]
fn settings_prompt_edits_enum_key() {
let mut app = test_app();