Skip to main content

surjection_core/server_input/
mod.rs

1//! What a pasted or typed server is (#47, the Add dialog and `surject server
2//! add <URL>` / `-- <COMMAND...>`): an address, a config snippet, a
3//! command line, a repository or a folder; the transport an address
4//! suggests; the clients a new server is enabled for by default; and the
5//! entries client files already hold for the same address or command (the
6//! dialog offers Import instead).
7//!
8//! Analysis reads no network and runs nothing; the folder check only asks
9//! whether the path is a directory.
10
11pub mod suggest;
12
13use std::path::PathBuf;
14use std::sync::Arc;
15
16use crate::apply::ApplyEnv;
17use crate::apply::import::{self, ScanFilter, ScanScope};
18use crate::apply::render::{DesiredState, Detected, RenderCx};
19use crate::env::Env;
20use crate::error::CoreError;
21use crate::fs::Fs;
22use crate::mcp_source::snippet;
23use crate::model::applied::Scope;
24use crate::model::clients::ClientSelection;
25use crate::model::server::Transport;
26use crate::secrets::scanner::SecretMemory;
27use crate::store::Store;
28
29/// What the text is.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum InputKind {
32    /// An `http(s)://` address of a remote server.
33    Url,
34    /// A client config snippet (JSON, JSONC, TOML, YAML) holding entries.
35    Snippet,
36    /// A command line that starts a local (stdio) server.
37    Command,
38    /// A git repository to find servers in.
39    Repository,
40    /// A local folder to find servers in.
41    Folder,
42    /// Nothing recognized (or empty).
43    Unknown,
44}
45
46impl InputKind {
47    pub const fn as_str(self) -> &'static str {
48        match self {
49            InputKind::Url => "url",
50            InputKind::Snippet => "snippet",
51            InputKind::Command => "command",
52            InputKind::Repository => "repository",
53            InputKind::Folder => "folder",
54            InputKind::Unknown => "unknown",
55        }
56    }
57}
58
59/// The result of [`analyze`].
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct Analysis {
62    pub kind: InputKind,
63    /// [`InputKind::Url`]: the address as given (trimmed).
64    pub url: Option<String>,
65    /// [`InputKind::Url`]: from the path ([`transport_from_url`]);
66    /// [`InputKind::Command`]: stdio.
67    pub transport: Option<Transport>,
68    /// [`InputKind::Command`]: the program and its arguments.
69    pub command: Option<String>,
70    pub args: Vec<String>,
71    /// [`InputKind::Repository`]: the address to clone.
72    pub repository: Option<String>,
73    /// [`InputKind::Folder`]: the folder (`~` expanded).
74    pub folder: Option<PathBuf>,
75    /// [`InputKind::Snippet`]: how many entries it holds.
76    pub snippet_entries: usize,
77    /// [`InputKind::Url`] and [`InputKind::Command`]: the id it suggests
78    /// ([`suggest::suggest`]), before it is made unique in the store.
79    pub suggested_id: Option<String>,
80    /// The detection result in English ("Remote server (Streamable HTTP)").
81    pub message: String,
82}
83
84impl Analysis {
85    fn new(kind: InputKind, message: impl Into<String>) -> Self {
86        Self {
87            kind,
88            url: None,
89            transport: None,
90            command: None,
91            args: Vec::new(),
92            repository: None,
93            folder: None,
94            snippet_entries: 0,
95            suggested_id: None,
96            message: message.into(),
97        }
98    }
99}
100
101/// Hosts whose `/<owner>/<repo>` addresses are repositories, not servers.
102const FORGES: [&str; 5] = [
103    "github.com",
104    "gitlab.com",
105    "bitbucket.org",
106    "codeberg.org",
107    "git.sr.ht",
108];
109
110/// Programs that start a local server (the first word of a command line);
111/// a path to a program counts too.
112const RUNNERS: [&str; 22] = [
113    "npx", "bunx", "uvx", "pipx", "node", "deno", "bun", "tsx", "uv", "python", "python3", "py",
114    "docker", "podman", "pnpm", "yarn", "npm", "java", "dotnet", "go", "cmd", "pwsh",
115];
116
117/// Reads `text` (see the module docs). The order: an address (a
118/// repository when it names one), a folder, a snippet, a command line.
119pub fn analyze(text: &str, env: &Env, fs: &dyn Fs) -> Analysis {
120    let text = text.trim();
121    if text.is_empty() {
122        return Analysis::new(
123            InputKind::Unknown,
124            "Paste a server URL, a config snippet or a command",
125        );
126    }
127    let single_line = !text.contains(['\n', '\r']);
128    if single_line && let Some(repository) = repository_url(text) {
129        let mut analysis = Analysis::new(
130            InputKind::Repository,
131            "Looks like a repository: find servers in it",
132        );
133        analysis.repository = Some(repository);
134        return analysis;
135    }
136    if single_line && is_http_url(text) {
137        let transport = transport_from_url(text);
138        let mut analysis = Analysis::new(
139            InputKind::Url,
140            match transport {
141                Transport::Sse => "Remote server (SSE)",
142                _ => "Remote server (Streamable HTTP)",
143            },
144        );
145        analysis.url = Some(text.to_owned());
146        analysis.transport = Some(transport);
147        analysis.suggested_id = suggest::from_url(text);
148        return analysis;
149    }
150    if single_line && let Some(folder) = folder_path(text, env, fs) {
151        let mut analysis = Analysis::new(InputKind::Folder, "A folder: find servers in it");
152        analysis.folder = Some(folder);
153        return analysis;
154    }
155    if let Some(doc) = snippet::parse_any(text)
156        && let Ok(entries) = snippet::entries(&doc, env.os(), None)
157    {
158        let count = entries.entries.len();
159        let mut analysis = Analysis::new(
160            InputKind::Snippet,
161            if count == 1 {
162                format!("Config snippet ({}): 1 server", entries.spec.display_name)
163            } else {
164                format!(
165                    "Config snippet ({}): {count} servers",
166                    entries.spec.display_name
167                )
168            },
169        );
170        analysis.snippet_entries = count;
171        return analysis;
172    }
173    if single_line {
174        let argv = program_path_with_args(text, fs).or_else(|| split_command(text));
175        if let Some(argv) = argv.filter(|argv| looks_like_command(argv)) {
176            let mut analysis = Analysis::new(InputKind::Command, "Local command (stdio)");
177            analysis.suggested_id = suggest::from_command(&argv);
178            analysis.transport = Some(Transport::Stdio);
179            let mut argv = argv.into_iter();
180            analysis.command = argv.next();
181            analysis.args = argv.collect();
182            return analysis;
183        }
184    }
185    Analysis::new(
186        InputKind::Unknown,
187        "Not recognized: paste a server URL, a config snippet or a command",
188    )
189}
190
191fn is_http_url(text: &str) -> bool {
192    url::Url::parse(text)
193        .is_ok_and(|url| matches!(url.scheme(), "http" | "https") && url.host().is_some())
194}
195
196/// `text` as a repository address: `git@host:owner/repo`, `ssh://` and
197/// `git://` addresses, an address ending in `.git`, or
198/// `https://<forge>/<owner>/<repo>[/tree/...]` on a known forge.
199pub fn repository_url(text: &str) -> Option<String> {
200    if text.contains(char::is_whitespace) {
201        return None;
202    }
203    if (text.starts_with("git@") && text.contains(':'))
204        || text.starts_with("ssh://")
205        || text.starts_with("git://")
206    {
207        return Some(text.to_owned());
208    }
209    let url = url::Url::parse(text).ok()?;
210    if !matches!(url.scheme(), "http" | "https") {
211        return None;
212    }
213    if url.path().trim_end_matches('/').ends_with(".git") {
214        return Some(text.to_owned());
215    }
216    let host = url.host_str()?.trim_start_matches("www.");
217    let segments: Vec<&str> = url.path_segments()?.filter(|s| !s.is_empty()).collect();
218    // A forge's own endpoints (`gitlab.com/api/v4/mcp`) are servers.
219    let endpoint = segments
220        .first()
221        .is_some_and(|first| first.eq_ignore_ascii_case("api"))
222        || segments
223            .last()
224            .is_some_and(|last| matches!(last.to_ascii_lowercase().as_str(), "mcp" | "sse"));
225    (FORGES.contains(&host) && segments.len() >= 2 && !endpoint).then(|| text.to_owned())
226}
227
228/// An unquoted absolute program path with spaces (`C:\Program
229/// Files\nodejs\npx.cmd -y pkg`): the longest run of leading words that
230/// names an existing file is the program, the other words its arguments
231/// (split as [`split_command`] does). `None` when no such file exists or
232/// the text does not start with an absolute path.
233fn program_path_with_args(text: &str, fs: &dyn Fs) -> Option<Vec<String>> {
234    let text = text.trim();
235    if text.starts_with(['"', '\'']) || !std::path::Path::new(text).has_root() {
236        return None;
237    }
238    let words: Vec<&str> = text.split_whitespace().collect();
239    (1..=words.len()).rev().find_map(|n| {
240        let program = words[..n].join(" ");
241        let path = std::path::Path::new(&program);
242        if !path.is_absolute() || !fs.is_regular_file(path) {
243            return None;
244        }
245        let rest = words[n..].join(" ");
246        let mut argv = vec![program];
247        argv.extend(split_command(&rest).unwrap_or_default());
248        Some(argv)
249    })
250}
251
252/// `text` as an existing folder: an absolute path, or one under `~`.
253fn folder_path(text: &str, env: &Env, fs: &dyn Fs) -> Option<PathBuf> {
254    let text = text.trim_matches('"');
255    let path = match text.strip_prefix("~/").or_else(|| text.strip_prefix("~\\")) {
256        Some(rest) => env.home().join(rest),
257        None if text == "~" => env.home().to_path_buf(),
258        None => PathBuf::from(text),
259    };
260    let absolute = path.is_absolute() || path.has_root();
261    (absolute && fs.is_dir(&path)).then_some(path)
262}
263
264/// The transport an address suggests: `sse` when its path ends in `/sse`,
265/// else Streamable HTTP.
266pub fn transport_from_url(url: &str) -> Transport {
267    let path = url::Url::parse(url)
268        .ok()
269        .map(|url| url.path().trim_end_matches('/').to_ascii_lowercase());
270    match path {
271        Some(path) if path.ends_with("/sse") => Transport::Sse,
272        _ => Transport::Http,
273    }
274}
275
276/// A one-line command as words: whitespace separates, `"..."` and `'...'`
277/// group (quotes removed). A backslash is an ordinary character, so
278/// Windows paths stay whole. A leading `$ ` or `> ` prompt is dropped.
279/// `None` for empty text or an unclosed quote.
280pub fn split_command(text: &str) -> Option<Vec<String>> {
281    let text = text.trim();
282    let text = text
283        .strip_prefix("$ ")
284        .or_else(|| text.strip_prefix("> "))
285        .unwrap_or(text);
286    let mut words = Vec::new();
287    let mut word = String::new();
288    let mut in_word = false;
289    let mut quote: Option<char> = None;
290    for c in text.chars() {
291        match quote {
292            Some(q) if c == q => quote = None,
293            Some(_) => word.push(c),
294            None if c == '"' || c == '\'' => {
295                quote = Some(c);
296                in_word = true;
297            }
298            None if c.is_whitespace() => {
299                if in_word {
300                    words.push(std::mem::take(&mut word));
301                    in_word = false;
302                }
303            }
304            None => {
305                word.push(c);
306                in_word = true;
307            }
308        }
309    }
310    if quote.is_some() {
311        return None;
312    }
313    if in_word {
314        words.push(word);
315    }
316    (!words.is_empty()).then_some(words)
317}
318
319/// Whether `argv` starts a local server: its program is a known runner
320/// ([`RUNNERS`]) or a path to a program.
321pub fn looks_like_command(argv: &[String]) -> bool {
322    let Some(command) = argv.first() else {
323        return false;
324    };
325    let program = suggest::program_name(command);
326    let is_path = command.contains(['/', '\\'])
327        || [".exe", ".cmd", ".bat", ".js", ".mjs", ".py", ".sh"]
328            .iter()
329            .any(|ext| command.to_ascii_lowercase().ends_with(ext));
330    !command.contains("://") && (is_path || RUNNERS.contains(&program.as_str()))
331}
332
333/// The clients a new server with `transport` is enabled for by default:
334/// the ones `all-detected` selects here (detected or forced on in
335/// `clients.toml`, with an MCP config Surjection writes on this OS, able
336/// to run the transport), minus clients this machine excludes. In table
337/// order. Read-only; no store is fine.
338pub fn default_clients(
339    store: Option<&Store<'_>>,
340    ax: &ApplyEnv<'_>,
341    transport: Transport,
342) -> Result<Vec<String>, CoreError> {
343    let (desired, _ledger) = import::store_inputs(store, ax)?;
344    let memory = match store {
345        Some(store) => store.secret_memory().clone(),
346        None => Arc::new(SecretMemory::new()?),
347    };
348    Ok(default_clients_in(
349        &ax.render_cx(memory),
350        &desired,
351        transport,
352    ))
353}
354
355/// [`default_clients`] for a desired state already loaded.
356pub fn default_clients_in(
357    cx: &RenderCx<'_>,
358    desired: &DesiredState,
359    transport: Transport,
360) -> Vec<String> {
361    let mut detected = Detected::default();
362    let mut clients = detected.select(cx, desired, &ClientSelection::AllDetected, Some(transport));
363    clients.retain(|client| !desired.excluded(client));
364    clients
365}
366
367/// What a client entry must run to be the same server.
368#[derive(Debug, Clone, Copy)]
369pub enum Launch<'a> {
370    Url(&'a str),
371    Command(&'a str, &'a [String]),
372}
373
374/// A client entry Surjection does not manage that runs the same server.
375#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct ExistingEntry {
377    pub client: &'static str,
378    /// The entry's name in the client file.
379    pub name: String,
380    pub scope: Scope,
381    /// The project of a project file.
382    pub project_id: Option<String>,
383}
384
385/// The entries not managed by Surjection (the import scan of user files
386/// and known projects) that run `launch`: the same address (scheme and
387/// host case, a trailing `/` ignored), or the same program (its name, so
388/// `npx` and `C:\...\npx.cmd` match; `cmd /c` unwrapped) with the same
389/// arguments. Read-only.
390pub fn existing_entries(
391    store: Option<&Store<'_>>,
392    ax: &ApplyEnv<'_>,
393    launch: Launch<'_>,
394) -> Result<Vec<ExistingEntry>, CoreError> {
395    let (desired, ledger) = import::store_inputs(store, ax)?;
396    let filter = ScanFilter {
397        clients: None,
398        scope: ScanScope::All,
399    };
400    let (candidates, _warnings) = import::scan_with(ax, &desired, &ledger, &filter)?;
401    let wanted = launch_key(launch);
402    let mut found = Vec::new();
403    for candidate in &candidates {
404        for source in &candidate.sources {
405            let Ok(def) = &source.def else { continue };
406            let fields = &def.fields;
407            let key = match (&fields.url, &fields.command) {
408                (Some(url), _) => launch_key(Launch::Url(url)),
409                (None, Some(command)) => launch_key(Launch::Command(
410                    command,
411                    fields.args.as_deref().unwrap_or_default(),
412                )),
413                (None, None) => continue,
414            };
415            if key == wanted {
416                found.push(ExistingEntry {
417                    client: source.client,
418                    name: candidate.name.clone(),
419                    scope: source.scope,
420                    project_id: source.project.as_ref().map(|p| p.id.clone()),
421                });
422            }
423        }
424    }
425    Ok(found)
426}
427
428/// What two launches must share to be the same server.
429fn launch_key(launch: Launch<'_>) -> Vec<String> {
430    match launch {
431        Launch::Url(url) => {
432            let normalized = url::Url::parse(url.trim()).map_or_else(
433                |_| url.trim().to_owned(),
434                |parsed| parsed.as_str().to_owned(),
435            );
436            vec![normalized.trim_end_matches('/').to_owned()]
437        }
438        Launch::Command(command, args) => {
439            let mut program = suggest::program_name(command);
440            let mut args = args;
441            if program == "cmd"
442                && let Some(at) = args.iter().position(|arg| {
443                    arg.eq_ignore_ascii_case("/c") || arg.eq_ignore_ascii_case("/k")
444                })
445                && let Some((inner, rest)) = args[at + 1..].split_first()
446            {
447                program = suggest::program_name(inner);
448                args = rest;
449            }
450            std::iter::once(program)
451                .chain(args.iter().cloned())
452                .collect()
453        }
454    }
455}
456
457#[cfg(test)]
458mod tests;