surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! Server id suggestions (#47): one slug rule for the app's Add dialog,
//! `surject server add <URL>` and `surject server add -- <COMMAND...>`, so
//! both suggest the same id for the same input.
//!
//! A suggestion follows the server id rule (SPEC 5.1): 1 to 64 characters
//! from `a-z`, `0-9`, `.`, `_`, `-`, starting with a letter or digit.

use crate::model::ids::MAX_ID_LEN;
use crate::secrets::classify::classify_import;

/// The id used when nothing in the text makes one.
pub const FALLBACK_ID: &str = "server";

/// `text` as a server id: lower case, every other character becomes `-`,
/// runs of `-` become one, separators are trimmed from both ends, at most
/// 64 characters. [`FALLBACK_ID`] when nothing is left.
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, '-' | '.' | '_'))
}

/// `base`, or `base-2`, `base-3`, ... (the stem cut to leave room for the
/// number): the first one `taken` does not hold.
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")
}

/// The id a name, an address or a command suggests: an `http(s)://`
/// address gives its host (and path, see [`from_url`]); a command line
/// that starts with a known runner or a path gives its package or program
/// ([`from_command`]); anything else is a name ([`slug`]).
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)
}

/// Host labels that name the service's MCP or API endpoint rather than the
/// service.
const HOST_PREFIXES: [&str; 6] = ["www", "mcp", "api", "server", "remote", "app"];

/// Path segments that name the transport or the endpoint, not the server.
const GENERIC_SEGMENTS: [&str; 15] = [
    "mcp",
    "sse",
    "http",
    "https",
    "mcp-server",
    "mcp_server",
    "server",
    "servers",
    "api",
    "stream",
    "streamable",
    "streamable-http",
    "message",
    "messages",
    "rpc",
];

/// The id an `http(s)://` address suggests: its host without endpoint
/// labels (`mcp.`, `api.`, ...) and the top-level domain
/// (`https://mcp.sentry.dev/mcp` gives `sentry`), then the last path
/// segment that names something (`.../@owner/weather/mcp` adds `weather`).
/// A path segment that may be a secret, holds a digit or is long is never
/// used. A loopback or IP address gives `localhost-<port>`. `None` when
/// `text` is not such an address.
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()))
}

/// The program name of `command` (its file name without the extension,
/// lower case): `C:\tools\npx.cmd` is `npx`.
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
}

/// Runners whose first positional argument is the package to run.
const PACKAGE_RUNNERS: [&str; 4] = ["npx", "bunx", "uvx", "pipx"];

/// Options of the runners that take a value (`--from X`, `-p X`).
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",
];

/// The positional arguments of `args`: options and the values of
/// [`VALUE_OPTIONS`] left out.
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
}

/// The id a command line suggests: the package an `npx`, `bunx`, `uvx`,
/// `pipx run`, `pnpm dlx` or `yarn dlx` runs (`@scope/server-github@1.2`
/// gives `github`), the module of `python -m`, the image of `docker run`,
/// the script of `node` or `python` (its folder for `index.js`), else the
/// program itself. Common `mcp`/`server` prefixes and suffixes are
/// dropped. `None` for an empty command.
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;
    // `cmd /c npx ...`: the command it runs.
    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 == '.'))
}

/// `@scope/name@version` or `name==1.0` or `name[extra]` as `name` (the
/// scope when the name is only `mcp`); a `git+https://` package as its
/// repository name.
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(),
    }
}

/// `ghcr.io/owner/name:tag` or `mcp/name@sha256:...` as `name`.
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()
}

/// Folders a build puts a script in, never the server's name.
const BUILD_DIRS: [&str; 6] = ["build", "dist", "src", "lib", "out", "bin"];

/// A script path as a name: its file name without the extension, or its
/// folder (above build folders) for `index.js`, `main.py`, `server.js`.
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()
}

/// `mcp-server-fetch`, `server-github`, `context7-mcp`, `github-mcp-server`
/// as `fetch`, `github`, `context7`, `github`; a name that would end up
/// empty is kept.
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
}