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.

35.3 KB
Raw Blame
use rmcp::model::{CallToolRequestParams, CallToolResult};
use serde_json::{json, Map, Value};
use tauri::{AppHandle, Emitter, Manager, Runtime, State};
use tauri_plugin_opener::OpenerExt;
use tokio::sync::oneshot;
use tokio::time::timeout;

use super::{
    constants::DEFAULT_MCP_CONFIG,
    helpers::{restart_active_mcp_servers, start_mcp_server, terminate_browser_mcp},
    truncate::truncate_tool_result,
};
use crate::core::{
    app::commands::get_jan_data_folder_path,
    mcp::models::{McpSettings, ServerSummary},
    mcp::oauth,
    state::AppState,
};
use crate::core::{
    mcp::identity,
    mcp::models::ToolWithServer,
    state::{RunningMcpService, SharedMcpServers},
};
use std::{collections::HashSet, fs, time::Duration};

async fn tool_call_timeout(state: &AppState) -> Duration {
    state.mcp_settings.lock().await.tool_call_timeout_duration()
}

/// Shared implementation for listing MCP tools.
///
/// - `server_filter: None` — every enabled server (same behavior as `get_tools`).
/// - `server_filter: Some(names)` — only enabled servers in that set; unknown names
///   are skipped (logged).
///
/// A server counts as "enabled" if it's in `mcp_active_servers`, regardless of
/// whether it's currently connected — a transiently disconnected server still
/// contributes its last successfully listed tools (`mcp_last_known_tools`), so
/// the tool schema Jan sends stays present and stable across reconnects instead
/// of shrinking/growing and invalidating the downstream KV-cache prefix.
/// `mcp_last_known_tools` is only cleared by explicit user deactivation
/// (`deactivate_mcp_server`), never by a transient list-tools failure here.
async fn collect_mcp_tools<R: Runtime>(
    app: &AppHandle<R>,
    state: &AppState,
    server_filter: Option<HashSet<String>>,
) -> Result<Vec<ToolWithServer>, String> {
    let timeout_duration = tool_call_timeout(state).await;
    let mut all_tools: Vec<ToolWithServer> = Vec::new();
    let mut removed_any = false;

    let server_names: Vec<String> = {
        let active_servers = state.mcp_active_servers.lock().await;
        match &server_filter {
            None => active_servers.keys().cloned().collect(),
            Some(filter) => {
                for name in filter {
                    if !active_servers.contains_key(name) {
                        log::debug!(
                            "collect_mcp_tools: requested server {name:?} is not enabled; skipping"
                        );
                    }
                }
                filter
                    .iter()
                    .filter(|n| active_servers.contains_key(*n))
                    .cloned()
                    .collect()
            }
        }
    };

    for server_name in server_names {
        // Snapshot the live service's list_all_tools() future while holding the
        // lock, but resolve it after dropping the guard so a slow/hanging
        // server doesn't hold `mcp_servers` locked for other callers.
        let maybe_list_result = {
            let servers = state.mcp_servers.lock().await;
            match servers.get(&server_name) {
                // Read under the servers lock, which every replacement holds.
                Some(service) => Some((
                    identity::current_generation(&server_name),
                    timeout(timeout_duration, service.list_all_tools()).await,
                )),
                None => None,
            }
        };

        let fresh_tools = match maybe_list_result {
            Some((generation, Ok(Ok(tools)))) => {
                let mapped: Vec<ToolWithServer> = tools
                    .into_iter()
                    .map(|tool| ToolWithServer {
                        name: tool.name.to_string(),
                        description: tool.description.as_ref().map(|d| d.to_string()),
                        input_schema: serde_json::Value::Object((*tool.input_schema).clone()),
                        server: server_name.clone(),
                        generation,
                    })
                    .collect();
                let mut last_known = state.mcp_last_known_tools.lock().await;
                last_known.insert(server_name.clone(), mapped.clone());
                Some(mapped)
            }
            Some((_, Ok(Err(e)))) => {
                let err_str = e.to_string();
                log::warn!("MCP server {server_name} failed to list tools: {err_str}");
                if is_transport_error(&err_str) {
                    state.mcp_reconnect_notify.notify_waiters();
                }
                if remove_mcp_server_entry(&state.mcp_servers, &server_name).await {
                    removed_any = true;
                }
                None
            }
            Some((_, Err(_))) => {
                log::warn!(
                    "MCP server {server_name}: listing tools timed out after {} seconds",
                    timeout_duration.as_secs()
                );
                None
            }
            None => {
                log::debug!(
                    "collect_mcp_tools: server {server_name:?} not connected; using last-known tools if any"
                );
                None
            }
        };

        let tools = match fresh_tools {
            Some(tools) => tools,
            None => {
                let last_known = state.mcp_last_known_tools.lock().await;
                last_known.get(&server_name).cloned().unwrap_or_default()
            }
        };
        all_tools.extend(tools);
    }

    if removed_any {
        if let Err(e) = app.emit("mcp-update", json!({ "server": "tools-refresh" })) {
            log::error!("Failed to emit mcp-update event: {e}");
        }
    }

    // A name two servers offer, or an empty one, cannot be held to one server
    // when the model calls it, so it is not offered at all.
    let unroutable = identity::unroutable_tool_names(
        all_tools
            .iter()
            .map(|tool| (tool.server.as_str(), tool.name.as_str())),
    );
    all_tools.retain(|tool| !unroutable.contains(&tool.name));

    Ok(all_tools)
}

fn is_transport_error(error: &str) -> bool {
    let lower = error.to_lowercase();
    lower.contains("transport closed")
        || lower.contains("broken pipe")
        || lower.contains("connection reset")
        || lower.contains("channel closed")
        || lower.contains("transport error")
}

async fn cleanup_cancellation_token(
    state: &State<'_, AppState>,
    cancellation_token: &Option<String>,
) {
    if let Some(token) = cancellation_token {
        let mut cancellations = state.tool_call_cancellations.lock().await;
        cancellations.remove(token);
    }
}

#[tauri::command]
pub async fn activate_mcp_server<R: Runtime>(
    app: tauri::AppHandle<R>,
    state: State<'_, AppState>,
    name: String,
    config: Value,
) -> Result<(), String> {
    let servers: SharedMcpServers = state.mcp_servers.clone();

    // Use the modified start_mcp_server that returns first attempt result
    start_mcp_server(app, servers, name, config).await
}

#[tauri::command]
pub async fn deactivate_mcp_server<R: Runtime>(
    app: AppHandle<R>,
    state: State<'_, AppState>,
    name: String,
) -> Result<(), String> {
    log::info!("Deactivating MCP server: {name}");

    // Get port from config before removing (for lock file cleanup later)
    let bridge_port = if name == "Jan Browser MCP" {
        let active_servers = state.mcp_active_servers.lock().await;
        active_servers.get(&name).and_then(|config| {
            config
                .get("env")
                .and_then(|envs| envs.get("BRIDGE_PORT"))
                .and_then(|port| port.as_str())
                .and_then(|port_str| port_str.parse::<u16>().ok())
        })
    } else {
        None
    };

    // First, mark server as manually deactivated
    // Remove from active servers list
    {
        let mut active_servers = state.mcp_active_servers.lock().await;
        active_servers.remove(&name);
        log::info!("Removed MCP server {name} from active servers list");
    }

    // Explicit deactivation is the only thing that should drop the last-known
    // tool schema — a transient disconnect must not (collect_mcp_tools keeps
    // serving it until the server is actually turned off).
    {
        let mut last_known = state.mcp_last_known_tools.lock().await;
        last_known.remove(&name);
    }

    // Now remove and stop the server
    let servers = state.mcp_servers.clone();
    let mut servers_map = servers.lock().await;

    let service = servers_map
        .remove(&name)
        .ok_or_else(|| format!("Server {name} not found"))?;

    // Release the lock before calling cancel
    drop(servers_map);

    log::info!("Stopping server {name}...");
    service.cancel().await.map_err(|e| e.to_string())?;

    let child_pid = {
        let mut pids = state.mcp_server_pids.lock().await;
        pids.remove(&name)
    };
    // Reap the process group and confirm the port is released, then drop the lock.
    if name == "Jan Browser MCP" {
        if let Some(port) = bridge_port {
            use crate::core::mcp::lockfile::delete_lock_file;

            terminate_browser_mcp(child_pid, port).await;

            if let Err(e) = delete_lock_file(&app, port) {
                log::warn!("Failed to delete lock file for port {}: {}", port, e);
            }
        }
    }

    log::info!("Server {name} stopped successfully and marked as deactivated.");

    // Emit mcp-update event so frontend can refresh tools list
    if let Err(e) = app.emit(
        "mcp-update",
        serde_json::json!({
            "server": name
        }),
    ) {
        log::error!("Failed to emit mcp-update event: {e}");
    }

    Ok(())
}

#[tauri::command]
pub async fn restart_mcp_servers<R: Runtime>(
    app: AppHandle<R>,
    state: State<'_, AppState>,
) -> Result<(), String> {
    use super::helpers::{stop_mcp_servers_with_context, ShutdownContext};

    let servers = state.mcp_servers.clone();

    stop_mcp_servers_with_context(&app, &state, ShutdownContext::ManualRestart).await?;

    // Restart only previously active servers (like cortex)
    restart_active_mcp_servers(&app, servers).await?;

    app.emit("mcp-update", "MCP servers updated")
        .map_err(|e| format!("Failed to emit event: {e}"))?;

    Ok(())
}

#[tauri::command]
pub async fn get_connected_servers(
    _app: AppHandle<impl Runtime>,
    state: State<'_, AppState>,
) -> Result<Vec<String>, String> {
    let servers = state.mcp_servers.clone();
    let servers_map = servers.lock().await;
    Ok(servers_map.keys().cloned().collect())
}

/// Remove an MCP server entry and cancel its running service (used when list-tools fails).
async fn remove_mcp_server_entry(mcp_servers: &SharedMcpServers, server_name: &str) -> bool {
    let mut servers = mcp_servers.lock().await;
    if let Some(service) = servers.remove(server_name) {
        log::warn!("Removing MCP server {server_name} from connected servers");
        let _ = service.cancel().await;
        true
    } else {
        false
    }
}

/// Retrieves all available tools from all MCP servers with server information
///
/// # Arguments
/// * `state` - Application state containing MCP server connections
///
/// # Returns
/// * `Result<Vec<Tool>, String>` - A vector of all tools if successful, or an error message if failed
///
/// This function:
/// 1. Locks the MCP servers mutex to access server connections
/// 2. Iterates through all connected servers
/// 3. Gets the list of tools from each server
/// 4. Associates each tool with its parent server name
/// 5. Combines all tools into a single vector
/// 6. Returns the combined list of all available tools with server information
#[tauri::command]
pub async fn get_tools<R: Runtime>(
    app: AppHandle<R>,
    state: State<'_, AppState>,
) -> Result<Vec<ToolWithServer>, String> {
    collect_mcp_tools(&app, &state, None).await
}

/// Retrieves tools from a specific subset of MCP servers by name.
/// Unknown or disconnected names are ignored; transport failures match `get_tools` cleanup.
#[tauri::command]
pub async fn get_tools_for_servers<R: Runtime>(
    app: AppHandle<R>,
    state: State<'_, AppState>,
    server_names: Vec<String>,
) -> Result<Vec<ToolWithServer>, String> {
    let mut seen = HashSet::new();
    let mut unique: Vec<String> = Vec::new();
    for n in server_names {
        if seen.insert(n.clone()) {
            unique.push(n);
        }
    }
    let filter: HashSet<String> = unique.into_iter().collect();
    if filter.is_empty() {
        return Ok(Vec::new());
    }
    collect_mcp_tools(&app, &state, Some(filter)).await
}

/// Returns name, capability tags, and description for all enabled MCP servers
/// (regardless of live connection state — see `collect_mcp_tools`).
#[tauri::command]
pub async fn get_server_summaries(
    state: State<'_, AppState>,
) -> Result<Vec<ServerSummary>, String> {
    let active_servers = state.mcp_active_servers.lock().await;
    let mut summaries = Vec::new();

    for name in active_servers.keys() {
        let config = active_servers.get(name);

        let capabilities: Vec<String> = config
            .and_then(|c| c.get("capabilities"))
            .and_then(|v| v.as_array())
            .map(|arr| {
                arr.iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect()
            })
            .unwrap_or_default();

        let description: String = config
            .and_then(|c| c.get("description"))
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string();

        summaries.push(ServerSummary {
            name: name.clone(),
            capabilities,
            description,
        });
    }

    Ok(summaries)
}

/// Calls a tool on an MCP server by name with optional arguments
///
/// # Arguments
/// * `state` - Application state containing MCP server connections
/// * `tool_name` - Name of the tool to call
/// * `server_name` - The server that offered the tool. Without it the tool is
///   looked up across servers, and a name more than one server offers is refused
/// * `server_generation` - The connection generation the tool was listed from
///   (`ToolWithServer::generation`). A call to a server that has since been
///   replaced is refused instead of running on the new process
/// * `arguments` - Optional map of argument names to values
/// * `thread_id`, `call_id` - The conversation and tool call the user approved
///   (`tauri_plugin_agent_tools::consent`). The call runs only on that
///   approval, given for this tool on the server that is about to run it
/// * `cancellation_token` - Optional token to allow cancellation from JS side
/// * `max_output_chars` - Optional caller-derived per-result character budget
///   (the desktop chat derives one from the active model's context window);
///   combined with the `maxToolOutputChars` setting, tighter wins
///
/// The servers lock is held from the generation check through the call, and
/// every replacement of a server takes that lock, so the connection checked is
/// the one that runs the call.
#[tauri::command]
#[allow(clippy::too_many_arguments)]
pub async fn call_tool(
    state: State<'_, AppState>,
    tool_name: String,
    server_name: Option<String>,
    server_generation: Option<u64>,
    arguments: Option<Map<String, Value>>,
    thread_id: Option<String>,
    call_id: Option<String>,
    cancellation_token: Option<String>,
    max_output_chars: Option<u64>,
) -> Result<CallToolResult, String> {
    let (timeout_duration, tool_output_cap) = {
        let settings = state.mcp_settings.lock().await;
        (
            settings.tool_call_timeout_duration(),
            settings.tool_output_cap(max_output_chars),
        )
    };
    // Set up cancellation if token is provided
    let (cancel_tx, cancel_rx) = oneshot::channel::<()>();

    if let Some(token) = &cancellation_token {
        let mut cancellations = state.tool_call_cancellations.lock().await;
        cancellations.insert(token.clone(), cancel_tx);
    }

    let servers = state.mcp_servers.lock().await;

    let target = resolve_call_target(
        &servers,
        &tool_name,
        server_name.as_deref(),
        server_generation,
    )
    .await;
    let (srv_name, service) = match target {
        Ok(target) => target,
        Err(CallTargetError::Refused(e)) => {
            log::warn!("MCP call to tool {tool_name} refused: {e}");
            cleanup_cancellation_token(&state, &cancellation_token).await;
            return Err(e);
        }
        Err(CallTargetError::Disconnected(names)) => {
            log::warn!(
                "MCP call to tool {tool_name} not run: server(s) [{}] disconnected",
                names.join(", ")
            );
            state.mcp_reconnect_notify.notify_waiters();
            cleanup_cancellation_token(&state, &cancellation_token).await;
            return Err(format!(
                "MCP server(s) [{}] disconnected while looking for tool '{}'. Reconnecting - please retry.",
                names.join(", "),
                tool_name
            ));
        }
    };

    log::info!("Found tool {tool_name} in server {srv_name}");

    if let Err(e) = tauri_plugin_agent_tools::consent::store().consume(
        thread_id.as_deref().unwrap_or_default(),
        call_id.as_deref().unwrap_or_default(),
        &tool_name,
        Some(srv_name),
        tauri_plugin_agent_tools::consent::ToolOrigin::Mcp,
    ) {
        log::warn!("MCP call to tool {tool_name} on {srv_name} not approved: {e}");
        cleanup_cancellation_token(&state, &cancellation_token).await;
        return Err(e);
    }

    // Call the tool with timeout and cancellation support
    let mut params = CallToolRequestParams::new(tool_name.clone());
    if let Some(args) = arguments {
        params = params.with_arguments(args);
    }
    let tool_call = service.call_tool(params);

    // Race between timeout, tool call, and cancellation
    let result = if cancellation_token.is_some() {
        tokio::select! {
            result = timeout(timeout_duration, tool_call) => {
                match result {
                    Ok(call_result) => call_result.map_err(|e| e.to_string()),
                    Err(_) => Err(format!(
                        "Tool call '{tool_name}' timed out after {} seconds",
                        timeout_duration.as_secs()
                    )),
                }
            }
            _ = cancel_rx => {
                Err(format!("Tool call '{tool_name}' was cancelled"))
            }
        }
    } else {
        match timeout(timeout_duration, tool_call).await {
            Ok(call_result) => call_result.map_err(|e| e.to_string()),
            Err(_) => Err(format!(
                "Tool call '{tool_name}' timed out after {} seconds",
                timeout_duration.as_secs()
            )),
        }
    };

    // Signal reconnect if the tool call itself hit a transport error
    if let Err(e) = &result {
        if is_transport_error(e) {
            log::warn!("MCP server {srv_name} transport error during tool call: {e}");
            state.mcp_reconnect_notify.notify_waiters();
        }
    }

    cleanup_cancellation_token(&state, &cancellation_token).await;
    // Cap here rather than at each caller: this is the single point every
    // desktop MCP tool result passes through on its way into conversation
    // history, so an unbounded result can never reach the model.
    result.map(|res| truncate_tool_result(&res, tool_output_cap))
}

pub(crate) enum CallTargetError {
    /// The call must not run; the message says why.
    Refused(String),
    /// No server was found to offer the tool, but these could not be asked.
    Disconnected(Vec<String>),
}

/// The one connection a call may run on. A named server must still be the
/// connection the tool was listed from and must offer the tool; an unnamed
/// call needs exactly one server offering it. Never falls back to another
/// server: a call meant for one server that reaches another acts with the
/// wrong server's handler and grants.
pub(crate) async fn resolve_call_target<'a, S: McpToolSource>(
    servers: &'a std::collections::HashMap<String, S>,
    tool_name: &str,
    server_name: Option<&str>,
    server_generation: Option<u64>,
) -> Result<(&'a str, &'a S), CallTargetError> {
    if let Some(server) = server_name {
        let Some((name, service)) = servers.get_key_value(server) else {
            return Err(CallTargetError::Refused(format!(
                "MCP server '{server}' is not connected; the call was not run"
            )));
        };
        if let Some(generation) = server_generation {
            identity::check_generation(server, generation).map_err(CallTargetError::Refused)?;
        }
        return match service.tool_names().await {
            Ok(names) if names.iter().any(|n| n == tool_name) => Ok((name.as_str(), service)),
            Ok(_) => Err(CallTargetError::Refused(format!(
                "MCP server '{server}' no longer offers tool '{tool_name}'"
            ))),
            Err(e) if is_transport_error(&e) => {
                Err(CallTargetError::Disconnected(vec![name.clone()]))
            }
            Err(e) => Err(CallTargetError::Refused(format!(
                "MCP server '{server}' could not list its tools: {e}"
            ))),
        };
    }

    if servers.is_empty() {
        return Err(CallTargetError::Refused(format!(
            "Tool {tool_name} not found - no MCP servers connected"
        )));
    }

    let mut offering: Vec<(&'a str, &'a S)> = Vec::new();
    let mut disconnected: Vec<String> = Vec::new();
    for (name, service) in servers {
        match service.tool_names().await {
            Ok(names) if names.iter().any(|n| n == tool_name) => {
                offering.push((name.as_str(), service))
            }
            Ok(_) => {}
            Err(e) => {
                log::warn!("MCP server {name} failed to list tools during call_tool: {e}");
                if is_transport_error(&e) {
                    disconnected.push(name.clone());
                }
            }
        }
    }

    match offering.as_slice() {
        [only] => Ok(*only),
        [] if !disconnected.is_empty() => Err(CallTargetError::Disconnected(disconnected)),
        [] => Err(CallTargetError::Refused(format!(
            "Tool {tool_name} not found"
        ))),
        many => {
            let mut names: Vec<&str> = many.iter().map(|(name, _)| *name).collect();
            names.sort_unstable();
            Err(CallTargetError::Refused(format!(
                "Tool '{tool_name}' is offered by more than one MCP server ({}); the call was not run",
                names.join(", ")
            )))
        }
    }
}

/// The part of a running MCP service call routing needs, so routing can be
/// tested without a live server.
#[async_trait::async_trait]
pub(crate) trait McpToolSource: Sync {
    async fn tool_names(&self) -> Result<Vec<String>, String>;
}

#[async_trait::async_trait]
impl McpToolSource for RunningMcpService {
    async fn tool_names(&self) -> Result<Vec<String>, String> {
        self.list_all_tools()
            .await
            .map(|tools| tools.into_iter().map(|t| t.name.to_string()).collect())
            .map_err(|e| e.to_string())
    }
}

/// Cancels a running tool call by its cancellation token
///
/// # Arguments
/// * `state` - Application state containing cancellation tokens
/// * `cancellation_token` - Token identifying the tool call to cancel
///
/// # Returns
/// * `Result<(), String>` - Success if token found and cancelled, error otherwise
#[tauri::command]
pub async fn cancel_tool_call(
    state: State<'_, AppState>,
    cancellation_token: String,
) -> Result<(), String> {
    let mut cancellations = state.tool_call_cancellations.lock().await;

    if let Some(cancel_tx) = cancellations.remove(&cancellation_token) {
        // Send cancellation signal - ignore if receiver is already dropped
        let _ = cancel_tx.send(());
        println!("Tool call with token {cancellation_token} cancelled");
        Ok(())
    } else {
        Err(format!("Cancellation token {cancellation_token} not found"))
    }
}

fn parse_mcp_settings(value: Option<&Value>) -> McpSettings {
    value
        .and_then(|v| serde_json::from_value::<McpSettings>(v.clone()).ok())
        .unwrap_or_default()
}

/// Read one configured server's entry out of `mcp_config.json`. Errors rather
/// than defaulting: every caller here is acting on a server the user picked, and
/// a silent empty config would report "not authenticated" for a typo.
fn read_server_config<R: Runtime>(app: &AppHandle<R>, name: &str) -> Result<Value, String> {
    let mut path = get_jan_data_folder_path(app.clone());
    path.push("mcp_config.json");
    let body = fs::read_to_string(&path).map_err(|e| e.to_string())?;
    serde_json::from_str::<Value>(&body)
        .map_err(|e| format!("Failed to parse mcp_config.json: {e}"))?
        .get("mcpServers")
        .and_then(|s| s.get(name))
        .cloned()
        .ok_or_else(|| format!("server '{name}' not found in mcp_config.json"))
}

/// The OAuth state of one configured server. Local only -- no network -- so the
/// settings screen can call it per row without a round trip each.
#[tauri::command]
pub async fn get_mcp_auth_status<R: Runtime>(
    app: AppHandle<R>,
    name: String,
) -> Result<oauth::AuthStatusInfo, String> {
    let config = read_server_config(&app, &name)?;
    let folder = get_jan_data_folder_path(app);
    Ok(oauth::status(&folder, &name, &config).into())
}

/// Run an interactive OAuth authorization for one server: discover the
/// provider, register a client, open the consent page, and wait for the
/// redirect on a loopback listener.
///
/// Resolves only once the flow finishes (or times out after five minutes), so
/// the caller awaits a single promise. The consent url is also emitted as
/// `mcp-oauth-url` before the wait begins, so the UI can offer it as a link
/// when the browser did not come up.
#[tauri::command]
pub async fn authorize_mcp_server<R: Runtime>(
    app: AppHandle<R>,
    name: String,
) -> Result<(), String> {
    let config = read_server_config(&app, &name)?;
    let url = 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")
        })?;

    let pending = oauth::begin(&name, url).await?;
    if let Err(e) = app.emit(
        "mcp-oauth-url",
        json!({ "server": &name, "url": &pending.authorization_url }),
    ) {
        log::error!("Failed to emit mcp-oauth-url event: {e}");
    }
    // Best-effort: the url has already been emitted, so a session with no
    // browser can still finish by opening it by hand. Only http(s) is handed
    // to the system opener, which would otherwise launch whatever handles the
    // scheme.
    if !oauth::is_allowed_oauth_url(&pending.authorization_url) {
        return Err(format!("'{name}' produced a sign-in URL Jan will not open"));
    }
    if let Err(e) = app.opener().open_url(&pending.authorization_url, None::<&str>) {
        log::warn!("Could not open the browser for '{name}': {e}");
    }

    let folder = get_jan_data_folder_path(app);
    pending.complete(&folder).await.map(|_| ())
}

/// Forget one server's stored tokens. `false` when there were none, so the UI
/// can tell "cleared" from "nothing to clear".
#[tauri::command]
pub async fn clear_mcp_auth<R: Runtime>(
    app: AppHandle<R>,
    name: String,
) -> Result<bool, String> {
    let folder = get_jan_data_folder_path(app);
    oauth::clear(&folder, &name)
}

#[tauri::command]
pub async fn get_mcp_configs<R: Runtime>(app: AppHandle<R>) -> Result<String, String> {
    let mut path = get_jan_data_folder_path(app.clone());
    path.push("mcp_config.json");

    // Create default empty config if file doesn't exist
    if !path.exists() {
        log::info!("mcp_config.json not found, creating default empty config");
        fs::write(&path, DEFAULT_MCP_CONFIG)
            .map_err(|e| format!("Failed to create default MCP config: {e}"))?;
    }

    let config_string = fs::read_to_string(&path).map_err(|e| e.to_string())?;

    let mut config_value: Value = if config_string.trim().is_empty() {
        json!({})
    } else {
        serde_json::from_str(&config_string).unwrap_or_else(|error| {
            log::error!("Failed to parse existing MCP config, regenerating defaults: {error}");
            json!({})
        })
    };

    if !config_value.is_object() {
        config_value = json!({});
    }

    let mut mutated = false;
    let config_object = config_value.as_object_mut().unwrap();

    let settings = parse_mcp_settings(config_object.get("mcpSettings"));
    if !config_object.contains_key("mcpSettings") {
        config_object.insert(
            "mcpSettings".to_string(),
            serde_json::to_value(&settings)
                .map_err(|e| format!("Failed to serialize MCP settings: {e}"))?,
        );
        mutated = true;
    }

    if !config_object.contains_key("mcpServers") {
        config_object.insert("mcpServers".to_string(), json!({}));
        mutated = true;
    }

    // Migration: Add Jan Browser MCP if not present
    let mcp_servers = config_object
        .get_mut("mcpServers")
        .and_then(|v| v.as_object_mut())
        .ok_or("mcpServers is not an object")?;

    if !mcp_servers.contains_key("Jan Browser MCP") {
        log::info!("Migrating config: Adding 'Jan Browser MCP' server");
        mcp_servers.insert(
            "Jan Browser MCP".to_string(),
            json!({
                "command": "npx",
                "args": ["-y", "search-mcp-server@latest"],
                "env": {
                    "BRIDGE_HOST": "127.0.0.1",
                    "BRIDGE_PORT": "17389"
                },
                "active": false,
                "official": true
            }),
        );
        mutated = true;
    }

    // Persist any mutations back to disk
    if mutated {
        fs::write(
            &path,
            serde_json::to_string_pretty(&config_value)
                .map_err(|e| format!("Failed to serialize MCP config: {e}"))?,
        )
        .map_err(|e| format!("Failed to write MCP config: {e}"))?;
    }

    // Update in-memory state with latest settings
    {
        let state = app.state::<AppState>();
        let mut settings_guard = state.mcp_settings.lock().await;
        *settings_guard = settings.clone();
    }

    serde_json::to_string_pretty(&config_value)
        .map_err(|e| format!("Failed to serialize MCP config: {e}"))
}

/// Check if error indicates extension not connected
pub(crate) fn is_extension_not_connected_error(text: &str) -> bool {
    const PATTERNS: &[&str] = &[
        "not connected to bridge",
        "not responding to ping",
        "extension not connected",
    ];
    const KEYWORD_PAIRS: &[(&str, &str)] = &[
        ("browser", "not connected"),
        ("browser", "not responding"),
        ("tool", "not found"),
    ];

    let text_lower = text.to_lowercase();
    PATTERNS.iter().any(|p| text_lower.contains(p))
        || KEYWORD_PAIRS
            .iter()
            .any(|(a, b)| text_lower.contains(a) && text_lower.contains(b))
}

/// Extract text response from tool result
fn get_result_text(result: &rmcp::model::CallToolResult) -> Option<&str> {
    result
        .content
        .first()
        .and_then(|c| c.as_text())
        .map(|t| t.text.as_str())
}

/// Check if Jan Browser extension is connected via MCP
#[tauri::command]
pub async fn check_jan_browser_extension_connected(
    state: State<'_, AppState>,
) -> Result<bool, String> {
    let servers = state.mcp_servers.lock().await;
    let service = match servers.get("Jan Browser MCP") {
        Some(s) => s,
        None => return Ok(false),
    };

    // Check available tools
    let tools = match timeout(Duration::from_secs(2), service.list_all_tools()).await {
        Ok(Ok(tools)) if !tools.is_empty() => tools,
        _ => return Ok(false),
    };

    let has_ping = tools.iter().any(|t| t.name == "ping");

    // Try simple ping first if available
    if has_ping {
        match try_ping_tool(service).await {
            PingResult::Connected => return Ok(true),
            PingResult::NotConnected => return Ok(false),
            PingResult::ToolNotAvailable => {
                log::debug!("ping unavailable, trying browser_snapshot");
            }
        }
    }

    // Fallback to browser_snapshot
    try_browser_snapshot_tool(service).await
}

enum PingResult {
    Connected,
    NotConnected,
    ToolNotAvailable,
}

async fn try_ping_tool(service: &RunningMcpService) -> PingResult {
    let result = timeout(
        Duration::from_secs(3),
        service.call_tool(CallToolRequestParams::new("ping").with_arguments(Map::new())),
    )
    .await;

    match result {
        Ok(Ok(res)) => {
            if let Some(text) = get_result_text(&res) {
                if text == "pong" {
                    return PingResult::Connected;
                }
                if is_extension_not_connected_error(text) {
                    return PingResult::NotConnected;
                }
            }
            if res.is_error == Some(true) {
                return PingResult::NotConnected;
            }
            PingResult::Connected
        }
        Ok(Err(e)) => {
            if is_extension_not_connected_error(&e.to_string()) {
                PingResult::NotConnected
            } else {
                PingResult::ToolNotAvailable
            }
        }
        Err(_) => PingResult::NotConnected,
    }
}

async fn try_browser_snapshot_tool(service: &RunningMcpService) -> Result<bool, String> {
    let result = timeout(
        // Snapshot tool is very time-consuming
        // Extend timeout to make sure the tool call has enough time to succeed
        Duration::from_secs(20),
        service.call_tool(
            CallToolRequestParams::new("browser_snapshot").with_arguments(Map::new()),
        ),
    )
    .await;

    match result {
        Ok(Ok(res)) => {
            if res.is_error == Some(true) {
                if let Some(text) = get_result_text(&res) {
                    if is_extension_not_connected_error(text) {
                        return Ok(false);
                    }
                }
            }
            Ok(true)
        }
        Ok(Err(_)) | Err(_) => Ok(false),
    }
}

#[tauri::command]
pub async fn save_mcp_configs<R: Runtime>(
    app: AppHandle<R>,
    configs: String,
) -> Result<(), String> {
    let mut path = get_jan_data_folder_path(app.clone());
    path.push("mcp_config.json");
    log::info!("save mcp configs, path: {path:?}");

    let mut config_value: Value =
        serde_json::from_str(&configs).map_err(|e| format!("Invalid MCP config payload: {e}"))?;

    if !config_value.is_object() {
        return Err("MCP config must be a JSON object".to_string());
    }

    let config_object = config_value.as_object_mut().unwrap();
    let settings = parse_mcp_settings(config_object.get("mcpSettings"));

    if !config_object.contains_key("mcpSettings") {
        config_object.insert(
            "mcpSettings".to_string(),
            serde_json::to_value(&settings).expect("Failed to serialize MCP settings"),
        );
    }

    if !config_object.contains_key("mcpServers") {
        config_object.insert("mcpServers".to_string(), json!({}));
    }

    fs::write(
        &path,
        serde_json::to_string_pretty(&config_value)
            .map_err(|e| format!("Failed to serialize MCP config: {e}"))?,
    )
    .map_err(|e| e.to_string())?;

    {
        let state = app.state::<AppState>();
        let mut settings_guard = state.mcp_settings.lock().await;
        *settings_guard = settings;
    }

    Ok(())
}