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

9.4 KB
Raw Blame
//! ZCode MCP 同步和导入模块
//!
//! ZCode 的 MCP 配置使用标准的 `type: "stdio"` 格式(与 Claude Code 一致)。
//! 连接字段可直接透传,但 ZCode 把启用状态放在服务器条目的 `enabled` 字段,
//! 而 CC Switch 使用 `apps.zcode`,因此边界处要统一这一个字段。
//!
//! 与 OpenCode 的差异:OpenCode 把 MCP 和 provider 放在同一个 `opencode.json`,
//! 且使用非标准的 `local`/`remote` 类型;ZCode 把 MCP 单独放在 `cli/config.json`,
//! 且使用标准 stdio/sse/http 类型,与 CC Switch 统一格式一致。

use serde_json::Value;
use std::collections::HashMap;

use crate::app_config::{McpApps, McpServer, MultiAppConfig};
use crate::error::AppError;
use crate::zcode_config;

use super::validation::validate_server_spec;

// ============================================================================
// Helper Functions
// ============================================================================

/// Check if ZCode MCP sync should proceed
fn should_sync_zcode_mcp() -> bool {
    // Skip if ZCode config directory doesn't exist
    zcode_config::get_zcode_dir().exists()
}

/// CC Switch 的 `apps.zcode = true` 在 ZCode 配置中必须投影为
/// `enabled = true`,不能让统一配置里遗留的 `enabled: false` 覆盖应用状态。
fn spec_for_zcode(server_spec: &Value) -> Result<Value, AppError> {
    let mut spec = server_spec.clone();
    let object = spec
        .as_object_mut()
        .ok_or_else(|| AppError::McpValidation("MCP 服务器连接定义必须为 JSON 对象".into()))?;
    object.insert("enabled".to_string(), Value::Bool(true));
    Ok(spec)
}

/// 导入统一配置后,启用状态只由 `apps.zcode` 表达。显式的
/// `enabled = false` 会映射成 `apps.zcode = false`,而连接定义中不再保留该字段。
fn spec_from_zcode(mut spec: Value) -> (Value, bool) {
    let enabled = spec
        .as_object_mut()
        .and_then(|object| object.remove("enabled"))
        .and_then(|value| value.as_bool())
        .unwrap_or(true);
    (spec, enabled)
}

// ============================================================================
// Public API: Sync Functions
// ============================================================================

/// Sync a single MCP server to ZCode live config.
///
/// ZCode uses the standard connection format; only its embedded enabled flag
/// is normalized from the CC Switch app selection.
pub fn sync_single_server_to_zcode(id: &str, server_spec: &Value) -> Result<(), AppError> {
    if !should_sync_zcode_mcp() {
        return Ok(());
    }

    zcode_config::set_mcp_server(id, spec_for_zcode(server_spec)?)
}

/// 写入(`spec` 为 `Some`)或移除一个 MCP 条目,文件写成功后才提交数据库(见
/// [`zcode_config::sync_mcp_server_and_commit`])。ZCode 没装(没有配置目录)时只提交。
pub(crate) fn sync_and_commit<T>(
    id: &str,
    spec: Option<&Value>,
    commit: impl FnOnce() -> Result<T, AppError>,
) -> Result<T, AppError> {
    if !should_sync_zcode_mcp() {
        return commit();
    }
    let spec = spec.map(spec_for_zcode).transpose()?;
    zcode_config::sync_mcp_server_and_commit(id, spec, commit)
}

/// Remove a single MCP server from ZCode live config
pub fn remove_server_from_zcode(id: &str) -> Result<(), AppError> {
    if !should_sync_zcode_mcp() {
        return Ok(());
    }

    zcode_config::remove_mcp_server(id)
}

/// Import MCP servers from ZCode config to unified structure.
///
/// Existing servers will have the ZCode app enabled without overwriting other
/// fields. Connection fields use the standard format; the embedded enabled
/// flag is removed because CC Switch stores that state in `apps.zcode`.
pub fn import_from_zcode(config: &mut MultiAppConfig) -> Result<usize, AppError> {
    let mcp_map = zcode_config::get_mcp_servers()?;
    if mcp_map.is_empty() {
        return Ok(0);
    }

    // Ensure servers map exists
    let servers = config.mcp.servers.get_or_insert_with(HashMap::new);

    let mut changed = 0;
    let mut errors = Vec::new();

    for (id, spec) in mcp_map {
        let (spec, zcode_enabled) = spec_from_zcode(spec);
        // Validate the normalized standard connection spec.
        if let Err(e) = validate_server_spec(&spec) {
            log::warn!("Skip invalid ZCode MCP server '{id}': {e}");
            errors.push(format!("{id}: {e}"));
            continue;
        }

        if let Some(existing) = servers.get_mut(&id) {
            // Existing server: enable ZCode and clean up any legacy embedded
            // enabled flag without overwriting its other connection fields.
            let mut server_changed = existing
                .server
                .as_object_mut()
                .is_some_and(|server| server.remove("enabled").is_some());
            if existing.apps.zcode != zcode_enabled {
                existing.apps.zcode = zcode_enabled;
                server_changed = true;
            }
            if server_changed {
                changed += 1;
                log::info!("MCP server '{id}' normalized for ZCode (enabled={zcode_enabled})");
            }
        } else {
            // New server: default to only ZCode enabled
            servers.insert(
                id.clone(),
                McpServer {
                    id: id.clone(),
                    name: id.clone(),
                    server: spec,
                    apps: McpApps {
                        claude: false,
                        codex: false,
                        gemini: false,
                        grokbuild: false,
                        opencode: false,
                        hermes: false,
                        mcode: false,
                        pi: false,
                        agy: false,
                        kimi: false,
                        omp: false,
                        copilot: false,
                        dsh: false,
                        workbuddy: false,
                        codebuddy: false,
                        zcode: zcode_enabled,
                        qoder: false,
                    },
                    description: None,
                    homepage: None,
                    docs: None,
                    tags: Vec::new(),
                },
            );
            changed += 1;
            log::info!("Imported new MCP server '{id}' from ZCode");
        }
    }

    if !errors.is_empty() {
        log::warn!(
            "Import completed with {} failures: {:?}",
            errors.len(),
            errors
        );
    }

    Ok(changed)
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use serial_test::serial;

    #[test]
    fn test_stdio_spec_passes_through_validation() {
        // ZCode uses the standard stdio format; validate_server_spec must accept it
        // as-is (no conversion). This mirrors the import path.
        let spec = json!({
            "type": "stdio",
            "command": "npx",
            "args": ["-y", "tavily-mcp"],
            "env": { "TAVILY_API_KEY": "xxx" }
        });
        // Should not error — stdio with command is valid
        validate_server_spec(&spec).expect("stdio spec is valid");
    }

    #[test]
    fn test_sse_spec_passes_through_validation() {
        // sse/http specs are also passed through without conversion
        let spec = json!({
            "type": "sse",
            "url": "https://example.com/mcp",
            "headers": { "Authorization": "Bearer xxx" }
        });
        validate_server_spec(&spec).expect("sse spec is valid");
    }

    #[test]
    fn export_forces_zcode_enabled_state() {
        let spec = json!({
            "type": "stdio",
            "command": "npx",
            "enabled": false
        });

        let exported = spec_for_zcode(&spec).expect("object spec");
        assert_eq!(exported["enabled"], json!(true));
        assert_eq!(spec["enabled"], json!(false), "input must not be mutated");
    }

    #[test]
    fn import_removes_embedded_zcode_enabled_state() {
        let (imported, enabled) = spec_from_zcode(json!({
            "type": "stdio",
            "command": "npx",
            "enabled": false
        }));

        assert!(imported.get("enabled").is_none());
        assert_eq!(imported["command"], json!("npx"));
        assert!(!enabled);
    }

    #[test]
    #[serial]
    fn test_import_marks_new_server_with_only_zcode_enabled() {
        // Isolate from the real ~/.zcode by pointing the home dir at a temp
        // directory so import_from_zcode sees an empty cli/config.json.
        // CC_SWITCH_TEST_HOME is process-global: without #[serial] this test
        // runs in parallel with hermes_config's serial tests and its
        // set/remove of the var can hijack their memory-path resolution
        // mid-test (seen on windows-latest CI as
        // write_then_read_memory_round_trip reading back "").
        let temp = tempfile::tempdir().unwrap();
        let old = std::env::var_os("CC_SWITCH_TEST_HOME");
        std::env::set_var("CC_SWITCH_TEST_HOME", temp.path());

        let mut config = MultiAppConfig::default();
        // With no ~/.zcode/cli/config.json present, import is a clean no-op.
        let count = import_from_zcode(&mut config).expect("empty import ok");
        assert_eq!(count, 0);

        match old {
            Some(value) => std::env::set_var("CC_SWITCH_TEST_HOME", value),
            None => std::env::remove_var("CC_SWITCH_TEST_HOME"),
        }
    }
}