pub mod edit;
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)]
pub detect_dir: Option<String>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct ClientCli {
pub binary: String,
pub add: Vec<String>,
pub status: 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) -> Vec<String> {
self.expand(&self.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 emit_type_stdio: bool,
pub http_url_key: String,
#[serde(default)]
pub user: Option<String>,
pub project: String,
#[serde(flatten)]
overrides: BTreeMap<String, toml::Value>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Format {
Json,
Toml,
}
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 => Some(&self.project),
}
}
pub fn path_for(&self, scope: Scope, os: Os, home: &str) -> Option<String> {
let template = self.template(scope, os)?;
let expanded = template.replace("$HOME", home.trim_end_matches(['/', '\\']));
let sep = os.separator();
Some(
expanded
.split(['/', '\\'])
.collect::<Vec<_>>()
.join(&sep.to_string()),
)
}
pub fn path_here(&self, scope: Scope, home: &str) -> Option<PathBuf> {
self.path_for(scope, Os::current(), home).map(PathBuf::from)
}
}
impl Client {
pub fn detect_dir_here(&self, home: &str) -> Option<PathBuf> {
let template = self.detect_dir.as_ref()?;
let expanded = template.replace("$HOME", home.trim_end_matches(['/', '\\']));
Some(PathBuf::from(expanded))
}
pub fn file_writable(&self, scope: Scope) -> bool {
match (&self.file, scope) {
(None, _) => false,
(Some(f), Scope::User) => f.user.is_some(),
(Some(_), Scope::Project) => true,
}
}
pub fn status_command(&self) -> Option<(String, PathBuf, Vec<String>)> {
let cli = self.cli.as_ref()?;
let resolved = crate::init::which(&cli.binary)?;
Some((cli.binary.clone(), resolved, cli.status_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(" "));
return match std::process::Command::new(&resolved).args(&args).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> {
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 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 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"],
"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
);
}
}
#[test]
fn paths_resolve_for_every_os() {
let cursor = find("cursor").expect("cursor is in the registry");
let file = cursor.file.expect("cursor registers by file");
assert_eq!(
file.path_for(Scope::User, Os::Linux, "/home/ada"),
Some("/home/ada/.cursor/mcp.json".to_owned())
);
assert_eq!(
file.path_for(Scope::User, Os::MacOs, "/Users/ada"),
Some("/Users/ada/.cursor/mcp.json".to_owned())
);
assert_eq!(
file.path_for(Scope::User, Os::Windows, "C:\\Users\\ada"),
Some("C:\\Users\\ada\\.cursor\\mcp.json".to_owned())
);
assert_eq!(
file.path_for(Scope::Project, Os::Windows, "C:\\Users\\ada"),
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, "/home/ada/"),
Some("/home/ada/.cursor/mcp.json".to_owned())
);
}
#[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"]
);
}
#[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 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 ["cursor", "codex", "gemini-cli", "grok"] {
assert!(
find(id).expect(id).file_writable(Scope::User),
"{id} should be writable"
);
}
}
#[test]
fn the_gemini_http_url_quirk_is_recorded() {
let gemini = find("gemini-cli")
.and_then(|c| c.file)
.expect("gemini file");
assert_eq!(gemini.http_url_key, "httpUrl");
for id in ["cursor", "codex", "grok", "claude-code"] {
let f = find(id).and_then(|c| c.file).expect(id);
assert_eq!(f.http_url_key, "url", "{id}");
}
}
}