pub mod edit;
pub mod hooks;
use std::collections::BTreeMap;
use std::path::PathBuf;
use serde::Deserialize;
use crate::launch::Launch;
const REGISTRY: &str = include_str!("clients.toml");
pub const SERVER_NAME: &str = "memfork";
pub const SERVER_ARGS: &[&str] = &["mcp"];
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Scope {
User,
Project,
}
impl Scope {
pub fn parse(s: &str) -> Option<Self> {
match s.to_ascii_lowercase().as_str() {
"user" => Some(Scope::User),
"project" => Some(Scope::Project),
_ => None,
}
}
pub fn as_str(self) -> &'static str {
match self {
Scope::User => "user",
Scope::Project => "project",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Os {
Linux,
MacOs,
Windows,
}
impl Os {
pub fn current() -> Self {
if cfg!(target_os = "windows") {
Os::Windows
} else if cfg!(target_os = "macos") {
Os::MacOs
} else {
Os::Linux
}
}
pub fn separator(self) -> char {
match self {
Os::Windows => '\\',
_ => '/',
}
}
fn suffix(self) -> &'static str {
match self {
Os::Linux => "linux",
Os::MacOs => "macos",
Os::Windows => "windows",
}
}
pub fn all() -> [Os; 3] {
[Os::Linux, Os::MacOs, Os::Windows]
}
}
#[derive(Debug, Deserialize)]
struct Registry {
client: Vec<Client>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct Client {
pub id: String,
pub display: String,
pub docs: String,
pub verified: String,
pub cli: Option<ClientCli>,
pub file: Option<ClientFile>,
#[serde(default, alias = "detect_dir")]
pub detect_dirs: OneOrMany,
#[serde(default)]
pub mcp_names: Vec<String>,
#[serde(default)]
pub instructions: Option<ClientInstructions>,
#[serde(default)]
pub hooks: Option<ClientHooks>,
#[serde(default)]
pub unverified: Option<String>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
#[serde(untagged)]
pub enum OneOrMany {
#[default]
None,
One(String),
Many(Vec<String>),
}
impl OneOrMany {
pub fn as_slice(&self) -> &[String] {
match self {
OneOrMany::None => &[],
OneOrMany::One(one) => std::slice::from_ref(one),
OneOrMany::Many(many) => many,
}
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct ClientInstructions {
pub reads: Vec<String>,
pub docs: String,
pub verified: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct ClientHooks {
pub format: hooks::Shape,
pub project_local: String,
pub docs: String,
pub verified: String,
}
#[derive(Debug, Clone, Deserialize)]
pub struct ClientCli {
pub binary: String,
pub add: Vec<String>,
#[serde(default)]
pub status: Option<Vec<String>>,
#[serde(default)]
pub remove: Option<Vec<String>>,
#[serde(default)]
pub scope_user: Option<Vec<String>>,
#[serde(default)]
pub scope_project: Option<Vec<String>>,
}
impl ClientCli {
pub fn scope_flags(&self, scope: Scope) -> Option<&[String]> {
match scope {
Scope::User => self.scope_user.as_deref(),
Scope::Project => self.scope_project.as_deref(),
}
}
pub fn status_args(&self) -> Option<Vec<String>> {
self.status
.as_ref()
.map(|status| self.expand(status, &[], &Launch::program("")))
}
pub fn add_args(&self, scope: Scope, launch: &Launch) -> Option<Vec<String>> {
let scope_flags = self.scope_flags(scope)?;
Some(self.expand(&self.add, scope_flags, launch))
}
pub fn remove_args(&self, scope: Scope) -> Option<Vec<String>> {
let template = self.remove.as_ref()?;
let scope_flags = self.scope_flags(scope).unwrap_or(&[]);
Some(self.expand(template, scope_flags, &Launch::program("")))
}
fn expand(&self, template: &[String], scope_flags: &[String], launch: &Launch) -> Vec<String> {
let mut out = Vec::new();
for token in template {
match token.as_str() {
"{scope}" => out.extend(scope_flags.iter().cloned()),
"{name}" => out.push(SERVER_NAME.to_owned()),
"{command}" => out.push(launch.program.display().to_string()),
"{args}" => {
out.extend(launch.args.iter().cloned());
out.extend(SERVER_ARGS.iter().map(|a| (*a).to_owned()));
}
literal => out.push(literal.to_owned()),
}
}
out
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct ClientFile {
pub format: Format,
pub server_map: Vec<String>,
#[serde(default)]
pub stdio_type: Option<String>,
#[serde(default)]
pub command_style: CommandStyle,
#[serde(default)]
pub extra: Option<toml::Table>,
pub http_url_key: String,
#[serde(default)]
pub user: Option<String>,
#[serde(default)]
pub project: Option<String>,
#[serde(flatten)]
overrides: BTreeMap<String, toml::Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Format {
Json,
Jsonc,
Toml,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CommandStyle {
#[default]
Split,
Array,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Vars {
pub home: String,
pub appdata: String,
pub localappdata: String,
pub xdg_config_home: String,
pub xdg_data_home: String,
}
impl Vars {
pub fn for_home(home: &str, os: Os) -> Self {
let home = home.trim_end_matches(['/', '\\']).to_owned();
let join = |parts: &[&str]| {
let mut s = home.clone();
for p in parts {
s.push(os.separator());
s.push_str(p);
}
s
};
Vars {
appdata: join(&["AppData", "Roaming"]),
localappdata: join(&["AppData", "Local"]),
xdg_config_home: join(&[".config"]),
xdg_data_home: join(&[".local", "share"]),
home,
}
}
pub fn here(home: &str) -> Self {
let os = Os::current();
let mut vars = Vars::for_home(home, os);
if std::env::var_os("MEMFORK_HOME").is_some() {
return vars;
}
let real = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
if let Some(v) = real("APPDATA") {
vars.appdata = v;
}
if let Some(v) = real("LOCALAPPDATA") {
vars.localappdata = v;
}
if let Some(v) = real("XDG_CONFIG_HOME") {
vars.xdg_config_home = v;
}
if let Some(v) = real("XDG_DATA_HOME") {
vars.xdg_data_home = v;
}
vars
}
pub fn expand(&self, template: &str, os: Os) -> String {
let expanded = template
.replace("$XDG_CONFIG_HOME", &self.xdg_config_home)
.replace("$XDG_DATA_HOME", &self.xdg_data_home)
.replace("$LOCALAPPDATA", &self.localappdata)
.replace("$APPDATA", &self.appdata)
.replace("$HOME", &self.home);
let sep = os.separator();
expanded
.split(['/', '\\'])
.collect::<Vec<_>>()
.join(&sep.to_string())
}
}
impl ClientFile {
fn template(&self, scope: Scope, os: Os) -> Option<&str> {
let key = format!("{}_{}", scope.as_str(), os.suffix());
if let Some(over) = self.overrides.get(&key).and_then(toml::Value::as_str) {
return Some(over);
}
match scope {
Scope::User => self.user.as_deref(),
Scope::Project => self.project.as_deref(),
}
}
pub fn path_for(&self, scope: Scope, os: Os, vars: &Vars) -> Option<String> {
let template = self.template(scope, os)?;
Some(vars.expand(template, os))
}
pub fn path_here(&self, scope: Scope, home: &str) -> Option<PathBuf> {
self.path_for(scope, Os::current(), &Vars::here(home))
.map(PathBuf::from)
}
}
impl Client {
pub fn detect_dirs_here(&self, home: &str) -> Vec<PathBuf> {
let vars = Vars::here(home);
self.detect_dirs
.as_slice()
.iter()
.map(|t| PathBuf::from(vars.expand(t, Os::current())))
.collect()
}
pub fn file_writable(&self, scope: Scope) -> bool {
match (&self.file, scope) {
(None, _) => false,
(Some(f), Scope::User) => f.user.is_some(),
(Some(f), Scope::Project) => f.project.is_some(),
}
}
pub fn status_command(&self) -> Option<(String, PathBuf, Vec<String>)> {
let cli = self.cli.as_ref()?;
let args = cli.status_args()?;
let resolved = crate::init::which(&cli.binary)?;
Some((cli.binary.clone(), resolved, args))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Registration {
Yes,
Stale {
found: Option<String>,
},
No,
Unknown(String),
}
impl Registration {
pub fn as_bool(&self) -> Option<bool> {
match self {
Registration::Yes => Some(true),
Registration::Stale { .. } | Registration::No => Some(false),
Registration::Unknown(_) => None,
}
}
pub fn points_at(&self) -> Option<&str> {
match self {
Registration::Stale { found } => found.as_deref(),
_ => None,
}
}
}
#[derive(Debug, Clone)]
pub enum Checked {
Command(String),
File(PathBuf),
Nothing,
}
pub fn registration(
client: &Client,
scope: Scope,
home: &str,
launch: &Launch,
) -> (Registration, Checked) {
if let Some((binary, resolved, args)) = client.status_command() {
let printed = format!("{binary} {}", args.join(" "));
let spinner = crate::style::Spinner::quiet(&format!(
"asking {} whether MemFork is registered",
client.display
));
let output = std::process::Command::new(&resolved).args(&args).output();
drop(spinner);
return match output {
Ok(output) => {
let text = format!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
let registered = output.status.success() && text.contains(SERVER_NAME);
let answer = match registered {
false => Registration::No,
true if launch.is_named_in(&text) => Registration::Yes,
true => Registration::Stale {
found: memfork_path_in(&text),
},
};
(answer, Checked::Command(printed))
}
Err(e) => (
Registration::Unknown(format!("`{printed}` could not be run: {e}")),
Checked::Command(printed),
),
};
}
let Some(file) = client.file.as_ref() else {
return (
Registration::Unknown("this client has no command and no config file".to_owned()),
Checked::Nothing,
);
};
let Some(path) = file.path_here(scope, home) else {
return (
Registration::Unknown(
"MemFork does not read this client's user configuration; install its \
command to have it answer for itself"
.to_owned(),
),
Checked::Nothing,
);
};
if !path.exists() {
return (Registration::No, Checked::File(path));
}
match edit::plan(file, &path, launch) {
Ok(e) if e.change == edit::Change::Unchanged => (Registration::Yes, Checked::File(path)),
Ok(e) if e.change == edit::Change::Update => (
Registration::Stale {
found: edit::registered_command(file, &path),
},
Checked::File(path),
),
Ok(_) => (Registration::No, Checked::File(path)),
Err(reason) => (Registration::Unknown(reason), Checked::File(path)),
}
}
fn memfork_path_in(text: &str) -> Option<String> {
let trim: &[char] = &['"', ',', '\''];
text.split_whitespace()
.map(|token| token.trim_matches(trim))
.find(|token| {
token.to_ascii_lowercase().contains(SERVER_NAME)
&& token.chars().any(|c| c == '/' || c == '\\')
})
.map(str::to_owned)
}
pub fn all() -> Vec<Client> {
cached().to_vec()
}
fn cached() -> &'static [Client] {
static PARSED: std::sync::OnceLock<Vec<Client>> = std::sync::OnceLock::new();
PARSED.get_or_init(|| load().unwrap_or_default())
}
pub fn load() -> Result<Vec<Client>, String> {
toml::from_str::<Registry>(REGISTRY)
.map(|r| r.client)
.map_err(|e| format!("the compiled-in client registry is malformed: {e}"))
}
pub fn display_for_writer(name: &str) -> String {
cached()
.iter()
.find(|c| {
c.mcp_names
.iter()
.any(|pattern| match pattern.strip_suffix('*') {
Some(prefix) => name.starts_with(prefix),
None => name == pattern,
})
})
.map(|c| c.display.clone())
.unwrap_or_else(|| name.to_owned())
}
pub fn instruction_files(clients: &[Client]) -> Vec<(String, Vec<String>)> {
let mut remaining: Vec<&Client> = clients
.iter()
.filter(|c| c.instructions.as_ref().is_some_and(|i| !i.reads.is_empty()))
.collect();
let order = ids();
remaining.sort_by_key(|c| {
order
.iter()
.position(|id| *id == c.id)
.unwrap_or(usize::MAX)
});
let mut chosen: Vec<(String, Vec<String>)> = Vec::new();
while !remaining.is_empty() {
let mut candidates: Vec<&String> = Vec::new();
for c in &remaining {
for f in c.instructions.iter().flat_map(|i| &i.reads) {
if !candidates.contains(&f) {
candidates.push(f);
}
}
}
let reach = |f: &String| {
remaining
.iter()
.filter(|c| c.instructions.iter().any(|i| i.reads.contains(f)))
.count()
};
let Some(best) = candidates
.iter()
.copied()
.enumerate()
.max_by(|(ia, a), (ib, b)| reach(a).cmp(&reach(b)).then(ib.cmp(ia)))
.map(|(_, f)| f.clone())
else {
break;
};
let served: Vec<String> = remaining
.iter()
.filter(|c| c.instructions.iter().any(|i| i.reads.contains(&best)))
.map(|c| c.id.clone())
.collect();
remaining.retain(|c| !served.contains(&c.id));
chosen.push((best, served));
}
chosen
}
pub fn find(id: &str) -> Option<Client> {
all().into_iter().find(|c| c.id == id)
}
pub fn ids() -> Vec<String> {
all().into_iter().map(|c| c.id).collect()
}
pub fn home_dir() -> Option<String> {
if let Some(over) = std::env::var_os("MEMFORK_HOME") {
return Some(over.to_string_lossy().into_owned());
}
#[allow(
deprecated,
reason = "un-deprecated in Rust 1.86 with correct Windows behaviour"
)]
std::env::home_dir().map(|p| p.to_string_lossy().into_owned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn writers_are_shown_by_the_name_a_person_knows() {
assert_eq!(display_for_writer("claude-code"), "Claude Code");
assert_eq!(display_for_writer("codex-mcp-client"), "Codex CLI");
assert_eq!(display_for_writer("gemini-cli-mcp-client"), "Gemini CLI");
assert_eq!(display_for_writer("grok-shell-memfork"), "Grok Build");
assert_eq!(display_for_writer("some-new-client"), "some-new-client");
}
#[test]
fn every_client_says_where_it_reads_instructions() {
for c in all() {
let i = c
.instructions
.as_ref()
.unwrap_or_else(|| panic!("{} has no instructions entry", c.id));
assert!(!i.reads.is_empty(), "{}", c.id);
assert!(i.docs.starts_with("https://"), "{}", c.id);
assert!(i.verified.len() == 10, "{}", c.id);
for f in &i.reads {
assert!(
!f.starts_with('/') && !f.contains('\\') && !f.contains(".."),
"{}: `{f}` must be a plain path inside the repository",
c.id
);
}
}
}
#[test]
fn clients_that_share_a_file_get_it_once() {
let pick = |ids: &[&str]| {
let clients: Vec<Client> = ids.iter().map(|id| find(id).unwrap()).collect();
instruction_files(&clients)
};
let agents = crate::init::project::AGENTS_FILE;
let shared = pick(&["codex", "cursor", "grok"]);
assert_eq!(shared.len(), 1, "{shared:?}");
assert_eq!(shared[0].0, agents);
assert_eq!(shared[0].1, ["cursor", "codex", "grok"]);
let all_ids = ids();
let every = pick(&all_ids.iter().map(String::as_str).collect::<Vec<_>>());
let files: Vec<&str> = every.iter().map(|(f, _)| f.as_str()).collect();
let mut unique = files.clone();
unique.dedup();
assert_eq!(files, unique);
for id in &all_ids {
assert!(
every
.iter()
.any(|(_, served)| served.iter().any(|s| s == id)),
"{id} is not reached by {every:?}"
);
}
assert_eq!(files.len(), 3, "{every:?}");
let mut backwards = all_ids.clone();
backwards.reverse();
let reversed = pick(&backwards.iter().map(String::as_str).collect::<Vec<_>>());
let names =
|v: &[(String, Vec<String>)]| v.iter().map(|(f, _)| f.clone()).collect::<Vec<_>>();
assert_eq!(names(&every), names(&reversed));
}
#[test]
fn the_registry_parses_and_is_complete() {
let clients = load().expect("the compiled-in registry parses");
assert_eq!(
ids(),
vec![
"claude-code",
"cursor",
"codex",
"gemini-cli",
"grok",
"cline",
"opencode",
"qwen-code",
"kiro",
"copilot-cli",
"devin",
"windsurf",
"zed",
"vscode",
"factory-droid",
"openhands",
],
"the registry is the list of supported clients"
);
for c in &clients {
assert!(!c.display.is_empty(), "{} has no display name", c.id);
assert!(c.docs.starts_with("https://"), "{} has no docs link", c.id);
assert!(
c.verified.len() == 10 && c.verified.starts_with("20"),
"{} has no verification date",
c.id
);
assert!(
c.cli.is_some() || c.file.is_some(),
"{} has no way to register at all",
c.id
);
assert!(
!c.detect_dirs.as_slice().is_empty(),
"{} has no way to be detected",
c.id
);
if let Some(why) = &c.unverified {
assert!(why.len() > 20 && !why.ends_with('.'), "{}: {why}", c.id);
}
for name in &c.mcp_names {
assert!(!name.is_empty(), "{}", c.id);
}
}
}
#[test]
fn what_could_not_be_verified_is_said_not_assumed() {
for id in ["cursor", "kiro", "devin", "windsurf", "vscode", "openhands"] {
let c = find(id).expect(id);
assert!(c.mcp_names.is_empty(), "{id} guesses a client name");
let why = c.unverified.as_deref().unwrap_or_default();
assert!(why.contains("MCP initialize"), "{id}: {why}");
}
let copilot = find("copilot-cli").expect("copilot");
assert_eq!(copilot.mcp_names, ["copilot-cli"]);
assert!(copilot
.unverified
.as_deref()
.is_some_and(|w| w.contains("issue tracker")));
}
fn vars(os: Os) -> Vars {
Vars::for_home(
match os {
Os::Linux => "/home/ada",
Os::MacOs => "/Users/ada",
Os::Windows => "C:\\Users\\ada",
},
os,
)
}
fn user_path(id: &str, os: Os) -> String {
find(id)
.and_then(|c| c.file)
.unwrap_or_else(|| panic!("{id} registers by file"))
.path_for(Scope::User, os, &vars(os))
.unwrap_or_else(|| panic!("{id} has no user path on {os:?}"))
}
fn project_path(id: &str, os: Os) -> Option<String> {
find(id)
.and_then(|c| c.file)
.unwrap_or_else(|| panic!("{id} registers by file"))
.path_for(Scope::Project, os, &vars(os))
}
#[test]
fn paths_resolve_for_every_os() {
assert_eq!(user_path("cursor", Os::Linux), "/home/ada/.cursor/mcp.json");
assert_eq!(
user_path("cursor", Os::MacOs),
"/Users/ada/.cursor/mcp.json"
);
assert_eq!(
user_path("cursor", Os::Windows),
"C:\\Users\\ada\\.cursor\\mcp.json"
);
assert_eq!(
project_path("cursor", Os::Windows),
Some(".cursor\\mcp.json".to_owned())
);
}
#[test]
fn a_trailing_separator_on_home_does_not_double_up() {
let cursor = find("cursor").and_then(|c| c.file).expect("cursor");
assert_eq!(
cursor.path_for(
Scope::User,
Os::Linux,
&Vars::for_home("/home/ada/", Os::Linux)
),
Some("/home/ada/.cursor/mcp.json".to_owned())
);
}
#[test]
fn the_new_clients_paths_follow_each_os_convention() {
assert_eq!(
user_path("vscode", Os::Windows),
"C:\\Users\\ada\\AppData\\Roaming\\Code\\User\\mcp.json"
);
assert_eq!(
user_path("vscode", Os::MacOs),
"/Users/ada/Library/Application Support/Code/User/mcp.json"
);
assert_eq!(
user_path("vscode", Os::Linux),
"/home/ada/.config/Code/User/mcp.json"
);
assert_eq!(
user_path("cline", Os::Windows),
"C:\\Users\\ada\\AppData\\Roaming\\Code\\User\\globalStorage\\saoudrizwan.claude-dev\\settings\\cline_mcp_settings.json"
);
assert_eq!(
user_path("cline", Os::MacOs),
"/Users/ada/Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json"
);
assert_eq!(
user_path("zed", Os::Linux),
"/home/ada/.config/zed/settings.json"
);
assert_eq!(
user_path("zed", Os::MacOs),
"/Users/ada/.config/zed/settings.json"
);
assert_eq!(
user_path("zed", Os::Windows),
"C:\\Users\\ada\\AppData\\Roaming\\Zed\\settings.json"
);
assert_eq!(
user_path("opencode", Os::Windows),
"C:\\Users\\ada\\.config\\opencode\\opencode.json"
);
assert_eq!(
user_path("devin", Os::Linux),
"/home/ada/.config/devin/mcp_config.json"
);
assert_eq!(
user_path("devin", Os::Windows),
"C:\\Users\\ada\\AppData\\Roaming\\devin\\mcp_config.json"
);
assert_eq!(
user_path("qwen-code", Os::Linux),
"/home/ada/.qwen/settings.json"
);
assert_eq!(
user_path("kiro", Os::Linux),
"/home/ada/.kiro/settings/mcp.json"
);
assert_eq!(
user_path("copilot-cli", Os::Windows),
"C:\\Users\\ada\\.copilot\\mcp-config.json"
);
assert_eq!(
user_path("windsurf", Os::MacOs),
"/Users/ada/.codeium/windsurf/mcp_config.json"
);
assert_eq!(
user_path("factory-droid", Os::Linux),
"/home/ada/.factory/mcp.json"
);
assert_eq!(
user_path("openhands", Os::Linux),
"/home/ada/.openhands/mcp.json"
);
for id in ["cline", "windsurf", "openhands"] {
assert_eq!(project_path(id, Os::Linux), None, "{id}");
assert!(!find(id).unwrap().file_writable(Scope::Project), "{id}");
}
assert_eq!(
project_path("copilot-cli", Os::Linux),
Some(".github/mcp.json".to_owned())
);
}
#[test]
fn a_stand_in_home_keeps_every_variable_under_it() {
let v = Vars::for_home("/tmp/home", Os::Linux);
assert_eq!(v.xdg_config_home, "/tmp/home/.config");
assert_eq!(v.xdg_data_home, "/tmp/home/.local/share");
let w = Vars::for_home("C:\\tmp\\home", Os::Windows);
assert_eq!(w.appdata, "C:\\tmp\\home\\AppData\\Roaming");
assert_eq!(w.localappdata, "C:\\tmp\\home\\AppData\\Local");
assert_eq!(
w.expand("$LOCALAPPDATA/x/$APPDATA/y", Os::Windows),
"C:\\tmp\\home\\AppData\\Local\\x\\C:\\tmp\\home\\AppData\\Roaming\\y"
);
}
#[test]
fn the_add_command_is_built_from_the_template() {
let claude = find("claude-code").and_then(|c| c.cli).expect("claude cli");
assert_eq!(
claude
.add_args(Scope::User, &Launch::program("memfork"))
.unwrap(),
vec!["mcp", "add", "--scope", "user", "memfork", "--", "memfork", "mcp"]
);
let gemini = find("gemini-cli").and_then(|c| c.cli).expect("gemini cli");
assert_eq!(
gemini
.add_args(Scope::Project, &Launch::program("/opt/memfork"))
.unwrap(),
vec![
"mcp",
"add",
"-s",
"project",
"memfork",
"/opt/memfork",
"mcp"
]
);
let grok = find("grok").and_then(|c| c.cli).expect("grok cli");
assert_eq!(
grok.add_args(Scope::User, &Launch::program("memfork"))
.unwrap(),
vec!["mcp", "add", "memfork", "--", "memfork", "mcp"]
);
let args = |id: &str, scope| {
find(id)
.and_then(|c| c.cli)
.unwrap_or_else(|| panic!("{id} has a cli"))
.add_args(scope, &Launch::program("memfork"))
};
assert_eq!(
args("cline", Scope::User).unwrap(),
vec!["mcp", "add", "memfork", "--yes", "--", "memfork", "mcp"]
);
assert_eq!(
args("opencode", Scope::User).unwrap(),
vec!["mcp", "add", "memfork", "--", "memfork", "mcp"]
);
assert_eq!(
args("qwen-code", Scope::Project).unwrap(),
vec!["mcp", "add", "-s", "project", "memfork", "memfork", "mcp"]
);
assert_eq!(
args("copilot-cli", Scope::User).unwrap(),
vec!["mcp", "add", "memfork", "--", "memfork", "mcp"]
);
assert_eq!(
args("devin", Scope::User).unwrap(),
vec!["mcp", "add", "-s", "user", "memfork", "--", "memfork", "mcp"]
);
assert_eq!(
args("openhands", Scope::User).unwrap(),
vec![
"mcp",
"add",
"memfork",
"--transport",
"stdio",
"memfork",
"--",
"mcp"
]
);
for id in ["cline", "opencode", "copilot-cli", "openhands"] {
assert!(args(id, Scope::Project).is_none(), "{id}");
}
}
#[test]
fn a_cli_that_cannot_express_a_scope_says_so() {
let codex = find("codex").and_then(|c| c.cli).expect("codex cli");
assert!(codex
.add_args(Scope::User, &Launch::program("memfork"))
.is_some());
assert!(codex
.add_args(Scope::Project, &Launch::program("memfork"))
.is_none());
}
#[test]
fn a_cli_that_cannot_answer_has_no_status_command() {
let cline = find("cline").and_then(|c| c.cli).expect("cline cli");
assert!(cline.status_args().is_none());
assert!(cline.remove_args(Scope::User).is_some());
let opencode = find("opencode").and_then(|c| c.cli).expect("opencode cli");
assert!(opencode.status_args().is_some());
assert!(opencode.remove_args(Scope::User).is_none());
}
#[test]
fn claude_codes_user_file_is_not_writable() {
let claude = find("claude-code").expect("claude-code");
assert!(!claude.file_writable(Scope::User));
assert!(claude.file_writable(Scope::Project));
for id in ids().iter().filter(|id| *id != "claude-code") {
assert!(
find(id).expect(id).file_writable(Scope::User),
"{id} should be writable"
);
}
}
#[test]
fn the_http_url_quirks_are_recorded() {
for (id, key) in [
("gemini-cli", "httpUrl"),
("qwen-code", "httpUrl"),
("windsurf", "serverUrl"),
] {
let f = find(id).and_then(|c| c.file).expect(id);
assert_eq!(f.http_url_key, key, "{id}");
}
for id in [
"cursor",
"codex",
"grok",
"claude-code",
"vscode",
"zed",
"opencode",
] {
let f = find(id).and_then(|c| c.file).expect(id);
assert_eq!(f.http_url_key, "url", "{id}");
}
}
#[test]
fn the_entry_shapes_are_data() {
let shape = |id: &str| find(id).and_then(|c| c.file).expect(id);
assert_eq!(shape("claude-code").stdio_type.as_deref(), Some("stdio"));
assert_eq!(shape("vscode").stdio_type.as_deref(), Some("stdio"));
assert_eq!(shape("opencode").stdio_type.as_deref(), Some("local"));
assert_eq!(shape("copilot-cli").stdio_type.as_deref(), Some("local"));
assert_eq!(shape("cursor").stdio_type, None);
assert_eq!(shape("opencode").command_style, CommandStyle::Array);
assert_eq!(shape("vscode").command_style, CommandStyle::Split);
assert!(shape("copilot-cli")
.extra
.is_some_and(|e| e.contains_key("tools")));
assert_eq!(shape("zed").format, Format::Jsonc);
assert_eq!(shape("zed").server_map, ["context_servers"]);
assert_eq!(shape("vscode").server_map, ["servers"]);
assert_eq!(shape("opencode").server_map, ["mcp"]);
}
}