141 lines
5.1 KiB
Rust
141 lines
5.1 KiB
Rust
//! MCP config: `~/.hx/mcp.json` + `.hx/mcp.json` (project wins per server), Claude Code `mcpServers` shape.
|
|
|
|
use serde::Deserialize;
|
|
use std::collections::BTreeMap;
|
|
use std::path::Path;
|
|
|
|
#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
|
|
#[serde(default, rename_all = "camelCase")]
|
|
pub struct Server {
|
|
/// stdio: program + args
|
|
pub command: Option<String>,
|
|
pub args: Vec<String>,
|
|
pub env: BTreeMap<String, String>,
|
|
/// streamable HTTP endpoint
|
|
pub url: Option<String>,
|
|
pub headers: BTreeMap<String, String>,
|
|
/// "stdio" | "http" | "sse"; inferred when absent
|
|
#[serde(rename = "type")]
|
|
pub kind: Option<String>,
|
|
/// hx: register tools as native tools instead of the lazy index
|
|
pub eager: Option<bool>,
|
|
/// hx: only these tools are exposed (empty = all)
|
|
pub allow: Vec<String>,
|
|
/// hx: per-call timeout (`timeoutSecs` or `timeout_secs`)
|
|
#[serde(alias = "timeout_secs")]
|
|
pub timeout_secs: Option<u64>,
|
|
pub disabled: bool,
|
|
/// hx: HTTP OAuth overrides (`hx mcp login <name>` works without; needed for servers lacking dynamic registration)
|
|
pub oauth: OauthCfg,
|
|
}
|
|
|
|
#[derive(Debug, Clone, PartialEq, Deserialize, Default)]
|
|
#[serde(default, rename_all = "camelCase")]
|
|
pub struct OauthCfg {
|
|
pub client_id: Option<String>,
|
|
pub client_secret: Option<String>,
|
|
pub scope: Option<String>,
|
|
/// fixed redirect port (default: random free port)
|
|
pub callback_port: Option<u16>,
|
|
/// token store override (tests)
|
|
#[serde(skip)]
|
|
pub store: Option<std::path::PathBuf>,
|
|
}
|
|
|
|
#[derive(Debug, Default, Deserialize)]
|
|
#[serde(rename_all = "camelCase")]
|
|
struct File {
|
|
#[serde(default)]
|
|
mcp_servers: BTreeMap<String, Server>,
|
|
}
|
|
|
|
/// `${VAR}` / `${VAR:-default}` from the environment; unknown vars become "".
|
|
pub fn interpolate(s: &str, env: &dyn Fn(&str) -> Option<String>) -> String {
|
|
let mut out = String::new();
|
|
let mut rest = s;
|
|
while let Some(i) = rest.find("${") {
|
|
out.push_str(&rest[..i]);
|
|
let Some(j) = rest[i..].find('}') else {
|
|
out.push_str(&rest[i..]);
|
|
return out;
|
|
};
|
|
let expr = &rest[i + 2..i + j];
|
|
let (name, def) = expr.split_once(":-").unwrap_or((expr, ""));
|
|
out.push_str(&env(name).unwrap_or_else(|| def.to_string()));
|
|
rest = &rest[i + j + 1..];
|
|
}
|
|
out.push_str(rest);
|
|
out
|
|
}
|
|
|
|
fn expand(mut s: Server, env: &dyn Fn(&str) -> Option<String>) -> Server {
|
|
let f = |x: &str| interpolate(x, env);
|
|
s.command = s.command.as_deref().map(f);
|
|
s.url = s.url.as_deref().map(f);
|
|
s.args = s.args.iter().map(|a| f(a)).collect();
|
|
s.env = s.env.iter().map(|(k, v)| (k.clone(), f(v))).collect();
|
|
s.headers = s.headers.iter().map(|(k, v)| (k.clone(), f(v))).collect();
|
|
s
|
|
}
|
|
|
|
pub fn parse(json: &str) -> Result<BTreeMap<String, Server>, String> {
|
|
serde_json::from_str::<File>(json)
|
|
.map(|f| f.mcp_servers)
|
|
.map_err(|e| e.to_string())
|
|
}
|
|
|
|
/// Global then project; a project entry replaces the global one with the same name. 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 env = |k: &str| std::env::var(k).ok();
|
|
Ok(all
|
|
.into_iter()
|
|
.filter(|(_, s)| !s.disabled)
|
|
.map(|(k, s)| (k, expand(s, &env)))
|
|
.collect())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod t {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn parse_merge_interpolate() {
|
|
let d = tempfile::tempdir().unwrap();
|
|
let (home, cwd) = (d.path().join("h"), d.path().join("p"));
|
|
std::fs::create_dir_all(&home).unwrap();
|
|
std::fs::create_dir_all(cwd.join(".hx")).unwrap();
|
|
std::fs::write(
|
|
home.join("mcp.json"),
|
|
r#"{"mcpServers":{
|
|
"fs":{"command":"npx","args":["-y","fs","${HOME}"]},
|
|
"web":{"type":"http","url":"https://x/mcp","headers":{"Authorization":"Bearer ${HX_T_TOKEN:-none}"}},
|
|
"off":{"command":"x","disabled":true}}}"#,
|
|
)
|
|
.unwrap();
|
|
std::fs::write(
|
|
cwd.join(".hx/mcp.json"),
|
|
r#"{"mcpServers":{"fs":{"command":"fs-server","eager":true,"allow":["read"]}}}"#,
|
|
)
|
|
.unwrap();
|
|
let m = load(&home, &cwd).unwrap();
|
|
assert_eq!(m.keys().collect::<Vec<_>>(), ["fs", "web"]);
|
|
assert_eq!(m["fs"].command.as_deref(), Some("fs-server"));
|
|
assert!(m["fs"].args.is_empty() && m["fs"].eager == Some(true));
|
|
assert_eq!(m["web"].headers["Authorization"], "Bearer none");
|
|
|
|
let env = |k: &str| (k == "A").then(|| "1".to_string());
|
|
assert_eq!(interpolate("x${A}y${B:-d}z${C}", &env), "x1ydz");
|
|
assert_eq!(interpolate("open ${A", &env), "open ${A");
|
|
assert!(parse("{").is_err());
|
|
std::fs::write(cwd.join(".hx/mcp.json"), "{nope").unwrap();
|
|
assert!(load(&home, &cwd).unwrap_err().contains(".hx/mcp.json"));
|
|
}
|
|
}
|