atomcode /mcp 管理面板数据层实施指南:含停用项的读取、来源映射与安全写入器

原创2026-10-14 09:58:591,762 阅读
文章标签:人工智能AI 应用AI Agent代码智能体CLIAI 评测

atomcode /mcp 管理面板数据层实施指南:含停用项的读取、来源映射与安全写入器

本文以 docs/mcp-panel-plan-1-data.md 为主体骨架,结合 docs/mcp-panel-design.md、docs/mcp-panel-plan-2-commands.md 及 atomcode-capabilities / atomcode-coding / atomcode-cli 的当前源码实现,讲解如何在 Rust 工作区中为 /mcp 交互式管理面板落地「数据层」:让 MCP 配置读取能看见被停用的服务器、把"来源 → 配置文件"的映射收敛为单一函数,并实现一个只改既有条目、绝不新增的停用/启用写入器。

这篇指南面向要在 atomcode 仓库内实施或理解该面板数据层的工程师:读完后你将掌握三条完整可运行的核心路径(含停用项读取、来源路径映射、就地写回),理解注释守卫的取舍逻辑,并学会用 cargo nextest 以 --features mcp 正确驱动这一层(这个坑会直接决定你的测试报告是否"假绿")。

1. 背景:为什么面板需要一个"数据层"

/mcp 在 atomcode-tui 里原本只是 crates/atomcode-tui/src/commands.rs 中的一列文本:无参调用变成一次 HostCommand::McpStatus,把服务器名和状态拼成字符串打印。人看不到工具数、看不到来源,也不能改任何东西。

设计目标(见 docs/mcp-panel-design.md §1)是把它做成交互式管理面板:列表按来源分组、每行带状态与工具数,Enter 钻进二级面板看配置与诊断,并在面板里完成信任、认证、启用/停用。要支撑这些交互,第一条硬前提是——停用项今天根本读不到:

// crates/atomcode-capabilities/src/mcp/config.rs 中 load_mcp_config 的过滤逻辑
Ok(merged.into_values().filter(|c| !c.disabled).collect())

disabled 字段本身早已存在(McpServerEntry 中 #[serde(default)] disabled: bool,配置写 disabled: true 是已支持的格式),但运行时读取路径会在最后一步把它滤掉。面板要显示 ○ 已停用 并让"重新启用"这个开关可触及,就必须另开一条保留停用项的读取路径。这就是数据层(计划 1)存在的全部理由。

数据层划定的范围与边界(设计 §3):

层 加什么 为什么是这一层
atomcode-capabilities::mcp ① 一条含停用项的读取路径 ② 来源→文件路径映射 ③ set_…_disabled() 写入器 配置读写是 capabilities 的职责;写入器已有两个先例可照抄(merge_stdio_mcp_server_into_json_file 与 add_auto_approved_tool),连注释守卫一起沿用

明确不做(计划 1 的边界):

  • 不碰 McpServerState(加 NeedsAuthentication / Disabled 变体是命令层计划 2 的事)
  • 不碰 host / runtime / TUI
  • 不做"新增服务器到配置文件"(merge_* 两个写入器已覆盖,面板不需要)
  • 不做删除服务器

所有改动只落在一个文件:crates/atomcode-capabilities/src/mcp/config.rs(该模块约 1100+ 行,读写同一份格式的知识不应被拆开)。

2. 前置:mcp 是 opt-in feature,别信"假绿"报告

crates/atomcode-capabilities/src/lib.rs 里 mcp 模块由 #[cfg(feature = "mcp")] pub mod mcp; 守卫,而 crates/atomcode-capabilities/Cargo.toml 的默认 feature 是:

[features]
default = ["provider", "tools"]
mcp = ["dep:atomcode-config", "dep:anyhow", "dep:sha2", "dep:uuid", "dep:dirs", "dep:toml", "dep:tempfile", "dep:reqwest", "reqwest/blocking", "dep:url", "tokio/process", "tokio/io-util"]

不带 --features mcp 跑测试,整个 mcp 模块根本不参与编译——测试报告会"全绿",但一个相关用例都没执行。实测数字:默认组合 947 个用例,带 mcp 是 1066 个,差的 119 个全是 mcp 模块的。

因此本计划所有测试命令都必须写:

cargo nextest run -p atomcode-capabilities --features mcp

注意第二个坑(来自计划 2 的实测):crates/atomcode-cli/ 的包名是 atomcode 而不是 atomcode-cli([package] name = "atomcode"),-p atomcode-cli 会报 did not match any packages;命令层测试要用 -p atomcode。

3. Task 1:一条保留停用项的读取路径

3.1 先写失败的测试

在 config.rs 的 mod tests 中新增测试。用带前缀的服务器名,避免与真实用户配置 $ATOMCODE_HOME/mcp.json 撞名——这条路径会读用户级配置:

#[test]
fn listing_shows_disabled_servers_that_loading_still_hides() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(
        dir.path().join(".mcp.json"),
        r#"{"mcpServers":{
            "panel-test-on":  {"command":"npx","args":["-y","a"]},
            "panel-test-off": {"command":"npx","args":["-y","b"],"disabled":true}
        }}"#,
    )
    .unwrap();

    let listed = load_mcp_config_including_disabled(dir.path()).unwrap();
    let names: Vec<&str> = listed.iter().map(|c| c.name.as_str()).collect();
    assert!(
        names.contains(&"panel-test-off"),
        "the management list shows disabled servers: {names:?}"
    );
    assert!(
        listed
            .iter()
            .find(|c| c.name == "panel-test-off")
            .unwrap()
            .disabled
    );

    let loaded = load_mcp_config(dir.path()).unwrap();
    let names: Vec<&str> = loaded.iter().map(|c| c.name.as_str()).collect();
    assert!(
        !names.contains(&"panel-test-off"),
        "the runtime load still withholds it: {names:?}"
    );
    assert!(names.contains(&"panel-test-on"));
}

预期:编译失败,cannot find function 'load_mcp_config_including_disabled' in this scope。

3.2 把"合并"拆出来,再加公开入口

把 load_mcp_config 那一段(含其上方四行文档注释,否则替换后旧注释会孤零零悬在新函数上方)整体替换为:

/// Merge the user-level and project-level configs, disabled entries included.
///
/// Project overrides user for a server of the same name. This is the whole read; whether
/// disabled servers are withheld is the caller's decision — see [`load_mcp_config`] and
/// [`load_mcp_config_including_disabled`].
fn merge_configs(project_dir: &Path) -> Result<Vec<McpServerConfig>> {
    let user_config = load_config_file(
        &crate::mcp::util::config_dir().join("mcp.json"),
        McpConfigSource::User,
    )?;

    let project_config =
        load_config_file(&project_dir.join(".mcp.json"), McpConfigSource::Project)?;

    // Merge: project overrides user
    let mut merged: BTreeMap<String, McpServerConfig> = BTreeMap::new();

    for config in user_config {
        merged.insert(config.name.clone(), config);
    }

    for config in project_config {
        merged.insert(config.name.clone(), config);
    }

    Ok(merged.into_values().collect())
}

/// Load and merge MCP configurations from project and user levels.
///
/// Project config (`.mcp.json` in project root) overrides user config
/// (`ATOMCODE_HOME/mcp.json`) for servers with the same name.
///
/// Servers configured with `disabled: true` are withheld: they are not a tool source for a
/// running session. A surface that manages them wants the other entry point, below.
pub fn load_mcp_config(project_dir: &Path) -> Result<Vec<McpServerConfig>> {
    Ok(merge_configs(project_dir)?
        .into_iter()
        .filter(|c| !c.disabled)
        .collect())
}

/// The same merge as [`load_mcp_config`], but keeping `disabled` servers.
///
/// A management surface has to show a server it is offering to re-enable; hiding it would
/// make the switch one-way. Nothing that builds a tool catalog may use this.
pub fn load_mcp_config_including_disabled(project_dir: &Path) -> Result<Vec<McpServerConfig>> {
    merge_configs(project_dir)
}

两条纪律在这里写死:

  • 运行时读取行为不变:load_mcp_config 的返回与改动前逐字一致,只是内部改为 merge_configs + 过滤。既有判据 shipped_mcp_json_example_parses_as_is、load_mcp_config_reports_malformed_project_file 都依赖这一点。
  • 含停用项路径的用途被约束:文档注释明确"Nothing that builds a tool catalog may use this"——只有管理面可以用它,工具目录的构建者必须继续过滤。

(当前主分支上的实际实现已演进为双参数版本 load_mcp_config(project_dir, user_dir) 与 load_mcp_config_including_disabled(project_dir, user_dir),并抽象出 project_over_user 辅助函数,见 crates/atomcode-capabilities/src/mcp/config.rs;合并逻辑还经由 McpStorage 支持 host 托管用户级配置的场景,见 config.rs。)

3.3 跑测试并提交

cargo nextest run -p atomcode-capabilities --features mcp

预期全绿。提交信息示例:

git add crates/atomcode-capabilities/src/mcp/config.rs
git commit -F - <<'EOF'
feat(mcp): 另给一条保留停用项的读取路径

管理面板要能显示 ○ 已停用,否则"启用"这个开关就是单向的——关掉之后再
也看不见它。把合并那一步从 load_mcp_config 里拆出来,运行时那条继续过滤,
新入口 load_mcp_config_including_disabled 不过滤。

运行时行为未变: load_mcp_config 的返回与改动前逐字相同。

Co-Authored-By: AtomCode (deepseek-flash) <noreply@atomgit.com>
EOF

4. Task 2:来源 → 配置文件的路径映射

写入器必须落到定义该服务器的那个文件里。这个映射今天散在两处:load_mcp_config 里各 join 一次,add_auto_approved_tool 里又自己判一次。收敛成一个函数,写入器与将来的调用方共用。

4.1 测试:三种来源三种预期

#[test]
fn a_driver_server_has_no_config_file_to_write() {
    let dir = tempfile::tempdir().unwrap();

    assert_eq!(
        config_path_for_source(dir.path(), McpConfigSource::Project),
        Some(dir.path().join(".mcp.json")),
        "a project server lives in the project root"
    );
    assert!(
        config_path_for_source(dir.path(), McpConfigSource::User).is_some(),
        "a user server lives under ATOMCODE_HOME"
    );
    assert_eq!(
        config_path_for_source(dir.path(), McpConfigSource::Driver),
        None,
        "a driver-supplied server was never read from a file, so there is none to edit"
    );
}

4.2 实现

紧跟在 load_mcp_config_including_disabled 之后:

/// The file a server of this source is read from and written back to.
///
/// `None` for [`McpConfigSource::Driver`]: those servers arrive over the wire (an ACP client
/// injecting `mcpServers` in `session/new`) and have no file to edit. A caller that is about
/// to report "disabled" must treat `None` as "not applicable", not as "not found".
pub fn config_path_for_source(
    project_dir: &Path,
    source: McpConfigSource,
) -> Option<std::path::PathBuf> {
    match source {
        McpConfigSource::User => Some(crate::mcp::util::config_dir().join("mcp.json")),
        McpConfigSource::Project => Some(project_dir.join(".mcp.json")),
        McpConfigSource::Driver => None,
    }
}

三个来源的语义(对应 config.rs 中 McpConfigSource 的注释):

来源 文件 说明
Project project_dir/.mcp.json 项目根下、随项目提交
User <user tree>/mcp.json(即 $ATOMCODE_HOME/mcp.json) 所有项目共享;可能装有凭据
Driver 无(None) ACP 客户端在 session/new 时通过 wire 注入,客户端即信任边界

Driver 返回 None 是关键语义:调用方准备上报"已停用"时,必须把 None 理解为"不适用",而不是"未找到"。

5. Task 3:停用 / 启用写入器

这是数据层最核心的交付。模子取两个既有先例:

  • merge_stdio_mcp_server_into_json_file(config.rs):同一个文件、同一份格式;
  • add_auto_approved_tool:就地改已有条目,而不是整条替换。

守卫照 read_json_for_rewrite(当前实现为 json_for_rewrite)。

5.1 三条失败的测试

#[test]
fn a_disabled_server_is_written_and_read_back() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join(".mcp.json");
    std::fs::write(
        &target,
        r#"{"mcpServers":{"srv":{"command":"npx","args":["-y","a"]}}}"#,
    )
    .unwrap();

    set_mcp_server_disabled_in_json_file(&target, "srv", true).unwrap();

    let configs = load_config_file(&target, McpConfigSource::Project).unwrap();
    assert_eq!(configs.len(), 1);
    assert!(configs[0].disabled, "the flag must survive a reload");

    set_mcp_server_disabled_in_json_file(&target, "srv", false).unwrap();

    let configs = load_config_file(&target, McpConfigSource::Project).unwrap();
    assert!(!configs[0].disabled);
    let text = std::fs::read_to_string(&target).unwrap();
    assert!(
        !text.contains("disabled"),
        "enabling removes the key instead of writing false: {text}"
    );
}

#[test]
fn disabling_a_server_the_file_does_not_define_is_an_error() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join(".mcp.json");
    let original = r#"{"mcpServers":{"srv":{"command":"npx"}}}"#;
    std::fs::write(&target, original).unwrap();

    let error = set_mcp_server_disabled_in_json_file(&target, "nope", true).unwrap_err();
    assert!(
        error.to_string().contains("not defined"),
        "unexpected error: {error}"
    );
    assert_eq!(
        std::fs::read_to_string(&target).unwrap(),
        original,
        "a refused write must leave the file byte-identical"
    );
}

#[test]
fn a_server_under_the_legacy_servers_key_can_still_be_disabled() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join(".mcp.json");
    std::fs::write(&target, r#"{"servers":{"srv":{"command":"npx"}}}"#).unwrap();

    set_mcp_server_disabled_in_json_file(&target, "srv", true).unwrap();

    let configs = load_config_file(&target, McpConfigSource::Project).unwrap();
    assert!(configs[0].disabled);
    let text = std::fs::read_to_string(&target).unwrap();
    assert!(
        !text.contains("\"servers\""),
        "the legacy key is folded into mcpServers, same as the other writers: {text}"
    );
}

这三条测试分别钉住:持久性(写后读回 disabled 仍为 true)、启用即删键(写 false 会在文件里留下噪音,而 McpServerEntry::disabled 是 #[serde(default)],两种写法读者等价)、只改不增(文件里没有该服务器时报错而不是补一条)、以及旧 servers 键兼容(先折叠再写回,与其它写入器行为一致)。

5.2 实现

/// Turn one configured server off or back on, in the file that defines it.
///
/// Turning off writes `disabled: true`. Turning on **removes** the key rather than writing
/// `false`, so an enabled entry reads exactly like one that never carried it
/// (`McpServerEntry::disabled` is `#[serde(default)]`).
///
/// Bails, leaving the file byte-identical, when the file carries JSONC comments (see
/// [`read_json_for_rewrite`]) or when it does not define `server_key`. This edits an existing
/// entry; it never adds a server.
pub fn set_mcp_server_disabled_in_json_file(
    path: &Path,
    server_key: &str,
    disabled: bool,
) -> Result<()> {
    if server_key.is_empty() {
        bail!("MCP server name must not be empty");
    }

    let mut root: Value = read_json_for_rewrite(path)?;

    let root_obj = root
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("MCP config root must be a JSON object"))?;

    // Merge the legacy `servers` key into `mcpServers` first, so the edit lands on the entry
    // a reader would resolve — and is written back in one place.
    let mut servers = collect_merged_mcp_server_maps(root_obj);
    let entry = servers.get_mut(server_key).ok_or_else(|| {
        anyhow::anyhow!(
            "MCP server '{server_key}' is not defined in {}",
            path.display()
        )
    })?;
    let entry_obj = entry
        .as_object_mut()
        .ok_or_else(|| anyhow::anyhow!("MCP server '{server_key}' entry is not an object"))?;

    if disabled {
        entry_obj.insert("disabled".to_string(), Value::Bool(true));
    } else {
        entry_obj.remove("disabled");
    }

    root_obj.insert("mcpServers".to_string(), Value::Object(servers));
    root_obj.remove("servers");

    let text = serde_json::to_string_pretty(&root).context("Failed to serialize MCP config")?;
    std::fs::write(path, format!("{text}\n"))
        .with_context(|| format!("Failed to write MCP config to {}", path.display()))?;

    Ok(())
}

实现要点拆解:

  • collect_merged_mcp_server_maps(config.rs):先合并旧的 servers 键与 mcpServers 键,让编辑落在读取方会解析到的条目上,且只写回一处;servers 键最后被移除——与 merge_stdio_mcp_server_into_json_file 等既有写入器行为完全一致。
  • 其它顶层键被保留:只改 mcpServers / servers 两个键,根对象里其它键原样序列化回去。
  • 启用删除而非写 false:McpServerEntry::disabled 带 #[serde(default)],两种写法读者等价,但删除不会在文件里留下一堆 false 噪音。
  • 只改不增:servers.get_mut(server_key) 找不到就 bail!,且拒绝写入前文件保持字节不变。

(当前主分支上的实际实现把"文件"与"文本"两条路径拆开:set_mcp_server_disabled_in_json_file 内部复用 read_config_text + with_server_disabled,并公开了 set_mcp_server_disabled_in_text 供托管用户级配置的 host 使用,见 config.rs;McpStorage::set_server_disabled 则把"host 托管 / 文件"两种存储统一起来,见 config.rs。)

5.3 跑测试并提交

cargo nextest run -p atomcode-capabilities --features mcp

预期全绿。

6. Task 4:锁定注释守卫

写入器必须走 read_json_for_rewrite,而不是自己 serde_json::from_str。这条测试是那道门的凭据:

#[test]
fn a_config_with_comments_refuses_the_disable_rewrite() {
    let dir = tempfile::tempdir().unwrap();
    let target = dir.path().join(".mcp.json");
    let original = "{\n  // 别删我\n  \"mcpServers\": {\"srv\": {\"command\": \"npx\"}}\n}";
    std::fs::write(&target, original).unwrap();

    let error = set_mcp_server_disabled_in_json_file(&target, "srv", true).unwrap_err();
    assert!(
        error.to_string().contains("contains comments"),
        "unexpected error: {error}"
    );
    assert_eq!(
        std::fs::read_to_string(&target).unwrap(),
        original,
        "a refused rewrite must leave the file byte-identical"
    );
}

关键预期:这条测试一写就该 PASS,且不需要写任何新代码。 它锁的是继承来的行为。如果它失败,说明写入器没真的走 read_json_for_rewrite(比如自己调了 serde_json::from_str)——那是必须修的 bug,不是测试的问题。

注释守卫的原文逻辑(config.rs):

A rewrite serialises the parsed Value back out, which would silently delete every comment in the file. Refuse instead: the read path tolerates comments, so the config still works — it just cannot be edited for you. Losing someone's annotations without telling them is worse than making them edit by hand.

守卫通过 crate::jsonc::strip_comments(text) != text 检测 JSONC 注释(has_json_comments)。失败语义(设计 §6)同样写死:一律说出来,不静默——面板遇到守卫拒绝时显示守卫原文 + "请手工编辑或删掉注释后重试"。

7. Task 5:交付门

  • Step 1:整个 crate 跑一遍

    cargo nextest run -p atomcode-capabilities --features mcp
    

    预期全绿。不要用 --workspace——9 个 consumer 各开不同的 feature 子集,全量构建会编 19 份 capabilities。

  • Step 2:格式门(check.yml 里唯一的阻塞门)

    cargo fmt --all
    cargo fmt --all -- --check
    

    第二条必须退出 0。若 cargo fmt --all 改动了文件,单独成一个 commit,不要混进功能 commit。

  • Step 3:确认运行时读取未被影响

    git diff 02b73ada3 -- crates/atomcode-capabilities/src/mcp/config.rs
    

    人工核对这份 diff:load_mcp_config 的返回语义必须与改动前逐字一致,只是内部改成了 merge_configs + 过滤。

8. 覆盖对照与后续衔接

对着 docs/mcp-panel-design.md §7 的测试判据逐条核对:

设计 §7 判据 落点
a_disabled_server_is_written_and_read_back Task 3 Step 1
a_config_with_comments_refuses_the_disable_rewrite Task 4 Step 1
listing_shows_disabled_servers_that_loading_still_hides Task 1 Step 1
a_driver_server_has_no_config_file_to_write Task 2 Step 1(计划新增判据,服务设计 §5.1 的 driver 组)
a_server_under_the_legacy_servers_key_can_still_be_disabled Task 3 Step 1(计划新增,锁住 servers 别名被折叠)

设计 §7 里 atomcode-host-api / atomcode-cli / atomcode-tui 三行不在本计划内——它们属于命令层(计划 2,读路径)与面板层(计划 3)。数据层完成后,上层将这样消费它(见 docs/mcp-panel-plan-2-commands.md Task 4):

join 数据来源 给出 取自
静态配置 name / disabled / source / transport load_mcp_config_including_disabled(计划 1 交付)
配置文件路径 该写回哪个文件 config_path_for_source(计划 1 交付)
实时状态 Connecting / Connected / Untrusted / Failed / Disconnected parts.mcp_statuses()
认证 有没有可用 token McpTokenStore::default().load_token(name)
工具数 模型实际拿到几个 parts.mcp_tools_for_server(name).len()

两条 join 纪律同时被数据层的设计所支撑:① 停用项不进树,状态恒为 Disabled、工具数恒为 0,也不去问连接状态;② 不为了让面板显示就去建连接——认证状态靠读 token store 推导。McpRowFacts(crates/atomcode-coding/src/parts.rs)的字段设计正是这条纪律的落地:它只带 command/args 与 url,绝不带 env 与 headers——后两者是凭据住的地方(stdio 服务器的 env、HTTP 服务器的 headers 可能装着 Authorization: Bearer …)。

9. 从源码结构看:数据层的实际落地形态

计划文档写的是针对 feat/mcp-panel 分支的改造方案;对照当前主分支源码,数据层三件事均已落地,且形态更完整:

  1. 含停用项读取:load_mcp_config_including_disabled(project_dir, user_dir) 已公开于 crates/atomcode-capabilities/src/mcp/config.rs,并经由 McpStorage::load_including_disabled 支持 host 托管用户级文档(with_user_config / with_tokens,见 config.rs)。文档注释明确"Nothing that builds a tool catalog may use this"。
  2. 来源映射:config_path_for_source(project_dir, user_dir, source) 已公开(config.rs),McpStorage::path_for 在 host 托管用户级配置时返回 None(没有可展示/可打开的文件)。
  3. 写入器:set_mcp_server_disabled_in_json_file 与 set_mcp_server_disabled_in_text 双路径已就位(config.rs),统一走 json_for_rewrite 注释守卫,启用即删键、只改不增、拒绝时字节不变。

mod.rs 的 pub use 清单(crates/atomcode-capabilities/src/mcp/mod.rs)也已把 config_path_for_source、load_mcp_config_including_disabled、McpConfigSource 等符号全部导出——计划 2 曾专门提醒过:初稿漏了这三个符号的导出,会让命令层的 join 代码解析不了。

数据层是 /mcp 面板三段式交付的第一段:它不产生任何 UI 效果,但为面板提供了"看得见停用项、找得到配置文件、改得动状态"的全部底层能力。读路径与写路径在此被清晰分离——面板的列表与详情页(计划 2 + 3)在数据层之上纯读,而"停用/启用"这一写操作在数据层即被注释守卫与"只改不增"的语义约束住,从根上避免了对用户 mcp.json 的破坏性改写。

登录后查看全文
atomcode