Skip to main content

surjection_core/server_input/
suggest.rs

1//! Server id suggestions (#47): one slug rule for the app's Add dialog,
2//! `surject server add <URL>` and `surject server add -- <COMMAND...>`, so
3//! both suggest the same id for the same input.
4//!
5//! A suggestion follows the server id rule (SPEC 5.1): 1 to 64 characters
6//! from `a-z`, `0-9`, `.`, `_`, `-`, starting with a letter or digit.
7
8use crate::model::ids::MAX_ID_LEN;
9use crate::secrets::classify::classify_import;
10
11/// The id used when nothing in the text makes one.
12pub const FALLBACK_ID: &str = "server";
13
14/// `text` as a server id: lower case, every other character becomes `-`,
15/// runs of `-` become one, separators are trimmed from both ends, at most
16/// 64 characters. [`FALLBACK_ID`] when nothing is left.
17pub fn slug(text: &str) -> String {
18    let mut id = String::with_capacity(text.len().min(MAX_ID_LEN));
19    for c in text.trim().chars() {
20        let c = c.to_ascii_lowercase();
21        let c = if c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '-') {
22            c
23        } else {
24            '-'
25        };
26        if c == '-' && id.ends_with('-') {
27            continue;
28        }
29        id.push(c);
30    }
31    let trimmed = trim_separators(&id);
32    let mut id = trimmed[..trimmed.len().min(MAX_ID_LEN)].to_owned();
33    id.truncate(trim_separators(&id).len());
34    if id.is_empty() {
35        FALLBACK_ID.to_owned()
36    } else {
37        id
38    }
39}
40
41fn trim_separators(text: &str) -> &str {
42    text.trim_matches(|c| matches!(c, '-' | '.' | '_'))
43}
44
45/// `base`, or `base-2`, `base-3`, ... (the stem cut to leave room for the
46/// number): the first one `taken` does not hold.
47pub fn unique(base: &str, taken: impl Fn(&str) -> bool) -> String {
48    if !taken(base) {
49        return base.to_owned();
50    }
51    let stem = trim_separators(&base[..base.len().min(MAX_ID_LEN - 4)]);
52    (2u32..)
53        .map(|n| format!("{stem}-{n}"))
54        .find(|id| !taken(id))
55        .expect("a free id")
56}
57
58/// The id a name, an address or a command suggests: an `http(s)://`
59/// address gives its host (and path, see [`from_url`]); a command line
60/// that starts with a known runner or a path gives its package or program
61/// ([`from_command`]); anything else is a name ([`slug`]).
62pub fn suggest(text: &str) -> String {
63    let text = text.trim();
64    if let Some(id) = from_url(text) {
65        return id;
66    }
67    if let Some(argv) = super::split_command(text)
68        && super::looks_like_command(&argv)
69        && let Some(id) = from_command(&argv)
70    {
71        return id;
72    }
73    slug(text)
74}
75
76/// Host labels that name the service's MCP or API endpoint rather than the
77/// service.
78const HOST_PREFIXES: [&str; 6] = ["www", "mcp", "api", "server", "remote", "app"];
79
80/// Path segments that name the transport or the endpoint, not the server.
81const GENERIC_SEGMENTS: [&str; 15] = [
82    "mcp",
83    "sse",
84    "http",
85    "https",
86    "mcp-server",
87    "mcp_server",
88    "server",
89    "servers",
90    "api",
91    "stream",
92    "streamable",
93    "streamable-http",
94    "message",
95    "messages",
96    "rpc",
97];
98
99/// The id an `http(s)://` address suggests: its host without endpoint
100/// labels (`mcp.`, `api.`, ...) and the top-level domain
101/// (`https://mcp.sentry.dev/mcp` gives `sentry`), then the last path
102/// segment that names something (`.../@owner/weather/mcp` adds `weather`).
103/// A path segment that may be a secret, holds a digit or is long is never
104/// used. A loopback or IP address gives `localhost-<port>`. `None` when
105/// `text` is not such an address.
106pub fn from_url(text: &str) -> Option<String> {
107    let url = url::Url::parse(text).ok()?;
108    if !matches!(url.scheme(), "http" | "https") {
109        return None;
110    }
111    let host = url.host()?;
112    let named = |segment: &str| {
113        let lower = segment.to_ascii_lowercase();
114        !lower.is_empty()
115            && lower.len() <= 32
116            && !GENERIC_SEGMENTS.contains(&lower.as_str())
117            && !is_version(&lower)
118            && lower.chars().any(|c| c.is_ascii_alphabetic())
119            && !lower.chars().any(|c| c.is_ascii_digit())
120            && classify_import(None, segment).is_none()
121    };
122    let segment = url
123        .path_segments()
124        .into_iter()
125        .flatten()
126        .rfind(|segment| named(segment))
127        .map(str::to_owned);
128    let stem = match host {
129        url::Host::Domain(domain) if domain != "localhost" => {
130            let mut labels: Vec<&str> = domain.split('.').filter(|l| !l.is_empty()).collect();
131            if labels.len() > 1 {
132                labels.pop();
133            }
134            while labels.len() > 1 && HOST_PREFIXES.contains(&labels[0]) {
135                labels.remove(0);
136            }
137            labels.join("-")
138        }
139        _ => match url.port() {
140            Some(port) => format!("localhost-{port}"),
141            None => "localhost".to_owned(),
142        },
143    };
144    let text = match segment {
145        Some(segment) if !stem.split('-').any(|label| label == segment) => {
146            format!("{stem}-{segment}")
147        }
148        _ => stem,
149    };
150    Some(slug(&text))
151}
152
153fn is_version(segment: &str) -> bool {
154    segment
155        .strip_prefix('v')
156        .is_some_and(|rest| !rest.is_empty() && rest.chars().all(|c| c.is_ascii_digit()))
157}
158
159/// The program name of `command` (its file name without the extension,
160/// lower case): `C:\tools\npx.cmd` is `npx`.
161pub(crate) fn program_name(command: &str) -> String {
162    let file = command.rsplit(['/', '\\']).next().unwrap_or(command);
163    let lower = file.to_ascii_lowercase();
164    for ext in [".exe", ".cmd", ".bat", ".ps1", ".sh"] {
165        if let Some(stem) = lower.strip_suffix(ext) {
166            return stem.to_owned();
167        }
168    }
169    lower
170}
171
172/// Runners whose first positional argument is the package to run.
173const PACKAGE_RUNNERS: [&str; 4] = ["npx", "bunx", "uvx", "pipx"];
174
175/// Options of the runners that take a value (`--from X`, `-p X`).
176const VALUE_OPTIONS: [&str; 22] = [
177    "--from",
178    "--with",
179    "--python",
180    "-p",
181    "--package",
182    "--index-url",
183    "--registry",
184    "-e",
185    "--env",
186    "--env-file",
187    "-v",
188    "--volume",
189    "--name",
190    "--network",
191    "-w",
192    "--workdir",
193    "-u",
194    "--user",
195    "--entrypoint",
196    "--mount",
197    "--label",
198    "--platform",
199];
200
201/// The positional arguments of `args`: options and the values of
202/// [`VALUE_OPTIONS`] left out.
203fn positionals(args: &[String]) -> Vec<&str> {
204    let mut out = Vec::new();
205    let mut skip = false;
206    for arg in args {
207        if skip {
208            skip = false;
209            continue;
210        }
211        if arg.starts_with('-') {
212            skip = !arg.contains('=') && VALUE_OPTIONS.contains(&arg.as_str());
213            continue;
214        }
215        out.push(arg.as_str());
216    }
217    out
218}
219
220/// The id a command line suggests: the package an `npx`, `bunx`, `uvx`,
221/// `pipx run`, `pnpm dlx` or `yarn dlx` runs (`@scope/server-github@1.2`
222/// gives `github`), the module of `python -m`, the image of `docker run`,
223/// the script of `node` or `python` (its folder for `index.js`), else the
224/// program itself. Common `mcp`/`server` prefixes and suffixes are
225/// dropped. `None` for an empty command.
226pub fn from_command(argv: &[String]) -> Option<String> {
227    let (command, args) = argv.split_first()?;
228    let mut program = program_name(command);
229    let mut args: &[String] = args;
230    // `cmd /c npx ...`: the command it runs.
231    if program == "cmd"
232        && let Some(at) = args
233            .iter()
234            .position(|arg| arg.eq_ignore_ascii_case("/c") || arg.eq_ignore_ascii_case("/k"))
235        && let Some((inner, rest)) = args[at + 1..].split_first()
236    {
237        program = program_name(inner);
238        args = rest;
239    }
240    let first = |args: &[String]| positionals(args).first().map(|s| (*s).to_owned());
241    let name = match program.as_str() {
242        p if PACKAGE_RUNNERS.contains(&p) => {
243            let args = match (p, args.first()) {
244                ("pipx", Some(run)) if run == "run" => &args[1..],
245                _ => args,
246            };
247            first(args).map(|package| package_name(&package))
248        }
249        "pnpm" | "yarn" | "npm" => {
250            let at = args
251                .iter()
252                .position(|arg| matches!(arg.as_str(), "dlx" | "exec" | "x"));
253            at.and_then(|at| first(&args[at + 1..]))
254                .map(|package| package_name(&package))
255        }
256        "docker" | "podman" => {
257            let at = args.iter().position(|arg| arg == "run");
258            at.and_then(|at| first(&args[at + 1..]))
259                .map(|image| image_name(&image))
260        }
261        p if is_python(p) => {
262            if let Some(at) = args.iter().position(|arg| arg == "-m") {
263                args.get(at + 1)
264                    .map(|module| module.split('.').next().unwrap_or(module).to_owned())
265            } else {
266                first(args).map(|script| script_name(&script))
267            }
268        }
269        "uv" => {
270            let at = args.iter().position(|arg| arg == "run");
271            at.and_then(|at| {
272                let rest = &args[at + 1..];
273                let positional = positionals(rest);
274                match positional.first() {
275                    Some(&python) if is_python(&program_name(python)) => rest
276                        .iter()
277                        .position(|arg| arg == "-m")
278                        .and_then(|m| rest.get(m + 1).cloned())
279                        .or_else(|| positional.get(1).map(|s| script_name(s))),
280                    Some(script) => Some(script_name(script)),
281                    None => None,
282                }
283            })
284        }
285        "node" | "deno" | "bun" | "tsx" | "ts-node" => {
286            let rest = match args.first() {
287                Some(run) if program != "node" && run == "run" => &args[1..],
288                _ => args,
289            };
290            first(rest).map(|script| script_name(&script))
291        }
292        _ => None,
293    };
294    let name = name.unwrap_or_else(|| script_name(command));
295    Some(slug(&strip_mcp_words(&name)))
296}
297
298fn is_python(program: &str) -> bool {
299    program == "py"
300        || program == "python"
301        || program
302            .strip_prefix("python")
303            .is_some_and(|rest| rest.chars().all(|c| c.is_ascii_digit() || c == '.'))
304}
305
306/// `@scope/name@version` or `name==1.0` or `name[extra]` as `name` (the
307/// scope when the name is only `mcp`); a `git+https://` package as its
308/// repository name.
309fn package_name(package: &str) -> String {
310    let package = package.trim_end_matches('/');
311    if package.contains("://") {
312        let last = package.rsplit('/').next().unwrap_or(package);
313        return last.trim_end_matches(".git").to_owned();
314    }
315    let (scope, rest) = match package.strip_prefix('@') {
316        Some(scoped) => match scoped.split_once('/') {
317            Some((scope, rest)) => (Some(scope), rest),
318            None => (None, scoped),
319        },
320        None => (None, package),
321    };
322    let name = rest
323        .split(['@', '=', '[', '<', '>', '~', '!'])
324        .next()
325        .unwrap_or(rest);
326    match scope {
327        Some(scope)
328            if matches!(
329                name.to_ascii_lowercase().as_str(),
330                "mcp" | "server" | "mcp-server"
331            ) =>
332        {
333            scope.to_owned()
334        }
335        _ => name.to_owned(),
336    }
337}
338
339/// `ghcr.io/owner/name:tag` or `mcp/name@sha256:...` as `name`.
340fn image_name(image: &str) -> String {
341    let image = image.split('@').next().unwrap_or(image);
342    let last = image.rsplit('/').next().unwrap_or(image);
343    last.split(':').next().unwrap_or(last).to_owned()
344}
345
346/// Folders a build puts a script in, never the server's name.
347const BUILD_DIRS: [&str; 6] = ["build", "dist", "src", "lib", "out", "bin"];
348
349/// A script path as a name: its file name without the extension, or its
350/// folder (above build folders) for `index.js`, `main.py`, `server.js`.
351fn script_name(path: &str) -> String {
352    let mut parts: Vec<&str> = path.split(['/', '\\']).filter(|p| !p.is_empty()).collect();
353    let file = parts.pop().unwrap_or(path);
354    let stem = match file.rsplit_once('.') {
355        Some((stem, _)) if !stem.is_empty() => stem,
356        _ => file,
357    };
358    if matches!(
359        stem.to_ascii_lowercase().as_str(),
360        "index" | "main" | "server" | "__main__" | "cli" | "app"
361    ) {
362        while let Some(dir) = parts.pop() {
363            if !BUILD_DIRS.contains(&dir.to_ascii_lowercase().as_str()) && !dir.ends_with(':') {
364                return dir.to_owned();
365            }
366        }
367    }
368    stem.to_owned()
369}
370
371/// `mcp-server-fetch`, `server-github`, `context7-mcp`, `github-mcp-server`
372/// as `fetch`, `github`, `context7`, `github`; a name that would end up
373/// empty is kept.
374fn strip_mcp_words(name: &str) -> String {
375    let mut name = name.to_ascii_lowercase().replace('_', "-");
376    for prefix in ["mcp-server-", "server-", "mcp-"] {
377        if let Some(rest) = name.strip_prefix(prefix)
378            && !rest.is_empty()
379        {
380            name = rest.to_owned();
381            break;
382        }
383    }
384    for suffix in ["-mcp-server", "-server-mcp", "-mcp", "-server"] {
385        if let Some(rest) = name.strip_suffix(suffix)
386            && !rest.is_empty()
387        {
388            name = rest.to_owned();
389            break;
390        }
391    }
392    name
393}