surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
//! What a pasted or typed server is (#47, the Add dialog and `surject server
//! add <URL>` / `-- <COMMAND...>`): an address, a config snippet, a
//! command line, a repository or a folder; the transport an address
//! suggests; the clients a new server is enabled for by default; and the
//! entries client files already hold for the same address or command (the
//! dialog offers Import instead).
//!
//! Analysis reads no network and runs nothing; the folder check only asks
//! whether the path is a directory.

pub mod suggest;

use std::path::PathBuf;
use std::sync::Arc;

use crate::apply::ApplyEnv;
use crate::apply::import::{self, ScanFilter, ScanScope};
use crate::apply::render::{DesiredState, Detected, RenderCx};
use crate::env::Env;
use crate::error::CoreError;
use crate::fs::Fs;
use crate::mcp_source::snippet;
use crate::model::applied::Scope;
use crate::model::clients::ClientSelection;
use crate::model::server::Transport;
use crate::secrets::scanner::SecretMemory;
use crate::store::Store;

/// What the text is.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputKind {
    /// An `http(s)://` address of a remote server.
    Url,
    /// A client config snippet (JSON, JSONC, TOML, YAML) holding entries.
    Snippet,
    /// A command line that starts a local (stdio) server.
    Command,
    /// A git repository to find servers in.
    Repository,
    /// A local folder to find servers in.
    Folder,
    /// Nothing recognized (or empty).
    Unknown,
}

impl InputKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            InputKind::Url => "url",
            InputKind::Snippet => "snippet",
            InputKind::Command => "command",
            InputKind::Repository => "repository",
            InputKind::Folder => "folder",
            InputKind::Unknown => "unknown",
        }
    }
}

/// The result of [`analyze`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Analysis {
    pub kind: InputKind,
    /// [`InputKind::Url`]: the address as given (trimmed).
    pub url: Option<String>,
    /// [`InputKind::Url`]: from the path ([`transport_from_url`]);
    /// [`InputKind::Command`]: stdio.
    pub transport: Option<Transport>,
    /// [`InputKind::Command`]: the program and its arguments.
    pub command: Option<String>,
    pub args: Vec<String>,
    /// [`InputKind::Repository`]: the address to clone.
    pub repository: Option<String>,
    /// [`InputKind::Folder`]: the folder (`~` expanded).
    pub folder: Option<PathBuf>,
    /// [`InputKind::Snippet`]: how many entries it holds.
    pub snippet_entries: usize,
    /// [`InputKind::Url`] and [`InputKind::Command`]: the id it suggests
    /// ([`suggest::suggest`]), before it is made unique in the store.
    pub suggested_id: Option<String>,
    /// The detection result in English ("Remote server (Streamable HTTP)").
    pub message: String,
}

impl Analysis {
    fn new(kind: InputKind, message: impl Into<String>) -> Self {
        Self {
            kind,
            url: None,
            transport: None,
            command: None,
            args: Vec::new(),
            repository: None,
            folder: None,
            snippet_entries: 0,
            suggested_id: None,
            message: message.into(),
        }
    }
}

/// Hosts whose `/<owner>/<repo>` addresses are repositories, not servers.
const FORGES: [&str; 5] = [
    "github.com",
    "gitlab.com",
    "bitbucket.org",
    "codeberg.org",
    "git.sr.ht",
];

/// Programs that start a local server (the first word of a command line);
/// a path to a program counts too.
const RUNNERS: [&str; 22] = [
    "npx", "bunx", "uvx", "pipx", "node", "deno", "bun", "tsx", "uv", "python", "python3", "py",
    "docker", "podman", "pnpm", "yarn", "npm", "java", "dotnet", "go", "cmd", "pwsh",
];

/// Reads `text` (see the module docs). The order: an address (a
/// repository when it names one), a folder, a snippet, a command line.
pub fn analyze(text: &str, env: &Env, fs: &dyn Fs) -> Analysis {
    let text = text.trim();
    if text.is_empty() {
        return Analysis::new(
            InputKind::Unknown,
            "Paste a server URL, a config snippet or a command",
        );
    }
    let single_line = !text.contains(['\n', '\r']);
    if single_line && let Some(repository) = repository_url(text) {
        let mut analysis = Analysis::new(
            InputKind::Repository,
            "Looks like a repository: find servers in it",
        );
        analysis.repository = Some(repository);
        return analysis;
    }
    if single_line && is_http_url(text) {
        let transport = transport_from_url(text);
        let mut analysis = Analysis::new(
            InputKind::Url,
            match transport {
                Transport::Sse => "Remote server (SSE)",
                _ => "Remote server (Streamable HTTP)",
            },
        );
        analysis.url = Some(text.to_owned());
        analysis.transport = Some(transport);
        analysis.suggested_id = suggest::from_url(text);
        return analysis;
    }
    if single_line && let Some(folder) = folder_path(text, env, fs) {
        let mut analysis = Analysis::new(InputKind::Folder, "A folder: find servers in it");
        analysis.folder = Some(folder);
        return analysis;
    }
    if let Some(doc) = snippet::parse_any(text)
        && let Ok(entries) = snippet::entries(&doc, env.os(), None)
    {
        let count = entries.entries.len();
        let mut analysis = Analysis::new(
            InputKind::Snippet,
            if count == 1 {
                format!("Config snippet ({}): 1 server", entries.spec.display_name)
            } else {
                format!(
                    "Config snippet ({}): {count} servers",
                    entries.spec.display_name
                )
            },
        );
        analysis.snippet_entries = count;
        return analysis;
    }
    if single_line {
        let argv = program_path_with_args(text, fs).or_else(|| split_command(text));
        if let Some(argv) = argv.filter(|argv| looks_like_command(argv)) {
            let mut analysis = Analysis::new(InputKind::Command, "Local command (stdio)");
            analysis.suggested_id = suggest::from_command(&argv);
            analysis.transport = Some(Transport::Stdio);
            let mut argv = argv.into_iter();
            analysis.command = argv.next();
            analysis.args = argv.collect();
            return analysis;
        }
    }
    Analysis::new(
        InputKind::Unknown,
        "Not recognized: paste a server URL, a config snippet or a command",
    )
}

fn is_http_url(text: &str) -> bool {
    url::Url::parse(text)
        .is_ok_and(|url| matches!(url.scheme(), "http" | "https") && url.host().is_some())
}

/// `text` as a repository address: `git@host:owner/repo`, `ssh://` and
/// `git://` addresses, an address ending in `.git`, or
/// `https://<forge>/<owner>/<repo>[/tree/...]` on a known forge.
pub fn repository_url(text: &str) -> Option<String> {
    if text.contains(char::is_whitespace) {
        return None;
    }
    if (text.starts_with("git@") && text.contains(':'))
        || text.starts_with("ssh://")
        || text.starts_with("git://")
    {
        return Some(text.to_owned());
    }
    let url = url::Url::parse(text).ok()?;
    if !matches!(url.scheme(), "http" | "https") {
        return None;
    }
    if url.path().trim_end_matches('/').ends_with(".git") {
        return Some(text.to_owned());
    }
    let host = url.host_str()?.trim_start_matches("www.");
    let segments: Vec<&str> = url.path_segments()?.filter(|s| !s.is_empty()).collect();
    // A forge's own endpoints (`gitlab.com/api/v4/mcp`) are servers.
    let endpoint = segments
        .first()
        .is_some_and(|first| first.eq_ignore_ascii_case("api"))
        || segments
            .last()
            .is_some_and(|last| matches!(last.to_ascii_lowercase().as_str(), "mcp" | "sse"));
    (FORGES.contains(&host) && segments.len() >= 2 && !endpoint).then(|| text.to_owned())
}

/// An unquoted absolute program path with spaces (`C:\Program
/// Files\nodejs\npx.cmd -y pkg`): the longest run of leading words that
/// names an existing file is the program, the other words its arguments
/// (split as [`split_command`] does). `None` when no such file exists or
/// the text does not start with an absolute path.
fn program_path_with_args(text: &str, fs: &dyn Fs) -> Option<Vec<String>> {
    let text = text.trim();
    if text.starts_with(['"', '\'']) || !std::path::Path::new(text).has_root() {
        return None;
    }
    let words: Vec<&str> = text.split_whitespace().collect();
    (1..=words.len()).rev().find_map(|n| {
        let program = words[..n].join(" ");
        let path = std::path::Path::new(&program);
        if !path.is_absolute() || !fs.is_regular_file(path) {
            return None;
        }
        let rest = words[n..].join(" ");
        let mut argv = vec![program];
        argv.extend(split_command(&rest).unwrap_or_default());
        Some(argv)
    })
}

/// `text` as an existing folder: an absolute path, or one under `~`.
fn folder_path(text: &str, env: &Env, fs: &dyn Fs) -> Option<PathBuf> {
    let text = text.trim_matches('"');
    let path = match text.strip_prefix("~/").or_else(|| text.strip_prefix("~\\")) {
        Some(rest) => env.home().join(rest),
        None if text == "~" => env.home().to_path_buf(),
        None => PathBuf::from(text),
    };
    let absolute = path.is_absolute() || path.has_root();
    (absolute && fs.is_dir(&path)).then_some(path)
}

/// The transport an address suggests: `sse` when its path ends in `/sse`,
/// else Streamable HTTP.
pub fn transport_from_url(url: &str) -> Transport {
    let path = url::Url::parse(url)
        .ok()
        .map(|url| url.path().trim_end_matches('/').to_ascii_lowercase());
    match path {
        Some(path) if path.ends_with("/sse") => Transport::Sse,
        _ => Transport::Http,
    }
}

/// A one-line command as words: whitespace separates, `"..."` and `'...'`
/// group (quotes removed). A backslash is an ordinary character, so
/// Windows paths stay whole. A leading `$ ` or `> ` prompt is dropped.
/// `None` for empty text or an unclosed quote.
pub fn split_command(text: &str) -> Option<Vec<String>> {
    let text = text.trim();
    let text = text
        .strip_prefix("$ ")
        .or_else(|| text.strip_prefix("> "))
        .unwrap_or(text);
    let mut words = Vec::new();
    let mut word = String::new();
    let mut in_word = false;
    let mut quote: Option<char> = None;
    for c in text.chars() {
        match quote {
            Some(q) if c == q => quote = None,
            Some(_) => word.push(c),
            None if c == '"' || c == '\'' => {
                quote = Some(c);
                in_word = true;
            }
            None if c.is_whitespace() => {
                if in_word {
                    words.push(std::mem::take(&mut word));
                    in_word = false;
                }
            }
            None => {
                word.push(c);
                in_word = true;
            }
        }
    }
    if quote.is_some() {
        return None;
    }
    if in_word {
        words.push(word);
    }
    (!words.is_empty()).then_some(words)
}

/// Whether `argv` starts a local server: its program is a known runner
/// ([`RUNNERS`]) or a path to a program.
pub fn looks_like_command(argv: &[String]) -> bool {
    let Some(command) = argv.first() else {
        return false;
    };
    let program = suggest::program_name(command);
    let is_path = command.contains(['/', '\\'])
        || [".exe", ".cmd", ".bat", ".js", ".mjs", ".py", ".sh"]
            .iter()
            .any(|ext| command.to_ascii_lowercase().ends_with(ext));
    !command.contains("://") && (is_path || RUNNERS.contains(&program.as_str()))
}

/// The clients a new server with `transport` is enabled for by default:
/// the ones `all-detected` selects here (detected or forced on in
/// `clients.toml`, with an MCP config Surjection writes on this OS, able
/// to run the transport), minus clients this machine excludes. In table
/// order. Read-only; no store is fine.
pub fn default_clients(
    store: Option<&Store<'_>>,
    ax: &ApplyEnv<'_>,
    transport: Transport,
) -> Result<Vec<String>, CoreError> {
    let (desired, _ledger) = import::store_inputs(store, ax)?;
    let memory = match store {
        Some(store) => store.secret_memory().clone(),
        None => Arc::new(SecretMemory::new()?),
    };
    Ok(default_clients_in(
        &ax.render_cx(memory),
        &desired,
        transport,
    ))
}

/// [`default_clients`] for a desired state already loaded.
pub fn default_clients_in(
    cx: &RenderCx<'_>,
    desired: &DesiredState,
    transport: Transport,
) -> Vec<String> {
    let mut detected = Detected::default();
    let mut clients = detected.select(cx, desired, &ClientSelection::AllDetected, Some(transport));
    clients.retain(|client| !desired.excluded(client));
    clients
}

/// What a client entry must run to be the same server.
#[derive(Debug, Clone, Copy)]
pub enum Launch<'a> {
    Url(&'a str),
    Command(&'a str, &'a [String]),
}

/// A client entry Surjection does not manage that runs the same server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExistingEntry {
    pub client: &'static str,
    /// The entry's name in the client file.
    pub name: String,
    pub scope: Scope,
    /// The project of a project file.
    pub project_id: Option<String>,
}

/// The entries not managed by Surjection (the import scan of user files
/// and known projects) that run `launch`: the same address (scheme and
/// host case, a trailing `/` ignored), or the same program (its name, so
/// `npx` and `C:\...\npx.cmd` match; `cmd /c` unwrapped) with the same
/// arguments. Read-only.
pub fn existing_entries(
    store: Option<&Store<'_>>,
    ax: &ApplyEnv<'_>,
    launch: Launch<'_>,
) -> Result<Vec<ExistingEntry>, CoreError> {
    let (desired, ledger) = import::store_inputs(store, ax)?;
    let filter = ScanFilter {
        clients: None,
        scope: ScanScope::All,
    };
    let (candidates, _warnings) = import::scan_with(ax, &desired, &ledger, &filter)?;
    let wanted = launch_key(launch);
    let mut found = Vec::new();
    for candidate in &candidates {
        for source in &candidate.sources {
            let Ok(def) = &source.def else { continue };
            let fields = &def.fields;
            let key = match (&fields.url, &fields.command) {
                (Some(url), _) => launch_key(Launch::Url(url)),
                (None, Some(command)) => launch_key(Launch::Command(
                    command,
                    fields.args.as_deref().unwrap_or_default(),
                )),
                (None, None) => continue,
            };
            if key == wanted {
                found.push(ExistingEntry {
                    client: source.client,
                    name: candidate.name.clone(),
                    scope: source.scope,
                    project_id: source.project.as_ref().map(|p| p.id.clone()),
                });
            }
        }
    }
    Ok(found)
}

/// What two launches must share to be the same server.
fn launch_key(launch: Launch<'_>) -> Vec<String> {
    match launch {
        Launch::Url(url) => {
            let normalized = url::Url::parse(url.trim()).map_or_else(
                |_| url.trim().to_owned(),
                |parsed| parsed.as_str().to_owned(),
            );
            vec![normalized.trim_end_matches('/').to_owned()]
        }
        Launch::Command(command, args) => {
            let mut program = suggest::program_name(command);
            let mut args = 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 = suggest::program_name(inner);
                args = rest;
            }
            std::iter::once(program)
                .chain(args.iter().cloned())
                .collect()
        }
    }
}

#[cfg(test)]
mod tests;