use std::path::{Path, PathBuf};
use anyhow::Context;
use serde_json::{Value, json};
use toml_edit::{DocumentMut, Item, Table, value};
use crate::cli::init::{claude_desktop_config_path, read_config_text};
pub const SYMFORGE_SERVER_NAME: &str = "symforge";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HarnessId {
ClaudeCode,
ClaudeDesktop,
Codex,
Gemini,
KiloCode,
Cursor,
}
impl HarnessId {
pub fn slug(self) -> &'static str {
match self {
HarnessId::ClaudeCode => "claude",
HarnessId::ClaudeDesktop => "claude-desktop",
HarnessId::Codex => "codex",
HarnessId::Gemini => "gemini",
HarnessId::KiloCode => "kilo-code",
HarnessId::Cursor => "cursor",
}
}
pub fn display_name(self) -> &'static str {
match self {
HarnessId::ClaudeCode => "Claude Code",
HarnessId::ClaudeDesktop => "Claude Desktop",
HarnessId::Codex => "Codex",
HarnessId::Gemini => "Gemini CLI",
HarnessId::KiloCode => "Kilo Code",
HarnessId::Cursor => "Cursor",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HarnessFormat {
Json,
Toml,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AttachEntry {
pub url: String,
pub bearer_key: Option<String>,
}
impl AttachEntry {
pub fn new(url: impl Into<String>, bearer_key: Option<String>) -> Self {
let bearer_key = bearer_key.filter(|k| !k.is_empty());
Self {
url: url.into(),
bearer_key,
}
}
}
#[derive(Debug, Clone)]
pub struct HarnessTarget {
pub id: HarnessId,
pub config_path: PathBuf,
pub format: HarnessFormat,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HarnessState {
NotInstalled,
Absent,
PresentCurrent,
PresentStale(StaleFields),
Malformed(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StaleFields {
Url,
BearerKey,
Both,
}
impl StaleFields {
fn between(found: &AttachEntry, desired: &AttachEntry) -> Option<Self> {
match (
found.url != desired.url,
found.bearer_key != desired.bearer_key,
) {
(false, false) => None,
(true, false) => Some(Self::Url),
(false, true) => Some(Self::BearerKey),
(true, true) => Some(Self::Both),
}
}
pub fn description(self) -> &'static str {
match self {
Self::Url => "url differs from the target",
Self::BearerKey => "bearer key differs from the target",
Self::Both => "url and bearer key differ from the target",
}
}
}
#[derive(Debug, Clone)]
pub struct HarnessStatus {
pub id: HarnessId,
pub config_path: PathBuf,
pub format: HarnessFormat,
pub state: HarnessState,
}
#[derive(Debug, Clone)]
pub struct HarnessRegistry {
targets: Vec<HarnessTarget>,
}
impl HarnessRegistry {
pub fn known() -> anyhow::Result<Self> {
let home = dirs::home_dir().context("cannot determine home directory")?;
let working_dir =
std::env::current_dir().context("cannot determine current working directory")?;
Ok(Self::known_with(&home, &working_dir))
}
pub fn known_with(home: &Path, working_dir: &Path) -> Self {
let desktop = claude_desktop_config_path(home, None);
let targets = vec![
HarnessTarget {
id: HarnessId::ClaudeCode,
config_path: home.join(".claude.json"),
format: HarnessFormat::Json,
},
HarnessTarget {
id: HarnessId::ClaudeDesktop,
config_path: desktop,
format: HarnessFormat::Json,
},
HarnessTarget {
id: HarnessId::Codex,
config_path: home.join(".codex").join("config.toml"),
format: HarnessFormat::Toml,
},
HarnessTarget {
id: HarnessId::Gemini,
config_path: home.join(".gemini").join("settings.json"),
format: HarnessFormat::Json,
},
HarnessTarget {
id: HarnessId::KiloCode,
config_path: working_dir.join(".kilocode").join("mcp.json"),
format: HarnessFormat::Json,
},
HarnessTarget {
id: HarnessId::Cursor,
config_path: home.join(".cursor").join("mcp.json"),
format: HarnessFormat::Json,
},
];
Self { targets }
}
pub fn from_targets(targets: Vec<HarnessTarget>) -> Self {
Self { targets }
}
pub fn targets(&self) -> &[HarnessTarget] {
&self.targets
}
pub fn scan(&self, desired: &AttachEntry) -> Vec<HarnessStatus> {
self.targets
.iter()
.map(|t| HarnessStatus {
id: t.id,
config_path: t.config_path.clone(),
format: t.format,
state: scan_target(t, desired),
})
.collect()
}
}
pub(crate) fn config_installed(config_path: &Path) -> bool {
config_path.exists() || config_path.parent().is_some_and(Path::exists)
}
pub(crate) fn harness_installed(id: HarnessId, config_path: &Path) -> bool {
match id {
HarnessId::ClaudeCode => {
config_path.exists() || config_path.with_file_name(".claude").exists()
}
_ => config_installed(config_path),
}
}
fn scan_target(target: &HarnessTarget, desired: &AttachEntry) -> HarnessState {
if !target.config_path.exists() {
return if harness_installed(target.id, &target.config_path) {
HarnessState::Absent
} else {
HarnessState::NotInstalled
};
}
let text = match read_config_text(&target.config_path) {
Ok(text) => text,
Err(e) => return HarnessState::Malformed(e.to_string()),
};
let existing = match target.format {
HarnessFormat::Json => read_json_entry(&text),
HarnessFormat::Toml => read_toml_entry(&text),
};
match existing {
Err(e) => HarnessState::Malformed(e),
Ok(None) => HarnessState::Absent,
Ok(Some(found)) => match StaleFields::between(&found, desired) {
None => HarnessState::PresentCurrent,
Some(fields) => HarnessState::PresentStale(fields),
},
}
}
fn read_json_entry(text: &str) -> Result<Option<AttachEntry>, String> {
let trimmed = text.trim();
let config: Value = if trimmed.is_empty() {
json!({})
} else {
serde_json::from_str(text).map_err(|e| e.to_string())?
};
let entry = config
.get("mcpServers")
.and_then(|m| m.get(SYMFORGE_SERVER_NAME));
let Some(entry) = entry else {
return Ok(None);
};
let url = entry
.get("url")
.and_then(Value::as_str)
.unwrap_or_default()
.to_string();
let bearer_key = entry
.get("headers")
.and_then(|h| h.get("Authorization"))
.and_then(Value::as_str)
.and_then(strip_bearer)
.map(str::to_string);
Ok(Some(AttachEntry { url, bearer_key }))
}
fn read_toml_entry(text: &str) -> Result<Option<AttachEntry>, String> {
let trimmed = text.trim();
if trimmed.is_empty() {
return Ok(None);
}
let doc = text.parse::<DocumentMut>().map_err(|e| e.to_string())?;
let entry = doc
.get("mcp_servers")
.and_then(Item::as_table)
.and_then(|t| t.get(SYMFORGE_SERVER_NAME))
.and_then(Item::as_table);
let Some(entry) = entry else {
return Ok(None);
};
let url = entry
.get("url")
.and_then(Item::as_str)
.unwrap_or_default()
.to_string();
let bearer_key = entry
.get("bearer_token")
.and_then(Item::as_str)
.filter(|s| !s.is_empty())
.map(str::to_string);
Ok(Some(AttachEntry { url, bearer_key }))
}
pub fn registered_command(status: &HarnessStatus) -> Option<String> {
let text = read_config_text(&status.config_path).ok()?;
match status.format {
HarnessFormat::Json => serde_json::from_str::<Value>(&text)
.ok()?
.get("mcpServers")?
.get(SYMFORGE_SERVER_NAME)?
.get("command")?
.as_str()
.map(str::to_string),
HarnessFormat::Toml => text
.parse::<DocumentMut>()
.ok()?
.get("mcp_servers")?
.as_table()?
.get(SYMFORGE_SERVER_NAME)?
.as_table()?
.get("command")?
.as_str()
.map(str::to_string),
}
}
pub fn registered_stdio_args(status: &HarnessStatus) -> Option<Vec<String>> {
let text = read_config_text(&status.config_path).ok()?;
match status.format {
HarnessFormat::Json => {
let value: Value = serde_json::from_str(&text).ok()?;
let entry = value.get("mcpServers")?.get(SYMFORGE_SERVER_NAME)?;
match entry.get("args") {
None | Some(Value::Null) => Some(Vec::new()),
Some(Value::Array(values)) => {
let mut args = Vec::with_capacity(values.len());
for value in values {
args.push(value.as_str()?.to_string());
}
Some(args)
}
Some(_) => None,
}
}
HarnessFormat::Toml => {
let doc = text.parse::<DocumentMut>().ok()?;
let entry = doc
.get("mcp_servers")?
.as_table()?
.get(SYMFORGE_SERVER_NAME)?
.as_table()?;
match entry.get("args") {
None => Some(Vec::new()),
Some(item) => {
let array = item.as_array()?;
let mut args = Vec::with_capacity(array.len());
for value in array.iter() {
args.push(value.as_str()?.to_string());
}
Some(args)
}
}
}
}
}
fn strip_bearer(header: &str) -> Option<&str> {
header
.strip_prefix("Bearer ")
.map(str::trim)
.filter(|s| !s.is_empty())
}
pub fn apply_attach_entry(
format: HarnessFormat,
existing_text: Option<&str>,
entry: &AttachEntry,
) -> anyhow::Result<String> {
match format {
HarnessFormat::Json => apply_json(existing_text, entry),
HarnessFormat::Toml => apply_toml(existing_text, entry),
}
}
fn apply_json(existing_text: Option<&str>, entry: &AttachEntry) -> anyhow::Result<String> {
let mut config: Value = match existing_text {
Some(text) if !text.trim().is_empty() => {
serde_json::from_str(text).context("parsing client JSON config")?
}
_ => json!({}),
};
if !config["mcpServers"].is_object() {
config["mcpServers"] = json!({});
}
let mut server = json!({
"type": "http",
"url": entry.url,
});
if let Some(key) = &entry.bearer_key {
server["headers"] = json!({ "Authorization": format!("Bearer {key}") });
}
config["mcpServers"][SYMFORGE_SERVER_NAME] = server;
let mut pretty = serde_json::to_string_pretty(&config)?;
pretty.push('\n');
Ok(pretty)
}
fn apply_toml(existing_text: Option<&str>, entry: &AttachEntry) -> anyhow::Result<String> {
let mut doc: DocumentMut = match existing_text {
Some(text) if !text.trim().is_empty() => text
.parse::<DocumentMut>()
.context("parsing Codex TOML config")?,
_ => DocumentMut::new(),
};
if !doc.as_table().contains_key("mcp_servers") || !doc["mcp_servers"].is_table() {
doc["mcp_servers"] = Item::Table(Table::new());
}
let mcp_servers = doc["mcp_servers"]
.as_table_mut()
.expect("mcp_servers is a table");
let mut server = Table::new();
server["url"] = value(entry.url.clone());
if let Some(key) = &entry.bearer_key {
server["bearer_token"] = value(key.clone());
}
mcp_servers.insert(SYMFORGE_SERVER_NAME, Item::Table(server));
Ok(doc.to_string())
}
#[cfg(feature = "server")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AapPresetChoice {
EmbedOnly,
Http,
}
#[cfg(feature = "server")]
impl AapPresetChoice {
pub fn label(self) -> &'static str {
match self {
AapPresetChoice::EmbedOnly => "embed_only",
AapPresetChoice::Http => "http",
}
}
}
#[cfg(feature = "server")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AapHarnessTarget {
pub detected: bool,
pub root: Option<PathBuf>,
pub source: Option<&'static str>,
pub embed_path_dep: String,
pub presets: Vec<AapPresetChoice>,
}
#[cfg(feature = "server")]
impl AapHarnessTarget {
pub fn offers_http(&self) -> bool {
self.presets.contains(&AapPresetChoice::Http)
}
pub fn embed_dep_is_path_not_stdio(&self) -> bool {
let dep = &self.embed_path_dep;
dep.contains("path =")
&& dep.contains("features = [\"embed\"]")
&& !dep.contains("command")
&& !dep.contains("stdio")
&& !dep.contains("args")
}
}
#[cfg(feature = "server")]
pub fn aap_target(serve_attach: Option<&str>) -> AapHarnessTarget {
aap_target_from(&crate::server::aap::AapDetection::resolve(), serve_attach)
}
#[cfg(feature = "server")]
pub fn aap_target_from(
detection: &crate::server::aap::AapDetection,
serve_attach: Option<&str>,
) -> AapHarnessTarget {
let mut presets = Vec::new();
if detection.detected {
presets.push(AapPresetChoice::EmbedOnly);
if serve_attach.is_some_and(|u| !u.is_empty()) {
presets.push(AapPresetChoice::Http);
}
}
AapHarnessTarget {
detected: detection.detected,
root: detection.root.clone(),
source: detection.source.map(|s| s.label()),
embed_path_dep: crate::server::aap::embed_cargo_snippet(),
presets,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn entry() -> AttachEntry {
AttachEntry::new("http://127.0.0.1:8787/mcp", Some("sf_key_123".to_string()))
}
const LEAK_SENTINEL: &str = "sentinel-must-never-be-rendered";
fn json_config(dir: &std::path::Path, name: &str, url: &str, key: &str) -> HarnessTarget {
let path = dir.join(name);
std::fs::write(
&path,
serde_json::to_string(&json!({
"mcpServers": {
SYMFORGE_SERVER_NAME: {
"type": "http",
"url": url,
"headers": { "Authorization": format!("Bearer {key}") },
}
}
}))
.unwrap(),
)
.unwrap();
HarnessTarget {
id: HarnessId::ClaudeCode,
config_path: path,
format: HarnessFormat::Json,
}
}
#[test]
fn a_stale_entry_reports_which_field_differs() {
let dir = tempfile::tempdir().unwrap();
let desired = entry();
let key_only = json_config(dir.path(), "key.json", &desired.url, "a-different-key");
let url_only = json_config(
dir.path(),
"url.json",
"http://127.0.0.1:9999/mcp",
desired.bearer_key.as_deref().unwrap(),
);
let key_state = scan_target(&key_only, &desired);
let url_state = scan_target(&url_only, &desired);
assert_ne!(key_state, HarnessState::PresentCurrent);
assert_ne!(url_state, HarnessState::PresentCurrent);
assert_ne!(
key_state, url_state,
"a key-only difference and a url-only difference must not report \
identically: the comparison holds both entries and must keep what \
it learned"
);
}
#[test]
fn a_stale_state_never_renders_the_bearer_key() {
let dir = tempfile::tempdir().unwrap();
let desired = entry();
let stale = json_config(dir.path(), "leak.json", &desired.url, LEAK_SENTINEL);
let state = scan_target(&stale, &desired);
assert_ne!(state, HarnessState::PresentCurrent);
let rendered = format!("{state:?}");
assert!(
!rendered.contains(LEAK_SENTINEL),
"a stale state must name WHICH field differs, never the value: \
bearer_key is a Bearer token and this state is rendered into the \
admin API's public `detail` field. Got: {rendered}"
);
}
#[test]
fn json_absent_adds_entry() {
let out = apply_json(Some("{}"), &entry()).unwrap();
let v: Value = serde_json::from_str(&out).unwrap();
assert_eq!(
v["mcpServers"]["symforge"]["url"],
"http://127.0.0.1:8787/mcp"
);
assert_eq!(
v["mcpServers"]["symforge"]["headers"]["Authorization"],
"Bearer sf_key_123"
);
assert_eq!(v["mcpServers"]["symforge"]["type"], "http");
}
#[test]
fn json_preserves_siblings() {
let input = r#"{"mcpServers":{"other":{"command":"x"}},"numStartups":3}"#;
let out = apply_json(Some(input), &entry()).unwrap();
let v: Value = serde_json::from_str(&out).unwrap();
assert_eq!(v["mcpServers"]["other"]["command"], "x");
assert_eq!(v["numStartups"], 3);
assert!(v["mcpServers"]["symforge"].is_object());
}
#[test]
fn json_stale_refreshes_no_dup() {
let input = r#"{"mcpServers":{"symforge":{"type":"http","url":"http://old/mcp","headers":{"Authorization":"Bearer old"}}}}"#;
let out = apply_json(Some(input), &entry()).unwrap();
let v: Value = serde_json::from_str(&out).unwrap();
assert_eq!(
v["mcpServers"]["symforge"]["url"],
"http://127.0.0.1:8787/mcp"
);
let servers = v["mcpServers"].as_object().unwrap();
assert_eq!(servers.keys().filter(|k| *k == "symforge").count(), 1);
}
#[test]
fn json_keyless_omits_headers() {
let e = AttachEntry::new("http://127.0.0.1:8787/mcp", None);
let out = apply_json(Some("{}"), &e).unwrap();
let v: Value = serde_json::from_str(&out).unwrap();
assert!(v["mcpServers"]["symforge"]["headers"].is_null());
}
#[test]
fn json_apply_is_idempotent() {
let once = apply_json(Some("{}"), &entry()).unwrap();
let twice = apply_json(Some(&once), &entry()).unwrap();
assert_eq!(once, twice);
}
#[test]
fn toml_absent_adds_entry() {
let out = apply_toml(Some("model = \"gpt-5\"\n"), &entry()).unwrap();
let doc = out.parse::<DocumentMut>().unwrap();
assert_eq!(
doc["mcp_servers"]["symforge"]["url"].as_str().unwrap(),
"http://127.0.0.1:8787/mcp"
);
assert_eq!(
doc["mcp_servers"]["symforge"]["bearer_token"]
.as_str()
.unwrap(),
"sf_key_123"
);
assert_eq!(doc["model"].as_str().unwrap(), "gpt-5");
}
#[test]
fn toml_preserves_other_servers() {
let input = "[mcp_servers.other]\ncommand = \"x\"\n";
let out = apply_toml(Some(input), &entry()).unwrap();
let doc = out.parse::<DocumentMut>().unwrap();
assert_eq!(
doc["mcp_servers"]["other"]["command"].as_str().unwrap(),
"x"
);
assert!(doc["mcp_servers"]["symforge"].is_table());
}
#[test]
fn toml_apply_is_idempotent() {
let once = apply_toml(None, &entry()).unwrap();
let twice = apply_toml(Some(&once), &entry()).unwrap();
assert_eq!(once, twice);
}
#[test]
fn read_json_entry_roundtrip() {
let out = apply_json(Some("{}"), &entry()).unwrap();
let read = read_json_entry(&out).unwrap().unwrap();
assert_eq!(read, entry());
}
#[test]
fn read_toml_entry_roundtrip() {
let out = apply_toml(None, &entry()).unwrap();
let read = read_toml_entry(&out).unwrap().unwrap();
assert_eq!(read, entry());
}
#[test]
fn read_json_entry_absent_is_none() {
assert!(read_json_entry("{}").unwrap().is_none());
assert!(read_json_entry("").unwrap().is_none());
}
#[test]
fn read_json_entry_malformed_errors() {
assert!(read_json_entry("{ not json").is_err());
}
}