Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

16.0 KB
Raw Blame
//! Short-lived MCP handshakes requested by the MCP page, never by app startup.
use std::{
    collections::HashMap,
    process::Stdio,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
    time::Duration,
};

use crate::sync_utils::MutexExt;
use futures::{future::AbortHandle, future::Abortable, stream, StreamExt};
use process_wrap::tokio::{ChildWrapper, CommandWrap, KillOnDrop};
use rmcp::{
    model::{ClientInfo, Implementation},
    transport::{
        async_rw::AsyncRwTransport,
        common::client_side_sse::{BoxedSseResponse, NeverRetry},
        sse_client::{SseClient, SseClientConfig, SseTransportError},
        streamable_http_client::{
            StreamableHttpClient, StreamableHttpClientTransportConfig, StreamableHttpError,
            StreamableHttpPostResponse,
        },
        SseClientTransport, StreamableHttpClientTransport, Transport,
    },
    RoleClient, ServiceExt,
};
use serde::{Deserialize, Serialize};
use std::sync::LazyLock;
use tokio::process::Command;

use crate::app_config::McpServer;

// Package launchers such as npx/uvx may need time to prepare a cold start.
const CHECK_TIMEOUT: Duration = Duration::from_secs(30);
const MAX_CONCURRENT_CHECKS: usize = 3;
// Shared across batches: rows can be tested while another batch is still running.
static CHECK_PERMITS: tokio::sync::Semaphore =
    tokio::sync::Semaphore::const_new(MAX_CONCURRENT_CHECKS);
static BATCHES: LazyLock<std::sync::Mutex<HashMap<String, AbortHandle>>> =
    LazyLock::new(Default::default);

#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ConnectivityStatus {
    Connected,
    /// The endpoint answered 401: reachable, but it wants the client's own
    /// (often OAuth) sign-in, which CC Switch neither has nor reads.
    AuthRequired,
    Failed,
}

#[derive(Clone, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ConnectivityResult {
    pub server_id: String,
    pub status: ConnectivityStatus,
}

#[derive(Deserialize)]
struct ConnectionSpec {
    #[serde(rename = "type")]
    transport: Option<String>,
    command: Option<String>,
    #[serde(default)]
    args: Vec<String>,
    #[serde(default)]
    env: HashMap<String, String>,
    cwd: Option<String>,
    url: Option<String>,
    #[serde(default)]
    headers: HashMap<String, String>,
}

pub fn start_checks(
    servers: Vec<McpServer>,
    on_result: impl Fn(ConnectivityResult) -> bool + Send + 'static,
) -> String {
    let id = uuid::Uuid::new_v4().to_string();
    let (abort, registration) = AbortHandle::new_pair();
    BATCHES.lock_recover().insert(id.clone(), abort);
    let batch_id = id.clone();
    tauri::async_runtime::spawn(async move {
        let checks = async move {
            let mut results = stream::iter(servers.into_iter().map(|server| async move {
                // Queueing here keeps the wait out of the per-server CHECK_TIMEOUT.
                let _permit = CHECK_PERMITS.acquire().await;
                ConnectivityResult {
                    server_id: server.id,
                    status: check_server(server.server, CHECK_TIMEOUT).await,
                }
            }))
            .buffer_unordered(MAX_CONCURRENT_CHECKS);
            while let Some(result) = results.next().await {
                if !on_result(result) {
                    break; // The page/channel has gone away; drop queued checks too.
                }
            }
        };
        let _ = Abortable::new(checks, registration).await;
        BATCHES.lock_recover().remove(&batch_id);
    });
    id
}

pub fn cancel_checks(batch_id: &str) {
    if let Some(abort) = BATCHES.lock_recover().remove(batch_id) {
        abort.abort();
    }
}

async fn check_server(value: serde_json::Value, timeout: Duration) -> ConnectivityStatus {
    // Do not return/log transport errors: URLs, headers and process arguments may
    // contain credentials. The UI only needs the coarse status.
    let unauthorized = Arc::new(AtomicBool::new(false));
    match tokio::time::timeout(timeout, connect(value, unauthorized.clone())).await {
        Ok(Ok(())) => ConnectivityStatus::Connected,
        _ if unauthorized.load(Ordering::Relaxed) => ConnectivityStatus::AuthRequired,
        _ => ConnectivityStatus::Failed,
    }
}

async fn connect(
    value: serde_json::Value,
    unauthorized: Arc<AtomicBool>,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let spec: ConnectionSpec = serde_json::from_value(value)?;
    let transport = spec.transport.as_deref().unwrap_or_else(|| {
        if spec.url.is_some() && spec.command.is_none() {
            "http"
        } else {
            "stdio"
        }
    });
    match transport {
        "stdio" => {
            let program = spec
                .command
                .as_deref()
                .filter(|s| !s.trim().is_empty())
                .ok_or("Missing MCP command")?;
            #[cfg(not(windows))]
            let mut command = Command::new(program);
            #[cfg(windows)]
            let mut command = Command::new(resolve_windows_command(program, &spec));
            #[cfg(not(target_os = "windows"))]
            if !spec.env.contains_key("PATH") {
                // GUI launches can inherit only launchd's minimal PATH. The
                // login-shell PATH is resolved once per process, off the executor.
                let login_path =
                    tokio::task::spawn_blocking(crate::commands::cached_login_shell_path)
                        .await
                        .ok()
                        .flatten();
                let inherited = std::env::var("PATH").unwrap_or_default();
                apply_login_shell_path(&mut command, login_path.as_deref(), &inherited);
            }
            // 设置里的全局代理也给检测拉起的服务(npx / uvx 首次运行要下载包);配置里
            // 自己写了代理的以配置为准,整组不加,免得大小写两套变量指向不同代理。
            let configures_proxy = spec.env.keys().any(|key| {
                ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"]
                    .iter()
                    .any(|name| key.eq_ignore_ascii_case(name))
            });
            if !configures_proxy {
                if let Some(url) = crate::proxy::http_client::get_current_proxy_url() {
                    let set_by_config = |key: &str| {
                        std::env::var_os(key).is_some()
                            || spec.env.keys().any(|name| name.eq_ignore_ascii_case(key))
                    };
                    command.envs(crate::services::claude_account::login::global_proxy_env(
                        &url,
                        false,
                        set_by_config,
                    ));
                }
            }
            command
                .args(&spec.args)
                .envs(&spec.env)
                .stdin(Stdio::piped())
                .stdout(Stdio::piped())
                .stderr(Stdio::null());
            if let Some(cwd) = spec.cwd.as_deref().filter(|s| !s.is_empty()) {
                command.current_dir(cwd);
            }
            let mut command = CommandWrap::from(command);
            command.wrap(KillOnDrop);
            // Kill the entire process tree, including children of npx/uvx.
            #[cfg(unix)]
            command.wrap(process_wrap::tokio::ProcessGroup::leader());
            #[cfg(windows)]
            {
                let mut flags = process_wrap::tokio::CreationFlags(Default::default());
                flags.0 .0 = 0x08000000; // CREATE_NO_WINDOW
                command.wrap(flags).wrap(process_wrap::tokio::JobObject);
            }
            let mut process = ProbeProcess(Some(command.spawn()?));
            let child = process.0.as_mut().unwrap();
            let stdout = child.stdout().take().ok_or("Missing MCP stdout")?;
            let stdin = child.stdin().take().ok_or("Missing MCP stdin")?;
            let result = handshake(AsyncRwTransport::new_client(stdout, stdin)).await;
            drop(process);
            result
        }
        "http" | "sse" => {
            let url = spec.url.as_deref().ok_or("Missing MCP URL")?;
            let mut headers = reqwest::header::HeaderMap::new();
            for (name, value) in &spec.headers {
                headers.insert(
                    reqwest::header::HeaderName::from_bytes(name.as_bytes())?,
                    reqwest::header::HeaderValue::from_str(value)?,
                );
            }
            let client = crate::proxy::http_client::build_for_url(
                reqwest::Client::builder()
                    .default_headers(headers)
                    .connect_timeout(CHECK_TIMEOUT)
                    .timeout(CHECK_TIMEOUT)
                    .redirect(reqwest::redirect::Policy::none()),
                url,
            )?;
            if transport == "sse" {
                let transport = SseClientTransport::start_with_client(
                    SameOriginSseClient {
                        client,
                        origin: url.parse()?,
                        unauthorized,
                    },
                    SseClientConfig {
                        sse_endpoint: url.into(),
                        retry_policy: Arc::new(NeverRetry),
                        ..Default::default()
                    },
                )
                .await?;
                handshake(transport).await
            } else {
                let transport = StreamableHttpClientTransport::with_client(
                    UnauthorizedAwareClient {
                        client,
                        unauthorized,
                    },
                    StreamableHttpClientTransportConfig {
                        retry_config: Arc::new(NeverRetry),
                        ..StreamableHttpClientTransportConfig::with_uri(url)
                    },
                );
                handshake(transport).await
            }
        }
        _ => Err("Unsupported MCP transport".into()),
    }
}

/// Inject before configured env so a server's explicit PATH always wins.
#[cfg(not(target_os = "windows"))]
fn apply_login_shell_path(command: &mut Command, login_path: Option<&str>, inherited: &str) {
    if let Some(login_path) = login_path {
        command.env(
            "PATH",
            crate::commands::merge_path_segments(login_path, inherited),
        );
    }
}

/// Always terminate the process group/job, even after a successful handshake.
/// A launcher can exit cleanly while its server child is still running.
struct ProbeProcess(Option<Box<dyn ChildWrapper>>);

impl Drop for ProbeProcess {
    fn drop(&mut self) {
        if let Some(mut child) = self.0.take() {
            let _ = child.start_kill();
            tokio::spawn(async move {
                let _ = child.wait().await;
            });
        }
    }
}

async fn handshake<T: Transport<RoleClient> + 'static>(
    transport: T,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let client = ClientInfo {
        client_info: Implementation {
            name: "cc-switch-connectivity".into(),
            version: env!("CARGO_PKG_VERSION").into(),
            ..Default::default()
        },
        ..Default::default()
    };
    // serve performs initialize + notifications/initialized. No tools are called.
    let service = client.serve(transport).await?;
    // A drop guard also closes the transport if the page leaves or we time out.
    let _ = service.cancel().await;
    Ok(())
}

fn is_unauthorized(error: &reqwest::Error) -> bool {
    error.status() == Some(reqwest::StatusCode::UNAUTHORIZED)
}

/// Remembers a 401 so the result can say "sign-in required" instead of
/// "connection failed": the server answered, it just wants the client's login.
#[derive(Clone)]
struct UnauthorizedAwareClient {
    client: reqwest::Client,
    unauthorized: Arc<AtomicBool>,
}

impl UnauthorizedAwareClient {
    fn note<T>(
        &self,
        result: Result<T, StreamableHttpError<reqwest::Error>>,
    ) -> Result<T, StreamableHttpError<reqwest::Error>> {
        if let Err(StreamableHttpError::AuthRequired(_)) = &result {
            self.unauthorized.store(true, Ordering::Relaxed);
        } else if let Err(StreamableHttpError::Client(error)) = &result {
            if is_unauthorized(error) {
                self.unauthorized.store(true, Ordering::Relaxed);
            }
        }
        result
    }
}

impl StreamableHttpClient for UnauthorizedAwareClient {
    type Error = reqwest::Error;

    async fn post_message(
        &self,
        uri: Arc<str>,
        message: rmcp::model::ClientJsonRpcMessage,
        session_id: Option<Arc<str>>,
        auth_header: Option<String>,
    ) -> Result<StreamableHttpPostResponse, StreamableHttpError<Self::Error>> {
        self.note(
            StreamableHttpClient::post_message(&self.client, uri, message, session_id, auth_header)
                .await,
        )
    }

    async fn delete_session(
        &self,
        uri: Arc<str>,
        session_id: Arc<str>,
        auth_header: Option<String>,
    ) -> Result<(), StreamableHttpError<Self::Error>> {
        StreamableHttpClient::delete_session(&self.client, uri, session_id, auth_header).await
    }

    async fn get_stream(
        &self,
        uri: Arc<str>,
        session_id: Arc<str>,
        last_event_id: Option<String>,
        auth_header: Option<String>,
    ) -> Result<BoxedSseResponse, StreamableHttpError<Self::Error>> {
        self.note(
            StreamableHttpClient::get_stream(
                &self.client,
                uri,
                session_id,
                last_event_id,
                auth_header,
            )
            .await,
        )
    }
}

/// A legacy SSE endpoint must not forward configured credentials to another host.
#[derive(Clone)]
struct SameOriginSseClient {
    client: reqwest::Client,
    origin: http::Uri,
    unauthorized: Arc<AtomicBool>,
}

impl SameOriginSseClient {
    fn note<T>(
        &self,
        result: Result<T, SseTransportError<reqwest::Error>>,
    ) -> Result<T, SseTransportError<reqwest::Error>> {
        if let Err(SseTransportError::Client(error)) = &result {
            if is_unauthorized(error) {
                self.unauthorized.store(true, Ordering::Relaxed);
            }
        }
        result
    }
}

impl SseClient for SameOriginSseClient {
    type Error = reqwest::Error;

    async fn post_message(
        &self,
        uri: http::Uri,
        message: rmcp::model::ClientJsonRpcMessage,
        auth_token: Option<String>,
    ) -> Result<(), SseTransportError<Self::Error>> {
        if uri.scheme() != self.origin.scheme() || uri.authority() != self.origin.authority() {
            return Err(SseTransportError::Io(std::io::Error::new(
                std::io::ErrorKind::PermissionDenied,
                "Cross-origin MCP message endpoint",
            )));
        }
        self.note(SseClient::post_message(&self.client, uri, message, auth_token).await)
    }

    async fn get_stream(
        &self,
        uri: http::Uri,
        last_event_id: Option<String>,
        auth_token: Option<String>,
    ) -> Result<BoxedSseResponse, SseTransportError<Self::Error>> {
        self.note(SseClient::get_stream(&self.client, uri, last_event_id, auth_token).await)
    }
}

#[cfg(windows)]
fn resolve_windows_command(program: &str, spec: &ConnectionSpec) -> std::path::PathBuf {
    use std::path::PathBuf;
    let path = PathBuf::from(program);
    if path.extension().is_some() {
        return path;
    }
    let path_env = spec
        .env
        .iter()
        .find(|(key, _)| key.eq_ignore_ascii_case("PATH"))
        .map(|(_, value)| std::ffi::OsString::from(value))
        .or_else(|| std::env::var_os("PATH"))
        .unwrap_or_default();
    let directories = if path.components().count() > 1 {
        vec![PathBuf::new()]
    } else {
        std::env::split_paths(&path_env).collect()
    };
    for directory in directories {
        for extension in ["exe", "cmd", "bat", "com"] {
            let candidate = directory.join(&path).with_extension(extension);
            if candidate.is_file() {
                return candidate;
            }
        }
    }
    path
}

#[cfg(test)]
mod tests;