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;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputKind {
Url,
Snippet,
Command,
Repository,
Folder,
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",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Analysis {
pub kind: InputKind,
pub url: Option<String>,
pub transport: Option<Transport>,
pub command: Option<String>,
pub args: Vec<String>,
pub repository: Option<String>,
pub folder: Option<PathBuf>,
pub snippet_entries: usize,
pub suggested_id: Option<String>,
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(),
}
}
}
const FORGES: [&str; 5] = [
"github.com",
"gitlab.com",
"bitbucket.org",
"codeberg.org",
"git.sr.ht",
];
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",
];
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())
}
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();
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())
}
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)
})
}
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)
}
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,
}
}
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)
}
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()))
}
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,
))
}
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
}
#[derive(Debug, Clone, Copy)]
pub enum Launch<'a> {
Url(&'a str),
Command(&'a str, &'a [String]),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ExistingEntry {
pub client: &'static str,
pub name: String,
pub scope: Scope,
pub project_id: Option<String>,
}
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)
}
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;