use crate::model::ids::MAX_ID_LEN;
use crate::secrets::classify::classify_import;
pub const FALLBACK_ID: &str = "server";
pub fn slug(text: &str) -> String {
let mut id = String::with_capacity(text.len().min(MAX_ID_LEN));
for c in text.trim().chars() {
let c = c.to_ascii_lowercase();
let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
c
} else {
'-'
};
if c == '-' && id.ends_with('-') {
continue;
}
id.push(c);
}
let trimmed = trim_separators(&id);
let mut id = trimmed[..trimmed.len().min(MAX_ID_LEN)].to_owned();
id.truncate(trim_separators(&id).len());
if id.is_empty() {
FALLBACK_ID.to_owned()
} else {
id
}
}
fn trim_separators(text: &str) -> &str {
text.trim_matches(|c| matches!(c, '-' | '.' | '_'))
}
pub fn unique(base: &str, taken: impl Fn(&str) -> bool) -> String {
if !taken(base) {
return base.to_owned();
}
let stem = trim_separators(&base[..base.len().min(MAX_ID_LEN - 4)]);
(2u32..)
.map(|n| format!("{stem}-{n}"))
.find(|id| !taken(id))
.expect("a free id")
}
pub fn suggest(text: &str) -> String {
let text = text.trim();
if let Some(id) = from_url(text) {
return id;
}
if let Some(argv) = super::split_command(text)
&& super::looks_like_command(&argv)
&& let Some(id) = from_command(&argv)
{
return id;
}
slug(text)
}
const HOST_PREFIXES: [&str; 6] = ["www", "mcp", "api", "server", "remote", "app"];
const GENERIC_SEGMENTS: [&str; 15] = [
"mcp",
"sse",
"http",
"https",
"mcp-server",
"mcp_server",
"server",
"servers",
"api",
"stream",
"streamable",
"streamable-http",
"message",
"messages",
"rpc",
];
pub fn from_url(text: &str) -> Option<String> {
let url = url::Url::parse(text).ok()?;
if !matches!(url.scheme(), "http" | "https") {
return None;
}
let host = url.host()?;
let named = |segment: &str| {
let lower = segment.to_ascii_lowercase();
!lower.is_empty()
&& lower.len() <= 32
&& !GENERIC_SEGMENTS.contains(&lower.as_str())
&& !is_version(&lower)
&& lower.chars().any(|c| c.is_ascii_alphabetic())
&& !lower.chars().any(|c| c.is_ascii_digit())
&& classify_import(None, segment).is_none()
};
let segment = url
.path_segments()
.into_iter()
.flatten()
.rfind(|segment| named(segment))
.map(str::to_owned);
let stem = match host {
url::Host::Domain(domain) if domain != "localhost" => {
let mut labels: Vec<&str> = domain.split('.').filter(|l| !l.is_empty()).collect();
if labels.len() > 1 {
labels.pop();
}
while labels.len() > 1 && HOST_PREFIXES.contains(&labels[0]) {
labels.remove(0);
}
labels.join("-")
}
_ => match url.port() {
Some(port) => format!("localhost-{port}"),
None => "localhost".to_owned(),
},
};
let text = match segment {
Some(segment) if !stem.split('-').any(|label| label == segment) => {
format!("{stem}-{segment}")
}
_ => stem,
};
Some(slug(&text))
}
fn is_version(segment: &str) -> bool {
segment
.strip_prefix('v')
.is_some_and(|rest| !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()))
}
pub(crate) fn program_name(command: &str) -> String {
let file = command.rsplit(['/', '\\']).next().unwrap_or(command);
let lower = file.to_ascii_lowercase();
for ext in [".exe", ".cmd", ".bat", ".ps1", ".sh"] {
if let Some(stem) = lower.strip_suffix(ext) {
return stem.to_owned();
}
}
lower
}
const PACKAGE_RUNNERS: [&str; 4] = ["npx", "bunx", "uvx", "pipx"];
const VALUE_OPTIONS: [&str; 22] = [
"--from",
"--with",
"--python",
"-p",
"--package",
"--index-url",
"--registry",
"-e",
"--env",
"--env-file",
"-v",
"--volume",
"--name",
"--network",
"-w",
"--workdir",
"-u",
"--user",
"--entrypoint",
"--mount",
"--label",
"--platform",
];
fn positionals(args: &[String]) -> Vec<&str> {
let mut out = Vec::new();
let mut skip = false;
for arg in args {
if skip {
skip = false;
continue;
}
if arg.starts_with('-') {
skip = !arg.contains('=') && VALUE_OPTIONS.contains(&arg.as_str());
continue;
}
out.push(arg.as_str());
}
out
}
pub fn from_command(argv: &[String]) -> Option<String> {
let (command, args) = argv.split_first()?;
let mut program = program_name(command);
let mut args: &[String] = args;
if program == "cmd"
&& let Some(at) = args
.iter()
.position(|arg| arg.eq_ignore_ascii_case("/c") || arg.eq_ignore_ascii_case("/k"))
&& let Some((inner, rest)) = args[at + 1..].split_first()
{
program = program_name(inner);
args = rest;
}
let first = |args: &[String]| positionals(args).first().map(|s| (*s).to_owned());
let name = match program.as_str() {
p if PACKAGE_RUNNERS.contains(&p) => {
let args = match (p, args.first()) {
("pipx", Some(run)) if run == "run" => &args[1..],
_ => args,
};
first(args).map(|package| package_name(&package))
}
"pnpm" | "yarn" | "npm" => {
let at = args
.iter()
.position(|arg| matches!(arg.as_str(), "dlx" | "exec" | "x"));
at.and_then(|at| first(&args[at + 1..]))
.map(|package| package_name(&package))
}
"docker" | "podman" => {
let at = args.iter().position(|arg| arg == "run");
at.and_then(|at| first(&args[at + 1..]))
.map(|image| image_name(&image))
}
p if is_python(p) => {
if let Some(at) = args.iter().position(|arg| arg == "-m") {
args.get(at + 1)
.map(|module| module.split('.').next().unwrap_or(module).to_owned())
} else {
first(args).map(|script| script_name(&script))
}
}
"uv" => {
let at = args.iter().position(|arg| arg == "run");
at.and_then(|at| {
let rest = &args[at + 1..];
let positional = positionals(rest);
match positional.first() {
Some(&python) if is_python(&program_name(python)) => rest
.iter()
.position(|arg| arg == "-m")
.and_then(|m| rest.get(m + 1).cloned())
.or_else(|| positional.get(1).map(|s| script_name(s))),
Some(script) => Some(script_name(script)),
None => None,
}
})
}
"node" | "deno" | "bun" | "tsx" | "ts-node" => {
let rest = match args.first() {
Some(run) if program != "node" && run == "run" => &args[1..],
_ => args,
};
first(rest).map(|script| script_name(&script))
}
_ => None,
};
let name = name.unwrap_or_else(|| script_name(command));
Some(slug(&strip_mcp_words(&name)))
}
fn is_python(program: &str) -> bool {
program == "py"
|| program == "python"
|| program
.strip_prefix("python")
.is_some_and(|rest| rest.chars().all(|c| c.is_ascii_digit() || c == '.'))
}
fn package_name(package: &str) -> String {
let package = package.trim_end_matches('/');
if package.contains("://") {
let last = package.rsplit('/').next().unwrap_or(package);
return last.trim_end_matches(".git").to_owned();
}
let (scope, rest) = match package.strip_prefix('@') {
Some(scoped) => match scoped.split_once('/') {
Some((scope, rest)) => (Some(scope), rest),
None => (None, scoped),
},
None => (None, package),
};
let name = rest
.split(['@', '=', '[', '<', '>', '~', '!'])
.next()
.unwrap_or(rest);
match scope {
Some(scope)
if matches!(
name.to_ascii_lowercase().as_str(),
"mcp" | "server" | "mcp-server"
) =>
{
scope.to_owned()
}
_ => name.to_owned(),
}
}
fn image_name(image: &str) -> String {
let image = image.split('@').next().unwrap_or(image);
let last = image.rsplit('/').next().unwrap_or(image);
last.split(':').next().unwrap_or(last).to_owned()
}
const BUILD_DIRS: [&str; 6] = ["build", "dist", "src", "lib", "out", "bin"];
fn script_name(path: &str) -> String {
let mut parts: Vec<&str> = path.split(['/', '\\']).filter(|p| !p.is_empty()).collect();
let file = parts.pop().unwrap_or(path);
let stem = match file.rsplit_once('.') {
Some((stem, _)) if !stem.is_empty() => stem,
_ => file,
};
if matches!(
stem.to_ascii_lowercase().as_str(),
"index" | "main" | "server" | "__main__" | "cli" | "app"
) {
while let Some(dir) = parts.pop() {
if !BUILD_DIRS.contains(&dir.to_ascii_lowercase().as_str()) && !dir.ends_with(':') {
return dir.to_owned();
}
}
}
stem.to_owned()
}
fn strip_mcp_words(name: &str) -> String {
let mut name = name.to_ascii_lowercase().replace('_', "-");
for prefix in ["mcp-server-", "server-", "mcp-"] {
if let Some(rest) = name.strip_prefix(prefix)
&& !rest.is_empty()
{
name = rest.to_owned();
break;
}
}
for suffix in ["-mcp-server", "-server-mcp", "-mcp", "-server"] {
if let Some(rest) = name.strip_suffix(suffix)
&& !rest.is_empty()
{
name = rest.to_owned();
break;
}
}
name
}