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,
Malformed(String),
}
#[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()
}
}
fn scan_target(target: &HarnessTarget, desired: &AttachEntry) -> HarnessState {
if !target.config_path.exists() {
return match target.config_path.parent() {
Some(parent) if parent.exists() => HarnessState::Absent,
_ => 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)) => {
if found == *desired {
HarnessState::PresentCurrent
} else {
HarnessState::PresentStale
}
}
}
}
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 }))
}
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()))
}
#[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());
}
}