1pub 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub enum InputKind {
32 Url,
34 Snippet,
36 Command,
38 Repository,
40 Folder,
42 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#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct Analysis {
62 pub kind: InputKind,
63 pub url: Option<String>,
65 pub transport: Option<Transport>,
68 pub command: Option<String>,
70 pub args: Vec<String>,
71 pub repository: Option<String>,
73 pub folder: Option<PathBuf>,
75 pub snippet_entries: usize,
77 pub suggested_id: Option<String>,
80 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
101const FORGES: [&str; 5] = [
103 "github.com",
104 "gitlab.com",
105 "bitbucket.org",
106 "codeberg.org",
107 "git.sr.ht",
108];
109
110const 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
117pub 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
196pub 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 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
228fn 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
252fn 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
264pub 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
276pub 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
319pub 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
333pub 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
355pub 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#[derive(Debug, Clone, Copy)]
369pub enum Launch<'a> {
370 Url(&'a str),
371 Command(&'a str, &'a [String]),
372}
373
374#[derive(Debug, Clone, PartialEq, Eq)]
376pub struct ExistingEntry {
377 pub client: &'static str,
378 pub name: String,
380 pub scope: Scope,
381 pub project_id: Option<String>,
383}
384
385pub 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
428fn 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;