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.

51.1 KB
Raw Blame
//! AppHandle-free MCP client for the CLI agent.
//!
//! The desktop activation stack (`core/mcp/helpers.rs`) is generic over a Tauri
//! `AppHandle` (data-folder lookup, `AppState`, event emit, bundled `bun`/`uv`
//! rewriting, health-monitor tasks). The CLI has no `AppHandle`, so this module
//! provides a focused connector: it reads the same `<jan_data>/mcp_config.json`,
//! reuses the shared `extract_command_args`/`extract_active_status` parsers, and
//! connects http/sse/stdio transports directly into a `SharedMcpServers` map that
//! the agent loop already consumes. No bundled-runtime rewriting, no Jan Browser
//! MCP bridge, no auto-reconnect monitor -- the CLI relies on the user's PATH.

use std::future::Future;
use std::path::PathBuf;
use std::process::Stdio;

use rmcp::{
    model::{ClientCapabilities, ClientInfo, Implementation},
    transport::{
        streamable_http_client::{StreamableHttpClient, StreamableHttpClientTransportConfig},
        StreamableHttpClientTransport, TokioChildProcess,
    },
    ServiceExt,
};
use serde_json::Value;
use tokio::process::Command;

use crate::core::app::commands::resolve_jan_data_folder;
use crate::core::mcp::models::McpSettings;
use crate::core::mcp::models::{extract_active_status, extract_command_args, McpServerConfig};
use crate::core::mcp::identity;
use crate::core::mcp::oauth;
use crate::core::state::{RunningServiceEnum, SharedMcpServers};

use super::providers::ProviderOverrides;

/// The Jan Browser MCP needs the desktop bridge/lockfile machinery, so it is
/// never offered or connected from the CLI.
const BROWSER_MCP_NAME: &str = "Jan Browser MCP";

/// A configured server as read from `mcp_config.json`.
pub struct McpServerEntry {
    pub name: String,
    pub active: bool,
    pub config: Value,
}

/// 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")
}

/// 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())?;
    // A machine where the desktop app never ran has no data folder yet, and this
    // is the first thing to write there.
    if let Some(folder) = path.parent() {
        std::fs::create_dir_all(folder)
            .map_err(|e| format!("could not create {}: {e}", folder.display()))?;
    }
    let tmp = path.with_extension("json.tmp");
    let mut options = std::fs::OpenOptions::new();
    options.write(true).create(true).truncate(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600);
    }
    let mut file = options
        .open(&tmp)
        .map_err(|e| format!("could not write {}: {e}", tmp.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        file.set_permissions(std::fs::Permissions::from_mode(0o600))
            .map_err(|e| e.to_string())?;
    }
    // MCP env/header fields can contain keys entered during plugin setup.
    std::io::Write::write_all(&mut file, body.as_bytes()).map_err(|e| e.to_string())?;
    drop(file);
    std::fs::rename(&tmp, &path).map_err(|e| format!("could not save {}: {e}", path.display()))?;
    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_settings_in(&default_data_folder())
}

fn read_settings_in(data_folder: &std::path::Path) -> McpSettings {
    read_config(data_folder)
        .get("mcpSettings")
        .cloned()
        .and_then(|v| serde_json::from_value(v).ok())
        .unwrap_or_default()
}

/// All configured servers (excluding the desktop-only browser bridge), sorted by
/// name so the picker order is stable.
pub fn list_servers() -> Vec<McpServerEntry> {
    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();
    };
    let mut out: Vec<McpServerEntry> = servers
        .iter()
        .filter(|(name, _)| name.as_str() != BROWSER_MCP_NAME)
        .map(|(name, config)| McpServerEntry {
            name: name.clone(),
            active: extract_active_status(config).unwrap_or(false),
            config: config.clone(),
        })
        .collect();
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}

/// 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> {
    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 entry = servers_map_mut(&mut cfg)
        .get_mut(name)
        .ok_or_else(|| format!("server '{name}' not found in mcp_config.json"))?;
    entry
        .as_object_mut()
        .ok_or_else(|| format!("config for '{name}' is not an object"))?
        .insert("active".to_string(), Value::Bool(active));

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

/// Why a connect failed, when the difference changes what the user should do.
///
/// A missing binary and an unauthorized remote both surface as "failed to
/// connect" from the transport, but only one of them is fixed by signing in --
/// so the distinction is carried in the type rather than left for the UI to
/// guess from an error string.
#[derive(Debug)]
pub enum ConnectError {
    /// The server advertises OAuth and there are no usable credentials for it.
    /// `/mcp` turns this into an `Authenticate` action.
    NeedsAuth { server: String, detail: String },
    Failed(String),
}

impl std::fmt::Display for ConnectError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::NeedsAuth { server, detail } => {
                write!(f, "'{server}' needs authentication: {detail}")
            }
            Self::Failed(e) => f.write_str(e),
        }
    }
}

impl ConnectError {
    pub fn needs_auth(&self) -> bool {
        matches!(self, Self::NeedsAuth { .. })
    }
}

impl From<String> for ConnectError {
    fn from(e: String) -> Self {
        Self::Failed(e)
    }
}

/// Connect one server and insert it into the shared map. Best-effort: a bad
/// transport/config returns `Err` without touching the map.
///
/// For http/sse this is where OAuth is applied: stored credentials (refreshed
/// if stale) are wrapped around the base client so every request carries the
/// bearer token. When there are none and the connect fails, the server is asked
/// whether it advertises OAuth at all, which is what separates
/// `ConnectError::NeedsAuth` from an ordinary transport failure.
pub async fn connect(
    name: &str,
    config: &Value,
    servers: &SharedMcpServers,
) -> Result<(), ConnectError> {
    connect_in(&default_data_folder(), name, config, servers).await
}

async fn connect_in(
    data_folder: &std::path::Path,
    name: &str,
    config: &Value,
    servers: &SharedMcpServers,
) -> Result<(), ConnectError> {
    if name == BROWSER_MCP_NAME {
        return Err(ConnectError::Failed(
            "Jan Browser MCP is desktop-only".to_string(),
        ));
    }
    let params = extract_command_args(config)
        .ok_or_else(|| ConnectError::Failed(format!("invalid MCP config for '{name}'")))?;
    // Bounds how long a server may take to answer `initialize`, by the same
    // setting that bounds its tool calls: one that starts and never answers
    // would otherwise hold every agent run behind the connect.
    let handshake_timeout = read_settings_in(data_folder).tool_call_timeout_duration();

    let service = match (params.transport_type.as_deref(), params.url.as_deref()) {
        (Some(transport @ ("http" | "sse")), Some(url)) => {
            // One deadline for the whole attempt - the credentials, the handshake
            // and the OAuth probe that follows a failure - because a server that
            // stalls in any of them blocks the run the same way.
            let attempt = async {
                let base = http_client(&params.headers)?;
                // A credential problem we can already name (expired with no
                // refresh token, or issued for a different url) is `NeedsAuth`
                // outright -- there is no point attempting a connect we know is
                // unauthorized.
                let auth = oauth::authorized_client(data_folder, name, url, config, base.clone())
                    .await
                    .map_err(|detail| ConnectError::NeedsAuth {
                        server: name.to_string(),
                        detail,
                    })?;
                let authorized = auth.is_some();
                // rmcp 3.x dropped the SSE client transport (MCP deprecated
                // HTTP+SSE for Streamable HTTP), so a legacy `sse` config
                // connects over the streamable-http client instead.
                if transport == "sse" {
                    log::warn!(
                        "MCP server '{name}' uses the deprecated 'sse' transport; \
                         connecting over Streamable HTTP instead"
                    );
                }
                let result = match auth {
                    Some(client) => serve_http(client, url, name).await,
                    None => serve_http(base, url, name).await,
                };
                Ok::<_, ConnectError>(match result {
                    Ok(service) => service,
                    // Only worth probing when we did not already send a token: a
                    // failure *with* credentials is either a real outage or
                    // tokens the provider revoked, and `advertises_oauth` cannot
                    // tell the difference. Re-authenticating is offered from
                    // `/mcp` anyway.
                    Err(e) if !authorized && oauth::advertises_oauth(url).await => {
                        // The transport error is kept: a server can advertise
                        // OAuth *and* have failed for an unrelated reason, and
                        // dropping the cause would report that as "needs
                        // authentication".
                        return Err(ConnectError::NeedsAuth {
                            server: name.to_string(),
                            detail: format!("no credentials are stored ({e})"),
                        });
                    }
                    Err(e) => return Err(ConnectError::Failed(e)),
                })
            };
            match tokio::time::timeout(handshake_timeout, attempt).await {
                Ok(outcome) => outcome?,
                Err(_) => {
                    return Err(ConnectError::Failed(timed_out(name, handshake_timeout)));
                }
            }
        }
        _ => {
            let cmd = stdio_command(&params, &inherited_credentials());
            let (process, _stderr) = TokioChildProcess::builder(cmd)
                .stderr(Stdio::null())
                .spawn()
                .map_err(|e| ConnectError::Failed(format!("failed to spawn '{name}': {e}")))?;
            let pid = process.id();
            // A server that fails to start up, or never answers, is not left
            // behind with what it started: the tree is killed first (see
            // `bounded`), and the error is the one the caller reports.
            let handshake = bounded(name, handshake_timeout, ().serve(process), || {
                if let Some(pid) = pid {
                    kill_process_tree(pid);
                }
            });
            RunningServiceEnum::NoInit(handshake.await.map_err(ConnectError::Failed)?)
        }
    };

    identity::insert_server(&mut *servers.lock().await, name, service);
    Ok(())
}

/// A stdio server's command: its args, and this process's environment minus
/// `scrub`, with the server's own `env` entries set last so a server that
/// needs one of the scrubbed variables can still be given it by name.
fn stdio_command(params: &McpServerConfig, scrub: &[String]) -> Command {
    let mut cmd = Command::new(&params.command);
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
    }
    // Its own session: pgid == pid for `kill_process_tree`, and no controlling
    // terminal, so a server cannot take the TUI's terminal away from Jan.
    #[cfg(unix)]
    tauri_plugin_agent_tools::tools::proc::detach_from_terminal(&mut cmd);
    cmd.kill_on_drop(true);
    for arg in params.args.iter().filter_map(Value::as_str) {
        cmd.arg(arg);
    }
    for name in scrub {
        cmd.env_remove(name);
    }
    for (k, v) in params.envs.iter() {
        if let Some(v) = v.as_str() {
            cmd.env(k, v);
        }
    }
    cmd
}

/// The OTLP exporter's header variables. While Jan's own telemetry is on they
/// hold its collector credentials (a launcher puts its API key there).
const OTLP_HEADER_VARS: &[&str] = &[
    "OTEL_EXPORTER_OTLP_HEADERS",
    "OTEL_EXPORTER_OTLP_LOGS_HEADERS",
    "OTEL_EXPORTER_OTLP_METRICS_HEADERS",
    "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
];

/// The variables a stdio MCP server must not inherit from this session: the
/// credentials Jan was given to reach its own model gateway and collector.
fn inherited_credentials() -> Vec<String> {
    credential_vars(
        ProviderOverrides::session().explicit_provider_name(),
        crate::core::agent::otel::is_active(),
    )
}

/// Deliberately narrow. `JAN_API_KEY`, the explicit `--provider`'s own
/// `<PROVIDER>_API_KEY` and `JAN_CUSTOM_HEADERS` only ever address Jan's
/// gateway. A Desktop-selected provider's variable (`OPENAI_API_KEY`, ...) is
/// left alone, because servers commonly read those for themselves, and so are
/// the OTLP header variables while Jan exports nothing: they are then the
/// user's, for a server that exports to its own collector.
fn credential_vars(explicit_provider: Option<&str>, telemetry_on: bool) -> Vec<String> {
    let mut names = vec![
        "JAN_API_KEY".to_string(),
        super::providers::CUSTOM_HEADERS_ENV.to_string(),
    ];
    if let Some(provider) = explicit_provider {
        names.push(super::providers::provider_key_env(provider));
    }
    if telemetry_on {
        names.extend(OTLP_HEADER_VARS.iter().map(|v| v.to_string()));
    }
    names
}

/// What a server that never answers is reported as: the same `failed to connect
/// to '<name>'` as one that fails, so the caller treats both alike and the run
/// goes on without it.
fn timed_out(name: &str, timeout: std::time::Duration) -> String {
    format!(
        "failed to connect to '{name}': timed out after {}s waiting for it to answer",
        timeout.as_secs()
    )
}

/// Wait for a handshake no longer than `timeout`. On a timeout `cleanup` runs
/// before the handshake is dropped, while it still owns the child: a child that
/// is already gone cannot have its tree walked (`taskkill /T` follows parent
/// links from a live root). After a failure the handshake has already let go of
/// the child, so `cleanup` is best effort there.
async fn bounded<T, E: std::fmt::Display>(
    name: &str,
    timeout: std::time::Duration,
    handshake: impl Future<Output = Result<T, E>>,
    cleanup: impl FnOnce(),
) -> Result<T, String> {
    tokio::pin!(handshake);
    tokio::select! {
        result = &mut handshake => match result {
            Ok(service) => Ok(service),
            Err(e) => {
                cleanup();
                Err(format!("failed to connect to '{name}': {e}"))
            }
        },
        _ = tokio::time::sleep(timeout) => {
            cleanup();
            Err(timed_out(name, timeout))
        }
    }
}

/// Kill a stdio server and everything it started. The server was spawned as the
/// leader of its own process group, so its pid names the group.
fn kill_process_tree(pid: u32) {
    #[cfg(unix)]
    {
        use nix::sys::signal::{killpg, Signal};
        use nix::unistd::Pid;
        // Already gone is the common case and not a failure.
        let _ = killpg(Pid::from_raw(pid as i32), Signal::SIGKILL);
    }
    #[cfg(windows)]
    {
        use std::os::windows::process::CommandExt;
        let _ = std::process::Command::new(jan_utils::windows_system_tool("taskkill.exe"))
            .args(["/F", "/T", "/PID", &pid.to_string()])
            .creation_flags(0x08000000) // CREATE_NO_WINDOW
            .output();
    }
}

/// Serve the streamable-http transport over any client that implements it, so
/// the plain and OAuth-wrapped clients share one code path instead of the
/// transport construction being written out twice.
async fn serve_http<C>(client: C, url: &str, name: &str) -> Result<RunningServiceEnum, String>
where
    C: StreamableHttpClient + Send + Sync + 'static,
{
    let transport = StreamableHttpClientTransport::with_client(
        client,
        StreamableHttpClientTransportConfig::with_uri(url.to_string()),
    );
    Ok(RunningServiceEnum::WithInit(
        client_info()
            .serve(transport)
            .await
            .map_err(|e| format!("failed to connect to '{name}': {e}"))?,
    ))
}

fn client_info() -> ClientInfo {
    ClientInfo::new(
        ClientCapabilities::default(),
        Implementation::new("Jan CLI Client", "0.0.1"),
    )
}

/// Build a reqwest client that sends the configured `headers` on every request
/// (http auth). Non-string header names/values are skipped. Uses `reqwest13`
/// because rmcp's streamable-http transport is implemented for reqwest 0.13.
fn http_client(
    headers: &serde_json::Map<String, Value>,
) -> Result<reqwest13::Client, String> {
    let mut map = reqwest13::header::HeaderMap::new();
    for (key, value) in headers.iter() {
        if let Some(v) = value.as_str() {
            if let (Ok(name), Ok(val)) = (
                reqwest13::header::HeaderName::from_bytes(key.as_bytes()),
                reqwest13::header::HeaderValue::from_str(v),
            ) {
                map.insert(name, val);
            }
        }
    }
    reqwest13::Client::builder()
        .default_headers(map)
        .build()
        .map_err(|e| e.to_string())
}

/// Remove a server from the shared map and cancel its transport.
pub async fn disconnect(name: &str, servers: &SharedMcpServers) {
    let service = servers.lock().await.remove(name);
    match service {
        Some(RunningServiceEnum::NoInit(s)) => {
            let _ = s.cancel().await;
        }
        Some(RunningServiceEnum::WithInit(s)) => {
            let _ = s.cancel().await;
        }
        None => {}
    }
}

/// The `mcp_config.json` a server is declared in. Surfaced by the `/mcp` detail
/// screen: "where do I edit this by hand" is otherwise unanswerable from the UI.
pub fn config_file_path() -> PathBuf {
    config_path(&default_data_folder())
}

/// This server's OAuth state, without touching the network.
pub fn auth_status(name: &str, config: &Value) -> oauth::AuthStatus {
    oauth::status(&default_data_folder(), name, config)
}

/// Forget one server's stored tokens. `Ok(false)` when there were none.
pub fn clear_auth(name: &str) -> Result<bool, String> {
    oauth::clear(&default_data_folder(), name)
}

/// Start an interactive authorization for a configured http/sse server. The
/// caller owns opening the browser and awaiting `PendingAuth::complete`.
pub async fn begin_auth(name: &str) -> Result<oauth::PendingAuth, String> {
    let entry =
        get_server(name).ok_or_else(|| format!("server '{name}' not found in mcp_config.json"))?;
    let url = entry
        .config
        .get("url")
        .and_then(Value::as_str)
        .filter(|u| !u.trim().is_empty())
        .ok_or_else(|| {
            format!("'{name}' is a stdio server - OAuth applies to http/sse servers only")
        })?;
    oauth::begin(name, url).await
}

/// Finish an authorization by persisting the tokens it produced.
pub async fn finish_auth(pending: oauth::PendingAuth) -> Result<oauth::StoredCredentials, String> {
    pending.complete(&default_data_folder()).await
}

/// Everything the `/mcp` detail screen shows about one server. Split from the
/// tool list on purpose: all of this is local (config plus the cached
/// `initialize` response), so the screen opens without a round trip and the
/// tool list arrives separately.
pub struct ServerDetail {
    pub name: String,
    pub active: bool,
    pub connected: bool,
    pub transport: String,
    /// The url for http/sse, or `command args` for stdio.
    pub endpoint: String,
    pub config_path: PathBuf,
    pub auth: oauth::AuthStatus,
    /// Capability names the server advertised, in a stable display order.
    pub capabilities: Vec<&'static str>,
    /// `name version` from the server's `initialize` response, when connected.
    pub implementation: Option<String>,
}

/// Snapshot one server for the detail screen. `None` when the name is no longer
/// in the config (deleted from another surface while the picker was open).
pub async fn describe(name: &str, servers: &SharedMcpServers) -> Option<ServerDetail> {
    let entry = get_server(name)?;
    let cfg = &entry.config;
    let transport = cfg
        .get("type")
        .and_then(Value::as_str)
        .unwrap_or("stdio")
        .to_string();
    let endpoint = if transport == "stdio" {
        let command = cfg.get("command").and_then(Value::as_str).unwrap_or("");
        let args: Vec<&str> = cfg
            .get("args")
            .and_then(Value::as_array)
            .map(|a| a.iter().filter_map(Value::as_str).collect())
            .unwrap_or_default();
        if args.is_empty() {
            command.to_string()
        } else {
            format!("{command} {}", args.join(" "))
        }
    } else {
        cfg.get("url").and_then(Value::as_str).unwrap_or("").to_string()
    };

    // The lock is held only for the cached `initialize` response; nothing here
    // goes to the network, so the render loop is never parked on a peer.
    let peer = servers.lock().await.get(name).and_then(|s| s.peer_info());
    let connected = peer.is_some();
    let mut capabilities = Vec::new();
    let mut implementation = None;
    if let Some(peer) = peer {
        let caps = &peer.capabilities;
        for (present, label) in [
            (caps.tools.is_some(), "tools"),
            (caps.resources.is_some(), "resources"),
            (caps.prompts.is_some(), "prompts"),
            (caps.logging.is_some(), "logging"),
            (caps.completions.is_some(), "completions"),
        ] {
            if present {
                capabilities.push(label);
            }
        }
        implementation = peer
            .server_info
            .as_ref()
            .map(|si| format!("{} {}", si.name, si.version));
    }

    Some(ServerDetail {
        auth: auth_status(name, cfg),
        name: entry.name,
        active: entry.active,
        connected,
        transport,
        endpoint,
        config_path: config_file_path(),
        capabilities,
        implementation,
    })
}

/// The tool names a connected server exposes, for the detail screen's `Tools:`
/// line and its `View tools` action. `Err` when the server is not connected or
/// the listing round trip fails.
///
/// This is the one part of the detail screen that talks to the peer, which is
/// why it is a separate call: the caller runs it off the render loop.
///
/// The round trip is bounded by `tool_call_timeout_duration`, as every other
/// `list_all_tools` call site is: the guard is the process-wide server map that
/// each agent turn also locks, so a peer that accepts the request and never
/// answers would otherwise stall turns and not just this screen.
pub async fn list_tools(name: &str, servers: &SharedMcpServers) -> Result<Vec<String>, String> {
    let timeout_duration = read_settings().tool_call_timeout_duration();
    let guard = servers.lock().await;
    let service = guard
        .get(name)
        .ok_or_else(|| format!("'{name}' is not connected"))?;
    let mut names: Vec<String> = tokio::time::timeout(timeout_duration, service.list_all_tools())
        .await
        .map_err(|_| {
            format!(
                "listing tools for '{name}' timed out after {}s",
                timeout_duration.as_secs()
            )
        })?
        .map_err(|e| format!("could not list tools for '{name}': {e}"))?
        .into_iter()
        .map(|t| t.name.to_string())
        .collect();
    names.sort();
    Ok(names)
}

/// Number of servers marked `active` in `mcp_config.json`.
pub fn active_count() -> usize {
    list_servers().iter().filter(|e| e.active).count()
}

/// Outcome of a best-effort connect of every `active` server.
///
/// Failures are returned rather than logged: the TUI owns the terminal while
/// this runs, so a `log::warn!` here paints raw text over the alternate screen.
/// The caller decides how to surface them (the TUI notes them in the
/// transcript alongside the ready line; headless logs them as before).
#[derive(Debug, Default)]
pub struct ConnectOutcome {
    /// Servers that came up, in the order they connected.
    pub connected: Vec<String>,
    /// One `failed to connect to '<name>': <error>` per server that didn't.
    pub failed: Vec<String>,
    /// Servers that are up to the user to sign into, kept apart from `failed`
    /// so the caller can point at `/mcp` instead of repeating a transport error
    /// nobody can act on.
    pub needs_auth: Vec<String>,
}

/// Connect every `active` server into the shared map, best-effort.
pub async fn connect_active(servers: &SharedMcpServers) -> ConnectOutcome {
    let mut out = ConnectOutcome::default();
    for entry in list_servers().into_iter().filter(|e| e.active) {
        match connect(&entry.name, &entry.config, servers).await {
            Ok(()) => out.connected.push(entry.name),
            Err(ConnectError::NeedsAuth { server, .. }) => out.needs_auth.push(server),
            Err(e) => out.failed.push(e.to_string()),
        }
    }
    out
}

#[cfg(test)]
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");
    }

    /// `config` saved under `name` with the smallest connect bound the setting
    /// allows, so a test that expects the connect to give up does not wait.
    fn save_with_a_one_second_bound(folder: &std::path::Path, name: &str, config: &Value) {
        upsert_server_in(folder, name, config).unwrap();
        let mut cfg = read_config(folder);
        cfg["mcpSettings"] = serde_json::json!({ "toolCallTimeoutSeconds": 1 });
        write_config(folder, &cfg).unwrap();
    }

    /// Run a connect that has to give up by itself, and return why it did.
    async fn connect_that_gives_up(
        folder: &std::path::Path,
        name: &str,
        config: &Value,
    ) -> (String, SharedMcpServers) {
        let servers: SharedMcpServers = Default::default();
        let outcome = tokio::time::timeout(
            std::time::Duration::from_secs(15),
            connect_in(folder, name, config, &servers),
        )
        .await
        .expect("the connect must give up by itself rather than wait on the server");
        let message = outcome
            .expect_err("a server that never answers did not connect")
            .to_string();
        assert!(
            message.contains(&format!("failed to connect to '{name}'")),
            "{message}"
        );
        assert!(message.contains("timed out after 1s"), "{message}");
        (message, servers)
    }

    /// Whether `pid` has been killed, given a moment to be. A killed process whose
    /// parent has not reaped it yet is a zombie: it still answers signal 0 until
    /// whoever adopted it collects it, and where that is a PID 1 that never reaps
    /// (a minimal container) it never stops answering. It is dead all the same.
    #[cfg(unix)]
    async fn process_is_gone(pid: i32) -> bool {
        fn is_zombie(pid: i32) -> bool {
            #[cfg(target_os = "linux")]
            {
                // "pid (comm) S ...": the state follows the last ')'.
                std::fs::read_to_string(format!("/proc/{pid}/stat"))
                    .ok()
                    .and_then(|stat| {
                        stat.rsplit(')')
                            .next()
                            .map(|rest| rest.trim_start().starts_with('Z'))
                    })
                    .unwrap_or(false)
            }
            #[cfg(not(target_os = "linux"))]
            {
                std::process::Command::new("ps")
                    .args(["-o", "stat=", "-p", &pid.to_string()])
                    .output()
                    .map(|out| String::from_utf8_lossy(&out.stdout).trim().starts_with('Z'))
                    .unwrap_or(false)
            }
        }

        for _ in 0..60 {
            // Signal 0 only checks that the process exists.
            let exists = std::process::Command::new("kill")
                .args(["-0", &pid.to_string()])
                .stderr(Stdio::null())
                .status()
                .map(|s| s.success())
                .unwrap_or(false);
            if !exists || is_zombie(pid) {
                return true;
            }
            tokio::time::sleep(std::time::Duration::from_millis(50)).await;
        }
        false
    }

    /// A stdio server that starts and then never answers `initialize` must fail
    /// the connect after the tool-call timeout, like a server that exits, so the
    /// run goes on without it. Unbounded, this awaited forever and blocked every
    /// agent run behind the connect.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_server_that_never_answers_initialize_fails_the_connect() {
        let data = temp_data();
        let pid_file = data.path().join("server.pid");
        let config = serde_json::json!({
            "command": "sh",
            // `exec` keeps the pid the file names.
            "args": ["-c", format!("echo $$ > '{}'; exec sleep 600", pid_file.display())],
            "active": true,
        });
        save_with_a_one_second_bound(data.path(), "silent", &config);

        let (_, servers) = connect_that_gives_up(data.path(), "silent", &config).await;
        assert!(
            servers.lock().await.is_empty(),
            "a failed connect leaves nothing behind"
        );

        let pid: i32 = std::fs::read_to_string(&pid_file)
            .expect("the server started")
            .trim()
            .parse()
            .unwrap();
        assert!(
            process_is_gone(pid).await,
            "the silent server was left running"
        );
    }

    /// A server that starts children of its own is reaped whole: dropping the
    /// handshake kills the process it started, not what that started in turn.
    #[cfg(unix)]
    #[tokio::test]
    async fn giving_up_on_a_server_takes_the_processes_it_started_with_it() {
        let data = temp_data();
        let pid_file = data.path().join("child.pid");
        let config = serde_json::json!({
            "command": "sh",
            "args": ["-c", format!("sleep 600 & echo $! > '{}'; wait", pid_file.display())],
            "active": true,
        });
        save_with_a_one_second_bound(data.path(), "forking", &config);

        connect_that_gives_up(data.path(), "forking", &config).await;

        let child: i32 = std::fs::read_to_string(&pid_file)
            .expect("the server started its child")
            .trim()
            .parse()
            .unwrap();
        assert!(
            process_is_gone(child).await,
            "the server's child was left running"
        );
    }

    /// An http server that accepts the connection and never answers is bounded
    /// too, together with the credential lookup and OAuth probe around it.
    #[tokio::test]
    async fn an_http_server_that_never_answers_fails_the_connect() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}/mcp", listener.local_addr().unwrap());
        // Hold every connection open without ever replying.
        let held = tokio::spawn(async move {
            let mut open = Vec::new();
            while let Ok((socket, _)) = listener.accept().await {
                open.push(socket);
            }
        });

        let data = temp_data();
        let config = serde_json::json!({ "type": "http", "url": url, "active": true });
        save_with_a_one_second_bound(data.path(), "mute", &config);

        let (_, servers) = connect_that_gives_up(data.path(), "mute", &config).await;
        assert!(servers.lock().await.is_empty());
        held.abort();
    }

    /// A machine where the desktop app never ran has no data folder yet, and the
    /// CLI is the first thing to write there.
    #[test]
    fn upsert_creates_a_data_folder_that_does_not_exist_yet() {
        let data = temp_data();
        let folder = data.path().join("never").join("created");
        let cfg = serde_json::json!({ "command": "echo", "args": [] });
        upsert_server_in(&folder, "fx", &cfg).unwrap();

        assert_eq!(get_server_in(&folder, "fx").unwrap().name, "fx");
    }

    /// When the folder cannot be created, the error says which one, rather than
    /// a bare "No such file or directory".
    #[test]
    fn a_data_folder_that_cannot_be_created_is_named_in_the_error() {
        let data = temp_data();
        // A file where a directory has to go.
        let blocker = data.path().join("blocker");
        std::fs::write(&blocker, b"").unwrap();
        let folder = blocker.join("data");
        let cfg = serde_json::json!({ "command": "echo", "args": [] });

        let err = upsert_server_in(&folder, "fx", &cfg).unwrap_err();
        assert!(err.contains(&folder.display().to_string()), "{err}");
    }

    #[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 gateway_credentials_are_scrubbed_and_a_desktop_providers_key_is_not() {
        // No explicit provider, no telemetry: only Jan's own gateway variables.
        assert_eq!(credential_vars(None, false), ["JAN_API_KEY", "JAN_CUSTOM_HEADERS"]);

        // A launcher's session: the named provider's key and, while Jan
        // exports, its collector headers too.
        let launched = credential_vars(Some("tokamak"), true);
        for name in [
            "JAN_API_KEY",
            "JAN_CUSTOM_HEADERS",
            "TOKAMAK_API_KEY",
            "OTEL_EXPORTER_OTLP_HEADERS",
            "OTEL_EXPORTER_OTLP_LOGS_HEADERS",
            "OTEL_EXPORTER_OTLP_METRICS_HEADERS",
            "OTEL_EXPORTER_OTLP_TRACES_HEADERS",
        ] {
            assert!(launched.iter().any(|n| n == name), "{name} in {launched:?}");
        }
        // Keys servers read for themselves stay.
        assert!(!launched.iter().any(|n| n == "OPENAI_API_KEY" || n == "GITHUB_TOKEN"));

        // Telemetry off: the OTLP headers are the user's, for a server that
        // exports to its own collector.
        assert!(!credential_vars(Some("tokamak"), false)
            .iter()
            .any(|n| n.starts_with("OTEL_")));
    }

    #[test]
    fn a_stdio_server_keeps_its_own_env_over_the_scrub() {
        let params = extract_command_args(&serde_json::json!({
            "command": "server",
            "args": ["--stdio"],
            "env": { "TOKAMAK_API_KEY": "the-servers-own" },
        }))
        .unwrap();
        let scrub = credential_vars(Some("tokamak"), true);
        let cmd = stdio_command(&params, &scrub);
        let envs: std::collections::HashMap<String, Option<String>> = cmd
            .as_std()
            .get_envs()
            .map(|(k, v)| {
                (
                    k.to_string_lossy().into_owned(),
                    v.map(|v| v.to_string_lossy().into_owned()),
                )
            })
            .collect();
        assert_eq!(envs.get("JAN_API_KEY"), Some(&None), "removed");
        assert_eq!(envs.get("OTEL_EXPORTER_OTLP_HEADERS"), Some(&None), "removed");
        assert_eq!(
            envs.get("TOKAMAK_API_KEY"),
            Some(&Some("the-servers-own".to_string())),
            "a server's explicit env entry is still set"
        );
    }

    /// The spawned process really goes without a scrubbed variable it would
    /// otherwise inherit. `HOME` stands in for a credential: every test
    /// process has it, so nothing here mutates the shared environment.
    #[cfg(unix)]
    #[tokio::test]
    async fn a_spawned_stdio_server_does_not_inherit_a_scrubbed_variable() {
        assert!(std::env::var_os("HOME").is_some());
        let params = extract_command_args(&serde_json::json!({
            "command": "/usr/bin/env",
            "args": [],
            "env": { "JAN_TEST_SERVER_OWN": "kept" },
        }))
        .unwrap();
        let out = stdio_command(&params, &["HOME".to_string()])
            .output()
            .await
            .expect("spawn env");
        let env = String::from_utf8_lossy(&out.stdout);
        assert!(!env.lines().any(|l| l.starts_with("HOME=")), "{env}");
        assert!(env.lines().any(|l| l == "JAN_TEST_SERVER_OWN=kept"), "{env}");
        assert!(env.lines().any(|l| l.starts_with("PATH=")), "the rest is inherited");
    }

    #[test]
    fn browser_mcp_excluded_and_sorted() {
        // list_servers reads the real data folder; assert only invariants that
        // hold regardless of installed config.
        let servers = list_servers();
        assert!(servers.iter().all(|s| s.name != BROWSER_MCP_NAME));
        for w in servers.windows(2) {
            assert!(w[0].name <= w[1].name);
        }
    }
}