mcp: load Claude Code user, project and local servers

Read ~/.claude.json mcpServers (user), .mcp.json (project) and
~/.claude.json projects[<dir>].mcpServers (local) alongside the hx files.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Johannes KresnerandClaude Opus 5.5 committed 2026-11-04 12:38:58 +01:00
1 parent ca6b917b17
commit 0c9a197fd5
2 files changed
+101 -12

No files matched your search

+97 -10
View File
@@ -1,8 +1,10 @@
//! MCP config: `~/.hx/mcp.json` + `.hx/mcp.json` (project wins per server), Claude Code `mcpServers` shape.
//! MCP config in the Claude Code `mcpServers` shape. Sources, lowest priority first: `~/.claude.json` (user),
//! `~/.hx/mcp.json`, `.mcp.json` (Claude Code project), `~/.claude.json` `projects[<dir>]` (Claude Code local),
//! `.hx/mcp.json`. A later entry replaces an earlier one with the same name.
use serde::Deserialize;
use std::collections::BTreeMap;
use std::path::Path;
use std::path::{Path, PathBuf};
#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
#[serde(default, rename_all = "camelCase")]
@@ -84,15 +86,29 @@ pub fn parse(json: &str) -> Result<BTreeMap<String, Server>, String> {
.map_err(|e| e.to_string())
}
/// Global then project; a project entry replaces the global one with the same name. Disabled are dropped.
/// All sources (see module docs) for `cwd`; `home` is the hx home. Disabled are dropped.
pub fn load(home: &Path, cwd: &Path) -> Result<BTreeMap<String, Server>, String> {
let mut all = BTreeMap::new();
for p in [home.join("mcp.json"), cwd.join(".hx/mcp.json")] {
let Ok(s) = std::fs::read_to_string(&p) else {
continue;
};
all.extend(parse(&s).map_err(|e| format!("{}: {e}", p.display()))?);
}
let claude = std::env::var_os("HOME").map(|h| Path::new(&h).join(".claude.json"));
load_from(home, claude.as_deref(), cwd)
}
pub fn load_from(
home: &Path,
claude_json: Option<&Path>,
cwd: &Path,
) -> Result<BTreeMap<String, Server>, String> {
let (user, local) = claude_json.map(|p| claude_code(p, cwd)).unwrap_or_default();
let mut all = user;
let file = |p: PathBuf| -> Result<BTreeMap<String, Server>, String> {
match std::fs::read_to_string(&p) {
Ok(s) => parse(&s).map_err(|e| format!("{}: {e}", p.display())),
Err(_) => Ok(BTreeMap::new()),
}
};
all.extend(file(home.join("mcp.json"))?);
all.extend(file(cwd.join(".mcp.json"))?);
all.extend(local);
all.extend(file(cwd.join(".hx/mcp.json"))?);
let env = |k: &str| std::env::var(k).ok();
Ok(all
.into_iter()
@@ -101,6 +117,30 @@ pub fn load(home: &Path, cwd: &Path) -> Result<BTreeMap<String, Server>, String>
.collect())
}
type Servers = BTreeMap<String, Server>;
/// `~/.claude.json`: top-level `mcpServers` (user scope) and those of the nearest `projects` entry at or
/// above `cwd` (local scope). Claude Code owns this file, so a broken one is ignored rather than fatal.
fn claude_code(path: &Path, cwd: &Path) -> (Servers, Servers) {
let Some(v) = std::fs::read_to_string(path)
.ok()
.and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
else {
return Default::default();
};
let servers = |v: Option<&serde_json::Value>| -> Servers {
v.and_then(|m| serde_json::from_value(m.clone()).ok())
.unwrap_or_default()
};
let user = servers(v.get("mcpServers"));
let local = cwd
.ancestors()
.find_map(|d| v.get("projects")?.get(d.to_str()?))
.map(|p| servers(p.get("mcpServers")))
.unwrap_or_default();
(user, local)
}
#[cfg(test)]
mod t {
use super::*;
@@ -137,4 +177,51 @@ mod t {
std::fs::write(cwd.join(".hx/mcp.json"), "{nope").unwrap();
assert!(load(&home, &cwd).unwrap_err().contains(".hx/mcp.json"));
}
#[test]
fn claude_code_sources() {
let d = tempfile::tempdir().unwrap();
let (home, root) = (d.path().join("h"), d.path().join("p"));
let cwd = root.join("sub");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(cwd.join(".hx")).unwrap();
let claude = d.path().join(".claude.json");
std::fs::write(
&claude,
serde_json::json!({
"mcpServers": {"u": {"command": "u"}, "a": {"command": "user"}},
"projects": {root.to_str().unwrap(): {"mcpServers": {"l": {"command": "l"}, "a": {"command": "local"}}}},
})
.to_string(),
)
.unwrap();
std::fs::write(
home.join("mcp.json"),
r#"{"mcpServers":{"a":{"command":"hx"}}}"#,
)
.unwrap();
std::fs::write(
cwd.join(".mcp.json"),
r#"{"mcpServers":{"p":{"command":"p"}}}"#,
)
.unwrap();
let m = load_from(&home, Some(&claude), &cwd).unwrap();
assert_eq!(m.keys().collect::<Vec<_>>(), ["a", "l", "p", "u"]);
assert_eq!(m["a"].command.as_deref(), Some("local"));
std::fs::write(
cwd.join(".hx/mcp.json"),
r#"{"mcpServers":{"a":{"command":"proj"}}}"#,
)
.unwrap();
assert_eq!(
load_from(&home, Some(&claude), &cwd).unwrap()["a"]
.command
.as_deref(),
Some("proj")
);
std::fs::write(&claude, "{broken").unwrap();
assert_eq!(load_from(&home, Some(&claude), &cwd).unwrap().len(), 2);
}
}