diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index 05e1d66c72..a8351228ab 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -19,6 +19,7 @@ mod external; pub mod hermes; mod images; pub mod mcp; +pub mod mcp_registry; pub mod memory; mod model; mod native; @@ -36,6 +37,10 @@ pub use automation::*; pub use catalogs::AgentCatalogs; pub use cli_update::{AgentCliInstallResult, AgentCliOffer, AgentCliUpdateResult}; pub use external::ExternalSession; +pub use mcp_registry::{ + DEFAULT_MCP_REGISTRY_URL, McpRegistryInputField, McpRegistryInputKind, McpRegistryInstallOption, McpRegistryPage, + McpRegistryServer, OFFICIAL_MCP_REGISTRY_URL, +}; pub use model::*; pub use provider::{LoginLaunch, gh_authenticated_accounts, gh_login_launch}; pub use skill_installer::{ diff --git a/crates/ide-agent/src/mcp.rs b/crates/ide-agent/src/mcp.rs index d0fe0edee5..c5a514b9bc 100644 --- a/crates/ide-agent/src/mcp.rs +++ b/crates/ide-agent/src/mcp.rs @@ -70,6 +70,8 @@ fn to_mcp_server(scope: McpScope, name: &str, cfg: &AgentMcpServer) -> McpServer unapproved: false, plugin_id: None, plugin_name: None, + registry_name: cfg.registry_name.clone(), + registry_url: cfg.registry_url.clone(), } } @@ -254,6 +256,28 @@ pub fn apply_save( if input.scope == McpScope::Workspace && !has_workspace { return Err("Open a project to configure workspace MCP servers".into()); } + let existing_meta = input.id.as_deref().and_then(parse_server_id).and_then(|(prev_scope, prev_name)| { + let map = match prev_scope { + McpScope::User => &*user, + McpScope::Workspace => &*workspace, + }; + map.get(prev_name).map(|prev| (prev.registry_name.clone(), prev.registry_url.clone())) + }); + let registry_name = input + .registry_name + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .or_else(|| existing_meta.as_ref().and_then(|(rn, _)| rn.clone())); + let registry_url = input + .registry_url + .as_deref() + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .or_else(|| existing_meta.and_then(|(_, ru)| ru)); + let cfg = match input.transport { McpTransport::Stdio => { let cmd = input.command.as_deref().map(str::trim).unwrap_or_default(); @@ -277,6 +301,8 @@ pub fn apply_save( url: None, headers: BTreeMap::new(), agents: normalize_agents_list(input.agents), + registry_name, + registry_url, } } McpTransport::Http | McpTransport::Sse => { @@ -301,6 +327,8 @@ pub fn apply_save( url: Some(url.to_owned()), headers, agents: normalize_agents_list(input.agents), + registry_name, + registry_url, } } }; @@ -1018,6 +1046,8 @@ fn parse_one_server_def(obj: &serde_json::Map) -> Option, + pub required: bool, + pub secret: bool, + pub default_value: Option, + pub placeholder: Option, + pub choices: Vec, + /// Target HTTP header name when `kind == Header`. + pub header_name: Option, + /// Target CLI flag (e.g. `--dir`) when `kind == Arg` and the argument is appended dynamically. + pub flag: Option, + /// Literal placeholder token (e.g. `{region}`) to substitute in `url`, `headers`, or `args`. + pub template_token: Option, +} + +/// One concrete way to install and launch an MCP registry server (either a local package or a remote URL). +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct McpRegistryInstallOption { + pub id: String, + /// Human-readable option label (e.g. `npm (npx)`, `PyPI (uvx)`, `Docker`, `Streamable HTTP`). + pub label: String, + pub transport: McpTransport, + /// Underlying registry type (`npm`, `pypi`, `oci`, `nuget`, `streamable-http`, `sse`). + pub registry_type: String, + pub package_identifier: Option, + pub command: Option, + pub args: Vec, + pub url: Option, + /// Pre-populated or templated HTTP headers (e.g. `Authorization: Bearer {TOKEN}`). + pub headers: Vec, + /// Declared env vars, header tokens, URL variables, and CLI arguments. + pub inputs: Vec, + /// Whether the required local runtime binary (`npx`, `uvx`, `docker`, `dnx`…) is available on `PATH`. + /// Always `true` for remote HTTP/SSE endpoints. + pub runtime_available: bool, +} + +/// One MCP server returned by an MCP registry search or listing. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct McpRegistryServer { + /// Canonical registry server identifier (e.g. `microsoft/playwright-mcp`). + pub name: String, + /// Human-friendly display title. + pub display_name: String, + /// Sanitized local configuration key suggestion (e.g. `playwright-mcp`). + pub suggested_name: String, + pub description: String, + pub version: String, + pub publisher: Option, + pub icon_url: Option, + pub icon_dark_url: Option, + pub repository_url: Option, + pub website_url: Option, + pub license: Option, + pub stars: Option, + pub install_options: Vec, +} + +/// Paginated response returned to Settings › Agents › MCP Connections › Browse. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Type)] +#[serde(rename_all = "camelCase")] +pub struct McpRegistryPage { + pub registry_url: String, + pub servers: Vec, + pub next_cursor: Option, + pub total: Option, +} + +/// Abstraction over HTTP GET requests for deterministic unit tests. +pub trait McpRegistryFetcher: Send + Sync { + fn get_json(&self, url: &str, max_bytes: u64, cancel: &CancellationToken) -> IdeResult; +} + +/// Live HTTP fetcher backed by [`ide_tools::Http`] (`curl` with IDE proxy settings, no GitHub auth). +pub struct HttpMcpRegistryFetcher { + https_http: Http, + loopback_http: Http, +} + +impl HttpMcpRegistryFetcher { + pub fn new(search_path: &OsStr) -> IdeResult { + let https_http = + Http::new(search_path)?.https_only().without_github_auth().accept("application/json").compressed(); + let loopback_http = Http::new(search_path)?.without_github_auth().accept("application/json").compressed(); + Ok(Self { https_http, loopback_http }) + } +} + +impl McpRegistryFetcher for HttpMcpRegistryFetcher { + fn get_json(&self, url: &str, max_bytes: u64, cancel: &CancellationToken) -> IdeResult { + let client = if url.starts_with("https://") { &self.https_http } else { &self.loopback_http }; + client.get_text_limited(url, Some(max_bytes), cancel) + } +} + +/// Normalizes and validates an MCP Registry base URL. +/// +/// Empty / `None` defaults to [`DEFAULT_MCP_REGISTRY_URL`]. Accepts `https://` URLs and +/// loopback `http://localhost` / `http://127.0.0.1` / `http://[::1]` URLs for local dev +/// registries, rejecting embedded credentials, queries, fragments, and whitespace. +pub fn normalize_registry_url(raw: Option<&str>) -> IdeResult { + let trimmed = raw.map(str::trim).filter(|s| !s.is_empty()).unwrap_or(DEFAULT_MCP_REGISTRY_URL); + if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) { + return Err(IdeError::invalid("MCP registry URL must not contain whitespace")); + } + if trimmed.contains('?') || trimmed.contains('#') { + return Err(IdeError::invalid("MCP registry URL must not contain query parameters or fragments")); + } + + let (scheme, rest) = if let Some(rest) = trimmed.strip_prefix("https://") { + ("https://", rest) + } else if let Some(rest) = trimmed.strip_prefix("http://") { + ("http://", rest) + } else { + return Err(IdeError::invalid("MCP registry URL must start with https:// (or http://localhost for local dev)")); + }; + + let authority = rest.split('/').next().unwrap_or_default(); + if authority.is_empty() || authority.contains('@') { + return Err(IdeError::invalid("MCP registry URL has an invalid host")); + } + if scheme == "http://" && !is_loopback_authority(authority) { + return Err(IdeError::invalid("Only https:// MCP registries are allowed (except http://localhost)")); + } + + let mut normalized = format!("{scheme}{}", rest.trim_end_matches('/')); + for suffix in ["/v0.1/servers", "/v0/servers", "/v0.1", "/v0"] { + if let Some(stripped) = normalized.strip_suffix(suffix) + && stripped.len() > scheme.len() + { + normalized = stripped.to_owned(); + break; + } + } + Ok(normalized) +} + +fn is_loopback_authority(authority: &str) -> bool { + let host = if let Some(bracketed) = authority.strip_prefix('[') { + bracketed.split(']').next().unwrap_or_default() + } else { + authority.split(':').next().unwrap_or_default() + }; + host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "::1" +} + +fn percent_encode_query(value: &str) -> String { + let mut out = String::with_capacity(value.len()); + for byte in value.bytes() { + let unreserved = byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~'); + if unreserved { + out.push(byte as char); + } else { + out.push('%'); + out.push(hex_digit(byte >> 4)); + out.push(hex_digit(byte & 0x0f)); + } + } + out +} + +fn hex_digit(nibble: u8) -> char { + match nibble { + 0..=9 => (b'0' + nibble) as char, + _ => (b'A' + (nibble - 10)) as char, + } +} + +fn build_servers_url(base_url: &str, version: &str, query: Option<&str>, cursor: Option<&str>, limit: u32) -> String { + let limit = limit.clamp(1, MAX_PAGE_LIMIT); + let mut url = format!("{base_url}/{version}/servers?limit={limit}&version=latest"); + if let Some(q) = query.map(str::trim).filter(|s| !s.is_empty()) { + url.push_str("&search="); + url.push_str(&percent_encode_query(q)); + } + if let Some(c) = cursor.map(str::trim).filter(|s| !s.is_empty()) { + url.push_str("&cursor="); + url.push_str(&percent_encode_query(c)); + } + url +} + +/// Searches or lists MCP servers from `registry_url` (or [`DEFAULT_MCP_REGISTRY_URL`] when empty). +pub fn search_registry( + fetcher: &dyn McpRegistryFetcher, + registry_url: Option<&str>, + query: Option<&str>, + cursor: Option<&str>, + limit: Option, + search_path: &OsStr, + cancel: &CancellationToken, +) -> IdeResult { + let base_url = normalize_registry_url(registry_url)?; + let page_limit = limit.unwrap_or(DEFAULT_PAGE_LIMIT).clamp(1, MAX_PAGE_LIMIT); + let primary_url = build_servers_url(&base_url, "v0.1", query, cursor, page_limit); + + let body = match fetcher.get_json(&primary_url, MAX_REGISTRY_PAGE_BYTES, cancel) { + Ok(text) => text, + Err(err) if !cancel.is_cancelled() && cursor.is_none() && err.message.contains("404") => { + let fallback_url = build_servers_url(&base_url, "v0", query, cursor, page_limit); + fetcher.get_json(&fallback_url, MAX_REGISTRY_PAGE_BYTES, cancel)? + } + Err(err) => return Err(err), + }; + + parse_registry_page(&base_url, &body, |cmd| ide_core::process::find_executable(cmd, search_path).is_some()) +} + +/// Parses an MCP Registry `v0.1` or `v0` JSON response into [`McpRegistryPage`]. +pub(crate) fn parse_registry_page(registry_url: &str, body: &str, has_runtime: F) -> IdeResult +where + F: Fn(&str) -> bool, +{ + let root: Value = serde_json::from_str(body) + .map_err(|e| IdeError::new(ErrorKind::InvalidInput, format!("Invalid MCP registry JSON: {e}")))?; + + let raw_servers = root + .get("servers") + .and_then(Value::as_array) + .ok_or_else(|| IdeError::new(ErrorKind::InvalidInput, "MCP registry response is missing `servers` array"))?; + + let mut seen = HashSet::new(); + let mut servers = Vec::with_capacity(raw_servers.len()); + for entry in raw_servers { + if let Some(parsed) = parse_server_entry(entry, &has_runtime) + && seen.insert(parsed.name.clone()) + { + servers.push(parsed); + } + } + + let metadata = root.get("metadata").and_then(Value::as_object); + let next_cursor = metadata + .and_then(|m| m.get("nextCursor").or_else(|| m.get("next_cursor"))) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let total = metadata.and_then(|m| m.get("total")).and_then(Value::as_u64); + + Ok(McpRegistryPage { registry_url: registry_url.to_owned(), servers, next_cursor, total }) +} + +fn parse_server_entry(entry: &Value, has_runtime: &F) -> Option +where + F: Fn(&str) -> bool, +{ + let server = entry.get("server").filter(|v| v.is_object()).unwrap_or(entry); + let obj = server.as_object()?; + let name = obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty())?.to_owned(); + + let gh_meta = extract_github_meta(server).or_else(|| extract_github_meta(entry)); + let display_name = obj + .get("title") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .or_else(|| { + gh_meta.and_then(|m| m.get("displayName")).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) + }) + .map(str::to_owned) + .unwrap_or_else(|| fallback_display_name(&name)); + + let description = obj.get("description").and_then(Value::as_str).map(str::trim).unwrap_or_default().to_owned(); + let version = obj.get("version").and_then(Value::as_str).map(str::trim).unwrap_or_default().to_owned(); + + let repository_url = + obj.get("repository").and_then(|r| r.get("url").or(Some(r))).and_then(Value::as_str).and_then(safe_http_url); + let website_url = + obj.get("websiteUrl").or_else(|| obj.get("website_url")).and_then(Value::as_str).and_then(safe_http_url); + let license = gh_meta + .and_then(|m| m.get("license")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned); + let stars = gh_meta.and_then(|m| m.get("stargazerCount").or_else(|| m.get("stars"))).and_then(Value::as_u64); + let publisher = gh_meta + .and_then(|m| m.get("nameWithOwner")) + .and_then(Value::as_str) + .and_then(|s| s.split('/').next()) + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_owned) + .or_else(|| publisher_from_name(&name)); + let (icon_url, icon_dark_url) = extract_icons(server, entry, gh_meta, repository_url.as_deref(), &name); + + let mut install_options = Vec::new(); + if let Some(packages) = obj.get("packages").and_then(Value::as_array) { + for (idx, pkg) in packages.iter().enumerate() { + if let Some(opt) = parse_package_option(idx, pkg, has_runtime) { + install_options.push(opt); + } + } + } + if let Some(remotes) = obj.get("remotes").and_then(Value::as_array) { + for (idx, remote) in remotes.iter().enumerate() { + if let Some(opt) = parse_remote_option(idx, remote) { + install_options.push(opt); + } + } + } + + let suggested_name = derive_suggested_name(&name, &display_name); + + Some(McpRegistryServer { + name, + display_name, + suggested_name, + description, + version, + publisher, + icon_url, + icon_dark_url, + repository_url, + website_url, + license, + stars, + install_options, + }) +} + +fn extract_github_meta(node: &Value) -> Option<&serde_json::Map> { + node.get("_meta") + .and_then(|m| m.get("io.modelcontextprotocol.registry/publisher-provided")) + .and_then(|p| p.get("github")) + .and_then(Value::as_object) +} + +fn extract_icons( + server: &Value, + entry: &Value, + gh_meta: Option<&serde_json::Map>, + repository_url: Option<&str>, + canonical_name: &str, +) -> (Option, Option) { + // 1. Standard MCP Registry v0.1 `icons` array (supports separate light/dark variants). + if let Some(icons) = server.get("icons").and_then(Value::as_array) { + let mut light: Option = None; + let mut dark: Option = None; + let mut unthemed: Option = None; + let mut first: Option = None; + for item in icons { + let Some(obj) = item.as_object() else { continue }; + let Some(src) = obj.get("src").and_then(Value::as_str).and_then(safe_icon_url) else { + continue; + }; + if first.is_none() { + first = Some(src.clone()); + } + match obj.get("theme").and_then(Value::as_str).map(|s| s.trim().to_ascii_lowercase()).as_deref() { + Some("light") if light.is_none() => light = Some(src), + Some("dark") if dark.is_none() => dark = Some(src), + None | Some("") if unthemed.is_none() => unthemed = Some(src), + _ => {} + } + } + let resolved_light = light.or_else(|| unthemed.clone()).or(first); + if let Some(l) = resolved_light { + let resolved_dark = dark.or(unthemed).filter(|d| d != &l); + return (Some(l), resolved_dark); + } + } + + // 2. GitHub MCP Registry publisher metadata (`preferredImage` / `ownerAvatarUrl`). + if let Some(meta) = gh_meta { + for key in ["preferredImage", "preferred_image", "ownerAvatarUrl", "owner_avatar_url"] { + if let Some(url) = meta.get(key).and_then(Value::as_str).and_then(safe_icon_url) { + return (Some(url), None); + } + } + } + + // 3. Enterprise Azure API Center `x-ms-icon` metadata. + for node in [server, entry] { + if let Some(pp) = node.get("_meta").and_then(|m| m.get("io.modelcontextprotocol.registry/publisher-provided")) { + let apic = pp.get("apic").or(Some(pp)); + if let Some(url) = apic.and_then(|a| a.get("x-ms-icon")).and_then(Value::as_str).and_then(safe_icon_url) { + return (Some(url), None); + } + } + } + + // 4. GitHub repository owner avatar fallback (or `io.github./...` namespace). + if let Some(owner) = github_owner_from_repo(repository_url).or_else(|| github_owner_from_name(canonical_name)) { + return (Some(format!("https://github.com/{owner}.png?size=64")), None); + } + + (None, None) +} + +fn safe_icon_url(raw: &str) -> Option { + let trimmed = raw.trim(); + let rest = trimmed.strip_prefix("https://")?; + if trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) { + return None; + } + let authority = rest.split('/').next().unwrap_or_default(); + if authority.is_empty() || authority.contains('@') { + return None; + } + Some(trimmed.to_owned()) +} + +fn is_valid_github_owner(owner: &str) -> bool { + !owner.is_empty() + && owner.len() <= 39 + && owner.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-') + && !owner.starts_with('-') + && !owner.ends_with('-') +} + +fn github_owner_from_repo(repo_url: Option<&str>) -> Option<&str> { + let url = repo_url?.trim(); + let rest = url + .strip_prefix("https://github.com/") + .or_else(|| url.strip_prefix("http://github.com/")) + .or_else(|| url.strip_prefix("https://www.github.com/"))?; + let owner = rest.split('/').next()?; + is_valid_github_owner(owner).then_some(owner) +} + +fn github_owner_from_name(canonical_name: &str) -> Option<&str> { + let (prefix, _) = canonical_name.split_once('/')?; + let owner = prefix.strip_prefix("io.github.")?; + is_valid_github_owner(owner).then_some(owner) +} + +fn safe_http_url(raw: &str) -> Option { + let trimmed = raw.trim(); + if (trimmed.starts_with("https://") || trimmed.starts_with("http://")) + && !trimmed.chars().any(|c| c.is_whitespace() || c.is_control()) + { + Some(trimmed.to_owned()) + } else { + None + } +} + +fn publisher_from_name(name: &str) -> Option { + let (prefix, _) = name.split_once('/')?; + let trimmed = prefix.trim(); + if trimmed.is_empty() { + return None; + } + if let Some(owner) = trimmed.strip_prefix("io.github.") + && !owner.is_empty() + { + return Some(owner.to_owned()); + } + Some(trimmed.to_owned()) +} + +fn fallback_display_name(name: &str) -> String { + let tail = name.rsplit('/').next().unwrap_or(name).trim(); + if tail.is_empty() { name.to_owned() } else { tail.to_owned() } +} + +/// Derives a clean local `settings.toml` key from a canonical registry name such as +/// `microsoft/playwright-mcp` → `playwright-mcp` or `io.github.netdata/mcp-server` → `netdata`. +pub(crate) fn derive_suggested_name(canonical: &str, display_name: &str) -> String { + let (prefix, tail) = canonical.split_once('/').unwrap_or(("", canonical)); + let generic_tail = matches!(tail.to_ascii_lowercase().as_str(), "mcp" | "mcp-server" | "server"); + let raw = if generic_tail && !display_name.trim().is_empty() { + display_name.trim() + } else if generic_tail && !prefix.is_empty() { + prefix.rsplit('.').next().unwrap_or(prefix) + } else { + tail + }; + let mut slug = String::with_capacity(raw.len()); + let mut prev_dash = false; + for ch in raw.chars() { + if ch.is_ascii_alphanumeric() || ch == '_' || ch == '-' { + slug.push(ch.to_ascii_lowercase()); + prev_dash = ch == '-'; + } else if !slug.is_empty() && !prev_dash { + slug.push('-'); + prev_dash = true; + } + } + let slug = slug.trim_matches('-').to_owned(); + if slug.is_empty() { "mcp-server".into() } else { slug } +} + +fn parse_package_option(idx: usize, pkg: &Value, has_runtime: &F) -> Option +where + F: Fn(&str) -> bool, +{ + let obj = pkg.as_object()?; + let transport_type = + obj.get("transport").and_then(|t| t.get("type").or(Some(t))).and_then(Value::as_str).unwrap_or("stdio"); + if !transport_type.eq_ignore_ascii_case("stdio") { + return None; + } + + let registry_type = obj + .get("registryType") + .or_else(|| obj.get("registry_type")) + .or_else(|| obj.get("registry_name")) + .and_then(Value::as_str) + .map(|s| s.trim().to_ascii_lowercase()) + .unwrap_or_default(); + let identifier = obj.get("identifier").or_else(|| obj.get("name")).and_then(Value::as_str)?.trim(); + if identifier.is_empty() { + return None; + } + let version = obj.get("version").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()); + let runtime_hint = obj + .get("runtimeHint") + .or_else(|| obj.get("runtime_hint")) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()); + + let (command, label, pkg_spec) = match registry_type.as_str() { + "npm" => { + let cmd = allowlisted_hint(runtime_hint, &["npx", "pnpx", "bunx", "npm", "node"]).unwrap_or("npx"); + let spec = format_npm_spec(identifier, version); + (cmd.to_owned(), format!("npm ({cmd})"), spec) + } + "pypi" => { + let cmd = allowlisted_hint(runtime_hint, &["uvx", "pipx", "python", "python3"]).unwrap_or("uvx"); + let spec = format_pypi_spec(identifier, version); + (cmd.to_owned(), format!("PyPI ({cmd})"), spec) + } + "oci" | "docker" => { + let cmd = allowlisted_hint(runtime_hint, &["docker", "podman"]).unwrap_or("docker"); + let spec = format_oci_spec(identifier, version); + (cmd.to_owned(), format!("Docker ({cmd})"), spec) + } + "nuget" => { + let cmd = allowlisted_hint(runtime_hint, &["dnx", "dotnet"]).unwrap_or("dnx"); + let spec = format_nuget_spec(identifier, version); + (cmd.to_owned(), format!("NuGet ({cmd})"), spec) + } + _ => return None, + }; + + let mut args = Vec::new(); + let mut inputs = Vec::new(); + let mut seen_keys = HashSet::new(); + + if registry_type == "oci" || registry_type == "docker" { + args.extend(["run".into(), "-i".into(), "--rm".into()]); + } + + let mut runtime_args = Vec::new(); + if let Some(raw_runtime) = + obj.get("runtimeArguments").or_else(|| obj.get("runtime_arguments")).and_then(Value::as_array) + { + parse_arguments(raw_runtime, &mut runtime_args, &mut inputs, &mut seen_keys, "rtarg"); + } + + if command == "npx" && !runtime_args.iter().any(|a| a == "-y" || a == "--yes") { + args.push("-y".into()); + } + if command == "dnx" && !runtime_args.iter().any(|a| a == "-y" || a == "--yes") { + args.push("-y".into()); + } + args.extend(runtime_args); + + // Environment variables declared by the package. + let mut env_names_for_docker = Vec::new(); + if let Some(env_vars) = + obj.get("environmentVariables").or_else(|| obj.get("environment_variables")).and_then(Value::as_array) + { + for raw_env in env_vars { + let Some(env_obj) = raw_env.as_object() else { continue }; + let Some(var_name) = env_obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) + else { + continue; + }; + env_names_for_docker.push(var_name.to_owned()); + let key = format!("env:{var_name}"); + if seen_keys.insert(key.clone()) { + inputs.push(McpRegistryInputField { + key, + label: var_name.to_owned(), + kind: McpRegistryInputKind::Env, + description: opt_string(env_obj.get("description")), + required: bool_field(env_obj, "isRequired", "is_required"), + secret: bool_field(env_obj, "isSecret", "is_secret"), + default_value: opt_string(env_obj.get("default")), + placeholder: opt_string(env_obj.get("placeholder")), + choices: string_array(env_obj.get("choices")), + header_name: None, + flag: None, + template_token: None, + }); + } + } + } + + // For Docker / OCI containers, forward declared env vars via `-e NAME` without placing secret values on the CLI. + if registry_type == "oci" || registry_type == "docker" { + for var_name in &env_names_for_docker { + let already_passed = args.windows(2).any(|w| (w[0] == "-e" || w[0] == "--env") && w[1] == *var_name); + if !already_passed { + args.push("-e".into()); + args.push(var_name.clone()); + } + } + } + + args.push(pkg_spec); + + if let Some(raw_pkg_args) = + obj.get("packageArguments").or_else(|| obj.get("package_arguments")).and_then(Value::as_array) + { + parse_arguments(raw_pkg_args, &mut args, &mut inputs, &mut seen_keys, "arg"); + } + + let runtime_available = has_runtime(&command); + + Some(McpRegistryInstallOption { + id: format!("pkg:{idx}"), + label, + transport: McpTransport::Stdio, + registry_type, + package_identifier: Some(identifier.to_owned()), + command: Some(command), + args, + url: None, + headers: Vec::new(), + inputs, + runtime_available, + }) +} + +fn parse_remote_option(idx: usize, remote: &Value) -> Option { + let obj = remote.as_object()?; + let raw_type = obj.get("type").or_else(|| obj.get("transport_type")).and_then(Value::as_str)?.trim(); + let (transport, label, registry_type) = match raw_type.to_ascii_lowercase().as_str() { + "streamable-http" | "http" => (McpTransport::Http, "Streamable HTTP".to_owned(), "streamable-http".to_owned()), + "sse" => (McpTransport::Sse, "SSE".to_owned(), "sse".to_owned()), + _ => return None, + }; + + let url = obj.get("url").and_then(Value::as_str).and_then(safe_http_url)?; + let mut inputs = Vec::new(); + let mut seen_keys = HashSet::new(); + + // URL template variables (e.g. `https://{region}.mcp.example.com/{workspaceId}/mcp`). + let url_vars = parse_variables_map(obj.get("variables")); + for var_name in extract_template_vars(&url) { + let meta = url_vars.get(&var_name); + let key = format!("url:{var_name}"); + if seen_keys.insert(key.clone()) { + inputs.push(McpRegistryInputField { + key, + label: var_name.clone(), + kind: McpRegistryInputKind::UrlVar, + description: meta.and_then(|m| m.description.clone()), + required: meta.and_then(|m| m.required).unwrap_or(true), + secret: meta.and_then(|m| m.secret).unwrap_or(false), + default_value: meta.and_then(|m| m.default_value.clone()), + placeholder: meta.and_then(|m| m.placeholder.clone()), + choices: meta.map(|m| m.choices.clone()).unwrap_or_default(), + header_name: None, + flag: None, + template_token: Some(format!("{{{var_name}}}")), + }); + } + } + + let mut headers = Vec::new(); + if let Some(raw_headers) = obj.get("headers").and_then(Value::as_array) { + for raw_header in raw_headers { + let Some(h_obj) = raw_header.as_object() else { continue }; + let Some(header_name) = h_obj.get("name").and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()) + else { + continue; + }; + let value_template = opt_string(h_obj.get("value")); + let header_required = bool_field(h_obj, "isRequired", "is_required"); + let header_secret = bool_field(h_obj, "isSecret", "is_secret"); + let header_desc = opt_string(h_obj.get("description")); + let header_default = opt_string(h_obj.get("default")); + let header_placeholder = opt_string(h_obj.get("placeholder")); + let header_choices = string_array(h_obj.get("choices")); + let header_vars = parse_variables_map(h_obj.get("variables")); + + if let Some(tpl) = value_template { + let vars = extract_template_vars(&tpl); + headers.push(McpKeyValue { name: header_name.to_owned(), value: tpl }); + for var_name in vars { + let meta = header_vars.get(&var_name); + let key = format!("header:{header_name}:{var_name}"); + if seen_keys.insert(key.clone()) { + inputs.push(McpRegistryInputField { + key, + label: var_name.clone(), + kind: McpRegistryInputKind::Header, + description: meta.and_then(|m| m.description.clone()).or_else(|| header_desc.clone()), + required: meta.and_then(|m| m.required).unwrap_or(header_required), + secret: meta.and_then(|m| m.secret).unwrap_or(header_secret), + default_value: meta.and_then(|m| m.default_value.clone()), + placeholder: meta.and_then(|m| m.placeholder.clone()), + choices: meta.map(|m| m.choices.clone()).unwrap_or_default(), + header_name: Some(header_name.to_owned()), + flag: None, + template_token: Some(format!("{{{var_name}}}")), + }); + } + } + } else { + let key = format!("header:{header_name}"); + if seen_keys.insert(key.clone()) { + inputs.push(McpRegistryInputField { + key, + label: header_name.to_owned(), + kind: McpRegistryInputKind::Header, + description: header_desc, + required: header_required, + secret: header_secret, + default_value: header_default, + placeholder: header_placeholder, + choices: header_choices, + header_name: Some(header_name.to_owned()), + flag: None, + template_token: None, + }); + } + } + } + } + + Some(McpRegistryInstallOption { + id: format!("remote:{idx}"), + label, + transport, + registry_type, + package_identifier: None, + command: None, + args: Vec::new(), + url: Some(url), + headers, + inputs, + runtime_available: true, + }) +} + +#[derive(Clone, Debug, Default)] +struct VarMeta { + description: Option, + required: Option, + secret: Option, + default_value: Option, + placeholder: Option, + choices: Vec, +} + +fn parse_variables_map(val: Option<&Value>) -> BTreeMap { + let Some(obj) = val.and_then(Value::as_object) else { + return BTreeMap::new(); + }; + obj.iter() + .filter_map(|(k, v)| { + let m = v.as_object()?; + Some(( + k.clone(), + VarMeta { + description: opt_string(m.get("description")), + required: opt_bool_field(m, "isRequired", "is_required"), + secret: opt_bool_field(m, "isSecret", "is_secret"), + default_value: opt_string(m.get("default")), + placeholder: opt_string(m.get("placeholder")), + choices: string_array(m.get("choices")), + }, + )) + }) + .collect() +} + +fn parse_arguments( + raw_args: &[Value], + args_out: &mut Vec, + inputs_out: &mut Vec, + seen_keys: &mut HashSet, + prefix: &str, +) { + for (idx, raw) in raw_args.iter().enumerate() { + let Some(obj) = raw.as_object() else { continue }; + let arg_type = obj.get("type").and_then(Value::as_str).unwrap_or("positional"); + let fixed_value = opt_string(obj.get("value")); + let required = bool_field(obj, "isRequired", "is_required"); + let secret = bool_field(obj, "isSecret", "is_secret"); + let description = opt_string(obj.get("description")); + let default_value = opt_string(obj.get("default")); + let placeholder = opt_string(obj.get("placeholder")); + let choices = string_array(obj.get("choices")); + let vars_meta = parse_variables_map(obj.get("variables")); + + match arg_type { + "named" => { + let Some(flag_name) = opt_string(obj.get("name")) else { continue }; + if let Some(val) = fixed_value { + let vars = extract_template_vars(&val); + args_out.push(flag_name.clone()); + args_out.push(val); + for var_name in vars { + let meta = vars_meta.get(&var_name); + let key = format!("{prefix}:{idx}:{var_name}"); + if seen_keys.insert(key.clone()) { + inputs_out.push(McpRegistryInputField { + key, + label: var_name.clone(), + kind: McpRegistryInputKind::Arg, + description: meta.and_then(|m| m.description.clone()).or_else(|| description.clone()), + required: meta.and_then(|m| m.required).unwrap_or(required), + secret: meta.and_then(|m| m.secret).unwrap_or(secret), + default_value: meta.and_then(|m| m.default_value.clone()), + placeholder: meta.and_then(|m| m.placeholder.clone()), + choices: meta.map(|m| m.choices.clone()).unwrap_or_default(), + header_name: None, + flag: None, + template_token: Some(format!("{{{var_name}}}")), + }); + } + } + } else { + let label = opt_string(obj.get("valueHint")) + .or_else(|| opt_string(obj.get("value_hint"))) + .unwrap_or_else(|| flag_name.trim_start_matches('-').to_owned()); + let key = format!("{prefix}:{idx}:{flag_name}"); + if seen_keys.insert(key.clone()) { + inputs_out.push(McpRegistryInputField { + key, + label, + kind: McpRegistryInputKind::Arg, + description, + required, + secret, + default_value, + placeholder, + choices, + header_name: None, + flag: Some(flag_name), + template_token: None, + }); + } + } + } + _ => { + if let Some(val) = fixed_value { + let vars = extract_template_vars(&val); + args_out.push(val); + for var_name in vars { + let meta = vars_meta.get(&var_name); + let key = format!("{prefix}:{idx}:{var_name}"); + if seen_keys.insert(key.clone()) { + inputs_out.push(McpRegistryInputField { + key, + label: var_name.clone(), + kind: McpRegistryInputKind::Arg, + description: meta.and_then(|m| m.description.clone()).or_else(|| description.clone()), + required: meta.and_then(|m| m.required).unwrap_or(required), + secret: meta.and_then(|m| m.secret).unwrap_or(secret), + default_value: meta.and_then(|m| m.default_value.clone()), + placeholder: meta.and_then(|m| m.placeholder.clone()), + choices: meta.map(|m| m.choices.clone()).unwrap_or_default(), + header_name: None, + flag: None, + template_token: Some(format!("{{{var_name}}}")), + }); + } + } + } else { + let label = opt_string(obj.get("valueHint")) + .or_else(|| opt_string(obj.get("value_hint"))) + .unwrap_or_else(|| format!("argument {}", idx + 1)); + let key = format!("{prefix}:{idx}:{label}"); + if seen_keys.insert(key.clone()) { + inputs_out.push(McpRegistryInputField { + key, + label, + kind: McpRegistryInputKind::Arg, + description, + required, + secret, + default_value, + placeholder, + choices, + header_name: None, + flag: None, + template_token: None, + }); + } + } + } + } + } +} + +fn extract_template_vars(text: &str) -> Vec { + let mut out = Vec::new(); + let mut seen = HashSet::new(); + let bytes = text.as_bytes(); + let mut i = 0; + while i < bytes.len() { + if bytes[i] == b'{' { + let start = i + 1; + let mut j = start; + while j < bytes.len() && bytes[j] != b'}' && bytes[j] != b'{' { + j += 1; + } + if j < bytes.len() && bytes[j] == b'}' && j > start { + let candidate = &text[start..j]; + if candidate.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.')) + && seen.insert(candidate.to_owned()) + { + out.push(candidate.to_owned()); + } + i = j + 1; + continue; + } + } + i += 1; + } + out +} + +fn allowlisted_hint<'a>(hint: Option<&'a str>, allowed: &[&'a str]) -> Option<&'a str> { + let h = hint?; + allowed.iter().copied().find(|&candidate| candidate.eq_ignore_ascii_case(h)) +} + +fn format_npm_spec(identifier: &str, version: Option<&str>) -> String { + let already_pinned = identifier.len() > 1 && identifier[1..].contains('@'); + match version { + Some(v) if !already_pinned && !v.eq_ignore_ascii_case("latest") => format!("{identifier}@{v}"), + _ => identifier.to_owned(), + } +} + +fn format_pypi_spec(identifier: &str, version: Option<&str>) -> String { + let already_pinned = identifier.contains("==") || identifier.contains(">=") || identifier.contains('@'); + match version { + Some(v) if !already_pinned && !v.eq_ignore_ascii_case("latest") => format!("{identifier}=={v}"), + _ => identifier.to_owned(), + } +} + +fn format_oci_spec(identifier: &str, version: Option<&str>) -> String { + let tail = identifier.rsplit('/').next().unwrap_or(identifier); + let already_pinned = tail.contains(':') || identifier.contains('@'); + match version { + Some(v) if !already_pinned && !v.eq_ignore_ascii_case("latest") => format!("{identifier}:{v}"), + _ => identifier.to_owned(), + } +} + +fn format_nuget_spec(identifier: &str, version: Option<&str>) -> String { + let already_pinned = identifier.contains('@'); + match version { + Some(v) if !already_pinned && !v.eq_ignore_ascii_case("latest") => format!("{identifier}@{v}"), + _ => identifier.to_owned(), + } +} + +fn opt_string(val: Option<&Value>) -> Option { + val.and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned) +} + +fn bool_field(obj: &serde_json::Map, camel: &str, snake: &str) -> bool { + opt_bool_field(obj, camel, snake).unwrap_or(false) +} + +fn opt_bool_field(obj: &serde_json::Map, camel: &str, snake: &str) -> Option { + obj.get(camel).or_else(|| obj.get(snake)).and_then(Value::as_bool) +} + +fn string_array(val: Option<&Value>) -> Vec { + val.and_then(Value::as_array) + .map(|arr| { + arr.iter().filter_map(|v| v.as_str().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned)).collect() + }) + .unwrap_or_default() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::Mutex; + + struct FakeFetcher { + responses: BTreeMap>, + requested: Mutex>, + } + + impl FakeFetcher { + fn new(responses: Vec<(&str, IdeResult)>) -> Self { + Self { + responses: responses.into_iter().map(|(k, v)| (k.to_owned(), v)).collect(), + requested: Mutex::new(Vec::new()), + } + } + } + + impl McpRegistryFetcher for FakeFetcher { + fn get_json(&self, url: &str, _max_bytes: u64, cancel: &CancellationToken) -> IdeResult { + if cancel.is_cancelled() { + return Err(IdeError::cancelled()); + } + self.requested.lock().unwrap().push(url.to_owned()); + self.responses.get(url).cloned().unwrap_or_else(|| Err(IdeError::not_found(format!("404 for {url}")))) + } + } + + #[test] + fn normalizes_and_validates_registry_urls() { + assert_eq!(normalize_registry_url(None).unwrap(), DEFAULT_MCP_REGISTRY_URL); + assert_eq!(normalize_registry_url(Some("")).unwrap(), DEFAULT_MCP_REGISTRY_URL); + assert_eq!( + normalize_registry_url(Some("https://api.mcp.github.com/v0.1/servers/")).unwrap(), + "https://api.mcp.github.com" + ); + assert_eq!( + normalize_registry_url(Some("https://registry.modelcontextprotocol.io/v0")).unwrap(), + OFFICIAL_MCP_REGISTRY_URL + ); + assert_eq!(normalize_registry_url(Some("http://localhost:8080/")).unwrap(), "http://localhost:8080"); + assert_eq!(normalize_registry_url(Some("http://127.0.0.1:9000")).unwrap(), "http://127.0.0.1:9000"); + + assert!(normalize_registry_url(Some("http://example.com")).is_err()); + assert!(normalize_registry_url(Some("https://user:pass@example.com")).is_err()); + assert!(normalize_registry_url(Some("https://example.com?foo=bar")).is_err()); + assert!(normalize_registry_url(Some("ftp://example.com")).is_err()); + } + + #[test] + fn parses_github_and_official_v01_packages_and_remotes() { + let body = r#"{ + "servers": [ + { + "server": { + "name": "microsoft/playwright-mcp", + "version": "0.0.1-seed", + "description": "Automate web browsers using accessibility trees.", + "repository": { "source": "github", "url": "https://github.com/microsoft/playwright-mcp" }, + "_meta": { + "io.modelcontextprotocol.registry/publisher-provided": { + "github": { + "displayName": "Playwright MCP", + "nameWithOwner": "microsoft/playwright-mcp", + "license": "Apache-2.0", + "stargazerCount": 40441 + } + } + }, + "packages": [ + { + "identifier": "@playwright/mcp", + "registryType": "npm", + "runtimeHint": "npx", + "transport": { "type": "stdio" }, + "version": "latest" + } + ] + } + }, + { + "server": { + "name": "io.github.netdata/mcp-server", + "title": "Netdata", + "version": "2.13.0", + "description": "Real-time monitoring.", + "websiteUrl": "https://www.netdata.cloud", + "remotes": [ + { + "type": "streamable-http", + "url": "https://app.netdata.cloud/api/v1/mcp", + "headers": [ + { + "name": "Authorization", + "value": "Bearer {NETDATA_CLOUD_API_TOKEN}", + "isRequired": true, + "isSecret": true, + "variables": { + "NETDATA_CLOUD_API_TOKEN": { + "description": "Netdata API token", + "isSecret": true + } + } + } + ] + } + ] + } + }, + { + "server": { + "name": "com.microsoft/playwright-cloud-browsers", + "title": "Playwright Cloud Browsers", + "version": "1.0.1", + "description": "Managed Playwright cloud browsers.", + "remotes": [ + { + "type": "streamable-http", + "url": "https://{region}.mcp.playwright.microsoft.com/ws/{workspaceId}/mcp", + "variables": { + "region": { "description": "Azure region", "isRequired": true, "placeholder": "eastus" }, + "workspaceId": { "description": "Workspace ID", "isRequired": true } + } + } + ] + } + }, + { + "server": { + "name": "com.example/docker-tool", + "version": "1.2.3", + "description": "OCI server with env and args.", + "packages": [ + { + "identifier": "ghcr.io/example/tool", + "registryType": "oci", + "version": "1.2.3", + "transport": { "type": "stdio" }, + "environmentVariables": [ + { "name": "API_KEY", "isRequired": true, "isSecret": true, "description": "Secret key" } + ], + "packageArguments": [ + { "type": "named", "name": "--workspace", "isRequired": true, "valueHint": "path" } + ] + } + ] + } + } + ], + "metadata": { + "nextCursor": "cursor-2", + "total": 981 + } + }"#; + + let page = parse_registry_page(DEFAULT_MCP_REGISTRY_URL, body, |cmd| cmd == "npx").unwrap(); + assert_eq!(page.total, Some(981)); + assert_eq!(page.next_cursor.as_deref(), Some("cursor-2")); + assert_eq!(page.servers.len(), 4); + + let pw = &page.servers[0]; + assert_eq!(pw.display_name, "Playwright MCP"); + assert_eq!(pw.suggested_name, "playwright-mcp"); + assert_eq!(pw.stars, Some(40441)); + assert_eq!(pw.publisher.as_deref(), Some("microsoft")); + assert_eq!(pw.install_options.len(), 1); + let pw_opt = &pw.install_options[0]; + assert_eq!(pw_opt.command.as_deref(), Some("npx")); + assert_eq!(pw_opt.args, vec!["-y", "@playwright/mcp"]); + assert!(pw_opt.inputs.is_empty()); + assert!(pw_opt.runtime_available); + + let nd = &page.servers[1]; + assert_eq!(nd.suggested_name, "netdata"); + assert_eq!(nd.install_options[0].transport, McpTransport::Http); + assert_eq!(nd.install_options[0].headers.len(), 1); + assert_eq!(nd.install_options[0].inputs.len(), 1); + assert_eq!(nd.install_options[0].inputs[0].kind, McpRegistryInputKind::Header); + assert_eq!(nd.install_options[0].inputs[0].template_token.as_deref(), Some("{NETDATA_CLOUD_API_TOKEN}")); + assert!(nd.install_options[0].inputs[0].required); + assert!(nd.install_options[0].inputs[0].secret); + + let cloud = &page.servers[2]; + assert_eq!(cloud.install_options[0].inputs.len(), 2); + assert_eq!(cloud.install_options[0].inputs[0].kind, McpRegistryInputKind::UrlVar); + assert_eq!(cloud.install_options[0].inputs[0].template_token.as_deref(), Some("{region}")); + + let oci = &page.servers[3]; + let oci_opt = &oci.install_options[0]; + assert_eq!(oci_opt.command.as_deref(), Some("docker")); + assert_eq!(oci_opt.args, vec!["run", "-i", "--rm", "-e", "API_KEY", "ghcr.io/example/tool:1.2.3"]); + assert!(!oci_opt.runtime_available); + assert_eq!(oci_opt.inputs.len(), 2); + assert_eq!(oci_opt.inputs[0].kind, McpRegistryInputKind::Env); + assert_eq!(oci_opt.inputs[1].kind, McpRegistryInputKind::Arg); + assert_eq!(oci_opt.inputs[1].flag.as_deref(), Some("--workspace")); + } + + #[test] + fn falls_back_from_v01_to_v0_on_404() { + let v0_url = "https://custom.example.com/v0/servers?limit=10&version=latest&search=hello%20world"; + let fetcher = FakeFetcher::new(vec![( + v0_url, + Ok(r#"{"servers":[{"name":"acme/echo","version":"1.0.0","description":"Echo","packages":[{"registryType":"pypi","identifier":"echo-mcp","version":"1.0.0"}]}]}"#.into()), + )]); + let page = search_registry( + &fetcher, + Some("https://custom.example.com"), + Some("hello world"), + None, + Some(10), + OsStr::new(""), + &CancellationToken::new(), + ) + .unwrap(); + assert_eq!(page.servers.len(), 1); + assert_eq!(page.servers[0].install_options[0].command.as_deref(), Some("uvx")); + assert_eq!(page.servers[0].install_options[0].args, vec!["echo-mcp==1.0.0"]); + let requested = fetcher.requested.lock().unwrap(); + assert_eq!(requested.len(), 2); + assert!(requested[0].contains("/v0.1/servers")); + assert!(requested[1].contains("/v0/servers")); + } + + #[test] + fn extracts_themed_registry_icons_github_avatars_and_rejects_unsafe_urls() { + let body = r#"{ + "servers": [ + { + "server": { + "name": "com.example/themed", + "version": "1.0.0", + "description": "Themed icons", + "icons": [ + { "src": "javascript:alert(1)", "theme": "light" }, + { "src": "https://cdn.example.com/light.png", "theme": "light" }, + { "src": "https://cdn.example.com/dark.png", "theme": "dark" } + ] + } + }, + { + "server": { + "name": "microsoft/markitdown", + "version": "1.0.0", + "description": "GitHub meta avatar", + "_meta": { + "io.modelcontextprotocol.registry/publisher-provided": { + "github": { + "preferredImage": "https://avatars.githubusercontent.com/u/6154722?v=4", + "ownerAvatarUrl": "https://avatars.githubusercontent.com/u/6154722?v=4" + } + } + } + } + }, + { + "server": { + "name": "io.github.upstash/context7", + "version": "1.0.0", + "description": "Namespace GitHub fallback" + } + }, + { + "server": { + "name": "ac.plain/no-icon", + "version": "1.0.0", + "description": "No icon at all", + "icons": [{ "src": "http://insecure.example.com/icon.png" }] + } + } + ] + }"#; + + let page = parse_registry_page(DEFAULT_MCP_REGISTRY_URL, body, |_| true).unwrap(); + assert_eq!(page.servers[0].icon_url.as_deref(), Some("https://cdn.example.com/light.png")); + assert_eq!(page.servers[0].icon_dark_url.as_deref(), Some("https://cdn.example.com/dark.png")); + assert_eq!(page.servers[1].icon_url.as_deref(), Some("https://avatars.githubusercontent.com/u/6154722?v=4")); + assert_eq!(page.servers[1].icon_dark_url, None); + assert_eq!(page.servers[2].icon_url.as_deref(), Some("https://github.com/upstash.png?size=64")); + assert_eq!(page.servers[3].icon_url, None); + } +} diff --git a/crates/ide-agent/src/model.rs b/crates/ide-agent/src/model.rs index 4e6df20139..ac9a0665ca 100644 --- a/crates/ide-agent/src/model.rs +++ b/crates/ide-agent/src/model.rs @@ -1058,6 +1058,14 @@ pub struct McpServer { #[serde(default, skip_serializing_if = "Option::is_none")] #[specta(optional)] pub plugin_name: Option, + /// Canonical MCP registry server identifier when installed from an MCP registry. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub registry_name: Option, + /// Normalized MCP registry base URL when installed from an MCP registry. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub registry_url: Option, } /// Payload for creating or updating a user or workspace MCP server. @@ -1084,6 +1092,14 @@ pub struct McpServerInput { /// Agent provider ids this server is enabled for; empty means enabled for all agents. #[serde(default)] pub agents: Vec, + /// Canonical MCP registry server identifier when installed from an MCP registry. + #[serde(default)] + #[specta(optional)] + pub registry_name: Option, + /// Normalized MCP registry base URL when installed from an MCP registry. + #[serde(default)] + #[specta(optional)] + pub registry_url: Option, } fn default_true() -> bool { diff --git a/crates/ide-agent/src/plugins.rs b/crates/ide-agent/src/plugins.rs index 33445a1097..9c3112894e 100644 --- a/crates/ide-agent/src/plugins.rs +++ b/crates/ide-agent/src/plugins.rs @@ -1461,6 +1461,8 @@ pub fn projected_mcp_servers( unapproved: false, plugin_id: Some(state.plugin.id.clone()), plugin_name: Some(state.plugin.display_name.clone()), + registry_name: None, + registry_url: None, }); } } diff --git a/crates/ide-agent/src/tests.rs b/crates/ide-agent/src/tests.rs index 7543970c1b..2d0ed37e4e 100644 --- a/crates/ide-agent/src/tests.rs +++ b/crates/ide-agent/src/tests.rs @@ -6366,6 +6366,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() { unapproved: false, plugin_id: None, plugin_name: None, + registry_name: None, + registry_url: None, }, McpServer { id: "user::slack".into(), @@ -6382,6 +6384,8 @@ async fn per_session_mcp_overrides_filter_session_and_reload_when_idle() { unapproved: false, plugin_id: None, plugin_name: None, + registry_name: None, + registry_url: None, }, ] })); diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index 34bacd6b20..324425cbdb 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -162,6 +162,9 @@ pub struct AgentSettings { #[serde(deserialize_with = "or_default")] #[specta(type = BTreeMap)] pub mcp_servers: BTreeMap, + /// Custom MCP Registry base URL (`agents.mcpRegistryUrl`); empty = GitHub MCP Registry. + #[serde(default, skip_serializing_if = "String::is_empty")] + pub mcp_registry_url: String, /// How agent skills may run, keyed by skill name (`[agents.skills.]`); `SKILL.md` /// files on disk are never modified. #[serde(deserialize_with = "or_default")] @@ -211,6 +214,7 @@ impl Default for AgentSettings { confirm_terminate_on_close: true, defaults: BTreeMap::new(), mcp_servers: BTreeMap::new(), + mcp_registry_url: String::new(), skills: BTreeMap::new(), memory: AgentMemorySettings::default(), plugins: AgentPluginSettings::default(), @@ -253,6 +257,14 @@ pub struct AgentMcpServer { /// empty means enabled for all agents. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub agents: Vec, + /// Canonical MCP registry server identifier (e.g. `microsoft/playwright-mcp`) when installed from a registry. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub registry_name: Option, + /// Normalized MCP registry base URL (e.g. `https://api.mcp.github.com`) when installed from a registry. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[specta(optional)] + pub registry_url: Option, } impl Default for AgentMcpServer { @@ -266,6 +278,8 @@ impl Default for AgentMcpServer { url: None, headers: BTreeMap::new(), agents: Vec::new(), + registry_name: None, + registry_url: None, } } } diff --git a/crates/ide-host/src/ops/agent.rs b/crates/ide-host/src/ops/agent.rs index a581082c2c..3de6366ae6 100644 --- a/crates/ide-host/src/ops/agent.rs +++ b/crates/ide-host/src/ops/agent.rs @@ -13,9 +13,9 @@ use ide_agent::{ AgentQueued, AgentRecoveryReport, AgentSkillMode, AgentSkillPolicy, AgentSkillState, AgentTask, AutoMemoryMode, AutomationRun, AutomationRunsPage, AutomationSnapshot, AutomationTrigger, AutomationWorkspace, CopilotAuthStatus, CreateAgentMemoryInput, CreateSessionScheduleInput, CustomAgentInput, ExternalSession, InstallAgentPluginRequest, - InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, McpScope, - McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput, RemoteSkillBrowseResult, - RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy, + InstallRemoteSkillRequest, Isolation, LoginLaunch, McpExternalSource, McpImportSelection, McpProbeResult, + McpRegistryPage, McpScope, McpServer, McpServerInput, McpTransport, NewAgentTask, PromoteAgentMemoryInput, + RemoteSkillBrowseResult, RemoteSkillPreview, SaveAutomationInput, SessionSchedule, SkillsPolicy, }; use ide_command::command; use ide_core::error::ErrorKind; @@ -1205,6 +1205,42 @@ pub async fn agent_mcp_import_selected( }) } +/// Searches or lists MCP servers from an open MCP Registry (`v0.1` / `v0`). +/// When `registry_url` is omitted or blank, uses `agents.mcpRegistryUrl` or GitHub's MCP Registry. +#[command(trust = always)] +pub async fn agent_mcp_registry_search( + host: &Host, + registry_url: Option, + query: Option, + cursor: Option, + limit: Option, + request: RequestId, +) -> IdeResult { + let effective_url = + registry_url.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned).or_else(|| { + let configured = host.global_settings.effective().agents.mcp_registry_url; + let trimmed = configured.trim(); + (!trimmed.is_empty()).then(|| trimmed.to_owned()) + }); + let cancel = host.begin_request(request); + let search_path = ide_core::tool_path::search_path(); + let res = blocking(move || { + let fetcher = ide_agent::mcp_registry::HttpMcpRegistryFetcher::new(&search_path)?; + ide_agent::mcp_registry::search_registry( + &fetcher, + effective_url.as_deref(), + query.as_deref(), + cursor.as_deref(), + limit, + &search_path, + &cancel, + ) + }) + .await; + host.end_request(request); + res +} + /// Tests an MCP server by connecting (`initialize`) and listing its tools (`tools/list`). #[command(trust = trusted)] pub async fn agent_mcp_test(host: &Host, window: &str, id: String) -> IdeResult { @@ -2888,6 +2924,7 @@ ide_command::domain!( agent_mcp_import, agent_mcp_import_selected, agent_mcp_list, + agent_mcp_registry_search, agent_mcp_remove, agent_mcp_save, agent_mcp_save_json, diff --git a/crates/ide-host/tests/agent_mcp.rs b/crates/ide-host/tests/agent_mcp.rs index cbe01e571b..766e3c6e77 100644 --- a/crates/ide-host/tests/agent_mcp.rs +++ b/crates/ide-host/tests/agent_mcp.rs @@ -6,8 +6,8 @@ use ide_agent::{McpScope, McpServer, McpServerInput}; use ide_core::settings::McpTransport; use ide_host::Host; use ide_host::ops::agent::{ - agent_mcp_import as mcp_import, agent_mcp_list as mcp_list, agent_mcp_save as mcp_save, - agent_mcp_set_enabled as mcp_set_enabled, + agent_mcp_import as mcp_import, agent_mcp_list as mcp_list, agent_mcp_remove as mcp_remove, + agent_mcp_save as mcp_save, agent_mcp_set_enabled as mcp_set_enabled, }; use std::path::{Path, PathBuf}; use std::sync::Arc; @@ -58,6 +58,8 @@ async fn workspace_servers_from_the_project_file_stay_off_until_the_user_turns_t url: None, headers: vec![], agents: vec![], + registry_name: None, + registry_url: None, }, ) .unwrap(); @@ -69,3 +71,64 @@ async fn workspace_servers_from_the_project_file_stay_off_until_the_user_turns_t assert!(!enabled(&imported, "workspace::imported")); assert!(enabled(&imported, "workspace::mine")); } + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn registry_provenance_round_trips_survives_edit_and_uninstalls_cleanly() { + let tmp = tempfile::tempdir().unwrap(); + let (host, _root) = open(tmp.path()); + + // Install from registry into User scope. + let saved = mcp_save( + &host, + "main", + McpServerInput { + id: None, + name: "playwright-mcp".into(), + scope: McpScope::User, + transport: McpTransport::Stdio, + enabled: true, + command: Some("npx".into()), + args: vec!["-y".into(), "@playwright/mcp".into()], + env: vec![], + url: None, + headers: vec![], + agents: vec![], + registry_name: Some("microsoft/playwright-mcp".into()), + registry_url: Some("https://api.mcp.github.com".into()), + }, + ) + .unwrap(); + let installed = saved.iter().find(|s| s.id == "user::playwright-mcp").expect("installed server present"); + assert_eq!(installed.registry_name.as_deref(), Some("microsoft/playwright-mcp")); + assert_eq!(installed.registry_url.as_deref(), Some("https://api.mcp.github.com")); + + // Updating the server without re-sending registry fields preserves provenance. + let edited = mcp_save( + &host, + "main", + McpServerInput { + id: Some("user::playwright-mcp".into()), + name: "playwright-mcp".into(), + scope: McpScope::User, + transport: McpTransport::Stdio, + enabled: true, + command: Some("npx".into()), + args: vec!["-y".into(), "@playwright/mcp".into(), "--headless".into()], + env: vec![], + url: None, + headers: vec![], + agents: vec!["copilot".into()], + registry_name: None, + registry_url: None, + }, + ) + .unwrap(); + let after_edit = edited.iter().find(|s| s.id == "user::playwright-mcp").expect("edited server present"); + assert_eq!(after_edit.registry_name.as_deref(), Some("microsoft/playwright-mcp")); + assert_eq!(after_edit.registry_url.as_deref(), Some("https://api.mcp.github.com")); + assert_eq!(after_edit.agents, vec!["copilot"]); + + // One-click uninstall removes the server cleanly. + let after_remove = mcp_remove(&host, "main", "user::playwright-mcp".into()).unwrap(); + assert!(!after_remove.iter().any(|s| s.id == "user::playwright-mcp")); +} diff --git a/crates/ide-host/tests/mcp_secrets.rs b/crates/ide-host/tests/mcp_secrets.rs index 58cf64e6e6..a146453c9b 100644 --- a/crates/ide-host/tests/mcp_secrets.rs +++ b/crates/ide-host/tests/mcp_secrets.rs @@ -46,6 +46,8 @@ fn input(name: &str, scope: McpScope) -> McpServerInput { url: Some("https://mcp.example/v1".into()), headers: vec![McpKeyValue { name: "Authorization".into(), value: format!("Bearer {VALUE}") }], agents: vec![], + registry_name: None, + registry_url: None, } } diff --git a/e2e/agentMcp.spec.ts b/e2e/agentMcp.spec.ts index 79dd0ead61..e7a4241a05 100644 --- a/e2e/agentMcp.spec.ts +++ b/e2e/agentMcp.spec.ts @@ -4,7 +4,9 @@ import type { AgentTask, McpExternalSource, McpProbeResult, + McpRegistryPage, McpServer, + McpServerInput, } from "../src/bindings"; import { expect, ipcCalls, stubDesktop, test } from "./fixtures"; @@ -359,7 +361,7 @@ test("manages multi-level MCP servers in Settings and per-session overrides via if (screenshotDir) { await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-hub-levels.png` }); - await settingsDialog.getByRole("button", { name: "More Actions" }).click(); + await settingsDialog.getByRole("button", { name: "More Actions", exact: true }).click(); await page.getByRole("menuitem", { name: "Add from JSON…" }).click(); const addDialog = page.getByRole("dialog", { name: "Add MCP Server" }); await expect(addDialog).toBeVisible(); @@ -380,3 +382,307 @@ test("manages multi-level MCP servers in Settings and per-session overrides via await settingsDialog.getByRole("button", { name: "Import Selected (1)" }).click(); await expect(settingsDialog.getByText("Imported 1 MCP servers into Global settings.")).toBeVisible(); }); + +const svgDataIcon = (bg: string, label: string) => + `data:image/svg+xml,${encodeURIComponent( + `${label}`, + )}`; + +const registryPage: McpRegistryPage = { + registryUrl: "https://api.mcp.github.com", + total: 981, + nextCursor: "cursor-page-2", + servers: [ + { + name: "microsoft/playwright-mcp", + displayName: "Playwright MCP", + suggestedName: "playwright-mcp", + description: "Automate web browsers using accessibility trees for testing and data extraction.", + version: "0.0.1-seed", + publisher: "microsoft", + iconUrl: svgDataIcon("#2EAD33", "PW"), + iconDarkUrl: null, + repositoryUrl: "https://github.com/microsoft/playwright-mcp", + websiteUrl: null, + license: "Apache-2.0", + stars: 40441, + installOptions: [ + { + id: "pkg:0", + label: "npm (npx)", + transport: "stdio", + registryType: "npm", + packageIdentifier: "@playwright/mcp", + command: "npx", + args: ["-y", "@playwright/mcp"], + url: null, + headers: [], + inputs: [], + runtimeAvailable: true, + }, + ], + }, + { + name: "io.github.netdata/mcp-server", + displayName: "Netdata", + suggestedName: "netdata", + description: "Real-time infrastructure monitoring with metrics, logs, alerts, and ML-based anomaly detection.", + version: "2.13.0", + publisher: "netdata", + iconUrl: svgDataIcon("#00AB44", "ND"), + iconDarkUrl: null, + repositoryUrl: "https://github.com/netdata/netdata", + websiteUrl: "https://www.netdata.cloud", + license: "GPL-3.0", + stars: 74200, + installOptions: [ + { + id: "remote:0", + label: "Streamable HTTP", + transport: "http", + registryType: "streamable-http", + packageIdentifier: null, + command: null, + args: [], + url: "https://app.netdata.cloud/api/v1/mcp", + headers: [{ name: "Authorization", value: "Bearer {NETDATA_CLOUD_API_TOKEN}" }], + inputs: [ + { + key: "header:Authorization:NETDATA_CLOUD_API_TOKEN", + label: "NETDATA_CLOUD_API_TOKEN", + kind: "header", + description: "Netdata Cloud API token with scope:mcp", + required: true, + secret: true, + defaultValue: null, + placeholder: null, + choices: [], + headerName: "Authorization", + flag: null, + templateToken: "{NETDATA_CLOUD_API_TOKEN}", + }, + ], + runtimeAvailable: true, + }, + ], + }, + { + name: "microsoft/markitdown", + displayName: "MarkItDown", + suggestedName: "markitdown", + description: "Convert various file formats (PDF, Word, Excel, images, audio) to Markdown.", + version: "1.0.0", + publisher: "microsoft", + iconUrl: svgDataIcon("#0078D4", "MD"), + iconDarkUrl: null, + repositoryUrl: "https://github.com/microsoft/markitdown", + websiteUrl: null, + license: "MIT License", + stars: 199509, + installOptions: [ + { + id: "pkg:0", + label: "PyPI (uvx)", + transport: "stdio", + registryType: "pypi", + packageIdentifier: "markitdown-mcp", + command: "uvx", + args: ["markitdown-mcp==0.0.1a4"], + url: null, + headers: [], + inputs: [], + runtimeAvailable: false, + }, + ], + }, + ...Array.from({ length: 10 }, (_, idx) => ({ + name: `io.example/demo-server-${idx + 1}`, + displayName: `Demo Server ${idx + 1}`, + suggestedName: `demo-server-${idx + 1}`, + description: `Sample MCP server ${idx + 1} for scrollable registry listing.`, + version: "1.0.0", + publisher: "example", + iconUrl: idx % 2 === 0 ? svgDataIcon("#5B6AE0", `S${idx + 1}`) : null, + iconDarkUrl: null, + repositoryUrl: null, + websiteUrl: null, + license: "MIT", + stars: 100 - idx, + installOptions: [ + { + id: "remote:0", + label: "Streamable HTTP", + transport: "http" as const, + registryType: "streamable-http", + packageIdentifier: null, + command: null, + args: [], + url: `https://demo-${idx + 1}.example.com/mcp`, + headers: [], + inputs: [], + runtimeAvailable: true, + }, + ], + })), + ], +}; + +const registryPage2: McpRegistryPage = { + registryUrl: "https://api.mcp.github.com", + total: 981, + nextCursor: null, + servers: [ + { + name: "upstash/context7", + displayName: "Context7 MCP", + suggestedName: "context7", + description: "Up-to-date documentation and code examples for any library.", + version: "1.0.12", + publisher: "upstash", + iconUrl: svgDataIcon("#00B87C", "C7"), + iconDarkUrl: null, + repositoryUrl: "https://github.com/upstash/context7", + websiteUrl: null, + license: "MIT", + stars: 35200, + installOptions: [ + { + id: "pkg:0", + label: "npm (npx)", + transport: "stdio", + registryType: "npm", + packageIdentifier: "@upstash/context7-mcp", + command: "npx", + args: ["-y", "@upstash/context7-mcp"], + url: null, + headers: [], + inputs: [], + runtimeAvailable: true, + }, + ], + }, + ], +}; + +test("browses the MCP Registry with infinite scroll and performs one-click install and uninstall", async ({ + workbench: page, +}) => { + await page.setViewportSize({ width: 1180, height: 800 }); + await stubDesktop(page); + + await page.evaluate( + async ({ initialServers, registryPage, registryPage2 }) => { + let servers = structuredClone(initialServers); + const handlers = window.__ipc.handlers; + handlers.window_open_settings = () => { + throw { kind: "unavailable", message: "separate settings window disabled in browser test", detail: null }; + }; + handlers.agent_mcp_list = () => servers; + handlers.agent_mcp_discover_sources = () => []; + handlers.agent_mcp_registry_search = ({ query, cursor }) => { + if (cursor === "cursor-page-2") { + return registryPage2; + } + const q = String(query ?? "") + .trim() + .toLowerCase(); + return { + ...registryPage, + servers: q + ? registryPage.servers.filter( + (s) => s.displayName.toLowerCase().includes(q) || s.name.toLowerCase().includes(q), + ) + : registryPage.servers, + nextCursor: q ? null : registryPage.nextCursor, + }; + }; + handlers.agent_mcp_save = ({ input }) => { + const req = input as McpServerInput; + const id = `${req.scope}::${req.name}`; + servers = [ + ...servers.filter((s) => s.id !== id), + { + id, + name: req.name, + scope: req.scope, + transport: req.transport, + enabled: req.enabled ?? true, + command: req.command ?? null, + args: req.args ?? [], + env: req.env ?? [], + url: req.url ?? null, + headers: req.headers ?? [], + agents: req.agents ?? [], + unapproved: false, + registryName: req.registryName ?? null, + registryUrl: req.registryUrl ?? null, + }, + ]; + return servers; + }; + handlers.agent_mcp_remove = ({ id }) => { + servers = servers.filter((s) => s.id !== id); + return servers; + }; + const actionsModule = "/src/platform/actions.ts"; + const { executeAction } = await import(/* @vite-ignore */ actionsModule); + await executeAction("file.settings", "agents.mcpServers"); + }, + { initialServers, registryPage, registryPage2 }, + ); + + const settingsDialog = page.getByRole("dialog", { name: "Settings", exact: true }); + await expect(settingsDialog).toBeVisible(); + await settingsDialog.getByRole("tab", { name: "Browse", exact: true }).click(); + await expect(settingsDialog.getByText("Playwright MCP", { exact: true })).toBeVisible(); + await expect(settingsDialog.getByText("Netdata", { exact: true })).toBeVisible(); + await expect(settingsDialog.getByText("Needs uvx", { exact: true })).toBeVisible(); + await expect(settingsDialog.getByRole("button", { name: "Load More" })).toHaveCount(0); + await expect(settingsDialog.getByText("Context7 MCP", { exact: true })).toHaveCount(0); + + const screenshotDir = process.env.CAPTURE_MCP_SCREENSHOTS; + if (screenshotDir) { + await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-browse-light.png`, animations: "disabled" }); + } + + // One-click install Playwright MCP. + const pwRow = settingsDialog.getByRole("listitem").filter({ hasText: "Playwright MCP" }); + await pwRow.getByRole("button", { name: "Install", exact: true }).click(); + await expect(pwRow.getByText("Installed")).toBeVisible(); + await expect(pwRow.getByRole("button", { name: "Uninstall", exact: true })).toBeVisible(); + + if (screenshotDir) { + await settingsDialog.screenshot({ + path: `${screenshotDir}/mcp-browse-installed-light.png`, + animations: "disabled", + }); + + // Open Install dialog for Netdata (required secret header). + const ndRow = settingsDialog.getByRole("listitem").filter({ hasText: "Netdata" }); + await ndRow.getByRole("button", { name: "Install…" }).click(); + const installDlg = page.getByRole("dialog", { name: "Install MCP Server — Netdata" }); + await expect(installDlg).toBeVisible(); + await installDlg.screenshot({ + path: `${screenshotDir}/mcp-browse-install-dialog-light.png`, + animations: "disabled", + }); + await installDlg.getByRole("button", { name: "Cancel" }).click(); + + // Dark theme screenshot. + await page.evaluate(async () => { + const themePath = "/src/workbench/theme.ts"; + const { setTheme } = await import(/* @vite-ignore */ themePath); + await setTheme("dark"); + }); + await settingsDialog.screenshot({ path: `${screenshotDir}/mcp-browse-dark.png`, animations: "disabled" }); + } + + // One-click uninstall Playwright MCP. + await pwRow.getByRole("button", { name: "Uninstall", exact: true }).click(); + await expect(pwRow.getByRole("button", { name: "Install", exact: true })).toBeVisible(); + + // Scroll to the bottom to trigger pageless infinite scroll automatically. + await settingsDialog.getByTestId("mcp-registry-sentinel").scrollIntoViewIfNeeded(); + await expect(settingsDialog.getByText("Context7 MCP", { exact: true })).toBeVisible(); + await expect(settingsDialog.getByTestId("mcp-registry-sentinel")).toHaveCount(0); +}); diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index d7474105d9..d8715a13c5 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -43,6 +43,7 @@ agent_mcp_discover_sources always project_host bin agent_mcp_import always project_host bindings sync agent_mcp_import_selected always project_host bindings async agent_mcp_list always project_host bindings sync +agent_mcp_registry_search always project_host bindings async agent_mcp_remove always project_host bindings sync agent_mcp_save always project_host bindings sync agent_mcp_save_json always project_host bindings sync diff --git a/src/bindings.ts b/src/bindings.ts index ef9ef8f447..bd319e0782 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -124,6 +124,11 @@ export const commands = { agentMcpImportSelected: (scope: McpScope, selections: McpImportSelection[], overwrite: boolean) => typedError(__TAURI_INVOKE("agent_mcp_import_selected", { scope, selections, overwrite })), /** Lists configured and discovered MCP servers across User, Workspace, Plugin, and Built-In scopes. */ agentMcpList: () => typedError(__TAURI_INVOKE("agent_mcp_list")), + /** + * Searches or lists MCP servers from an open MCP Registry (`v0.1` / `v0`). + * When `registry_url` is omitted or blank, uses `agents.mcpRegistryUrl` or GitHub's MCP Registry. + */ + agentMcpRegistrySearch: (registryUrl: string | null, query: string | null, cursor: string | null, limit: number | null, request: RequestId) => typedError(__TAURI_INVOKE("agent_mcp_registry_search", { registryUrl, query, cursor, limit, request })), /** Removes a User or Workspace MCP server and returns the updated list. */ agentMcpRemove: (id: string) => typedError(__TAURI_INVOKE("agent_mcp_remove", { id })), /** Creates or updates a User or Workspace MCP server and returns the updated list. */ @@ -3787,6 +3792,10 @@ export type AgentMcpServer_Deserialize = { * empty means enabled for all agents. */ agents?: string[], + /** Canonical MCP registry server identifier (e.g. `microsoft/playwright-mcp`) when installed from a registry. */ + registryName?: string | null, + /** Normalized MCP registry base URL (e.g. `https://api.mcp.github.com`) when installed from a registry. */ + registryUrl?: string | null, }; /** An MCP server passed to coding agents in `session/new`, `session/load` and `session/fork`. */ @@ -3803,6 +3812,10 @@ export type AgentMcpServer_Serialize = { * empty means enabled for all agents. */ agents?: string[], + /** Canonical MCP registry server identifier (e.g. `microsoft/playwright-mcp`) when installed from a registry. */ + registryName?: string | null, + /** Normalized MCP registry base URL (e.g. `https://api.mcp.github.com`) when installed from a registry. */ + registryUrl?: string | null, }; /** Full catalog returned to Settings › Agents › Memory and the Composer `MemoryPicker`. */ @@ -4680,6 +4693,8 @@ export type AgentSettings_Deserialize = { * keyed by server name (`[agents.mcpServers.]`). */ mcpServers?: { [key in string]: AgentMcpServer_Deserialize }, + /** Custom MCP Registry base URL (`agents.mcpRegistryUrl`); empty = GitHub MCP Registry. */ + mcpRegistryUrl?: string, /** * How agent skills may run, keyed by skill name (`[agents.skills.]`); `SKILL.md` * files on disk are never modified. @@ -4764,6 +4779,8 @@ export type AgentSettings_Serialize = { * keyed by server name (`[agents.mcpServers.]`). */ mcpServers: { [key in string]: AgentMcpServer_Serialize }, + /** Custom MCP Registry base URL (`agents.mcpRegistryUrl`); empty = GitHub MCP Registry. */ + mcpRegistryUrl?: string, /** * How agent skills may run, keyed by skill name (`[agents.skills.]`); `SKILL.md` * files on disk are never modified. @@ -12931,6 +12948,89 @@ export type McpProbeResult = { error: string | null, }; +/** One configurable input declared by an MCP registry package or remote endpoint. */ +export type McpRegistryInputField = { + /** Stable key unique within its install option. */ + key: string, + /** Short display label (env var name, header name, or variable identifier). */ + label: string, + kind: McpRegistryInputKind, + description: string | null, + required: boolean, + secret: boolean, + defaultValue: string | null, + placeholder: string | null, + choices: string[], + /** Target HTTP header name when `kind == Header`. */ + headerName: string | null, + /** Target CLI flag (e.g. `--dir`) when `kind == Arg` and the argument is appended dynamically. */ + flag: string | null, + /** Literal placeholder token (e.g. `{region}`) to substitute in `url`, `headers`, or `args`. */ + templateToken: string | null, +}; + +/** Kind of user-supplied input required or optional when installing an MCP server from a registry. */ +export type McpRegistryInputKind = +/** Environment variable passed to a stdio server (`env`). */ +"env" | +/** HTTP header value or `{var}` placeholder inside an HTTP/SSE header. */ +"header" | +/** `{var}` placeholder inside an HTTP/SSE endpoint URL. */ +"urlVar" | +/** CLI argument value (named flag or positional argument) or `{var}` placeholder inside `args`. */ +"arg"; + +/** One concrete way to install and launch an MCP registry server (either a local package or a remote URL). */ +export type McpRegistryInstallOption = { + id: string, + /** Human-readable option label (e.g. `npm (npx)`, `PyPI (uvx)`, `Docker`, `Streamable HTTP`). */ + label: string, + transport: McpTransport, + /** Underlying registry type (`npm`, `pypi`, `oci`, `nuget`, `streamable-http`, `sse`). */ + registryType: string, + packageIdentifier: string | null, + command: string | null, + args: string[], + url: string | null, + /** Pre-populated or templated HTTP headers (e.g. `Authorization: Bearer {TOKEN}`). */ + headers: McpKeyValue[], + /** Declared env vars, header tokens, URL variables, and CLI arguments. */ + inputs: McpRegistryInputField[], + /** + * Whether the required local runtime binary (`npx`, `uvx`, `docker`, `dnx`…) is available on `PATH`. + * Always `true` for remote HTTP/SSE endpoints. + */ + runtimeAvailable: boolean, +}; + +/** Paginated response returned to Settings › Agents › MCP Connections › Browse. */ +export type McpRegistryPage = { + registryUrl: string, + servers: McpRegistryServer[], + nextCursor: string | null, + total: number | null, +}; + +/** One MCP server returned by an MCP registry search or listing. */ +export type McpRegistryServer = { + /** Canonical registry server identifier (e.g. `microsoft/playwright-mcp`). */ + name: string, + /** Human-friendly display title. */ + displayName: string, + /** Sanitized local configuration key suggestion (e.g. `playwright-mcp`). */ + suggestedName: string, + description: string, + version: string, + publisher: string | null, + iconUrl: string | null, + iconDarkUrl: string | null, + repositoryUrl: string | null, + websiteUrl: string | null, + license: string | null, + stars: number | null, + installOptions: McpRegistryInstallOption[], +}; + /** Where an MCP server configuration is stored (`settings.toml` vs `.openidea/settings.toml`). */ export type McpScope = "user" | "workspace"; @@ -12951,6 +13051,10 @@ export type McpServerInput = { headers?: McpKeyValue[], /** Agent provider ids this server is enabled for; empty means enabled for all agents. */ agents?: string[], + /** Canonical MCP registry server identifier when installed from an MCP registry. */ + registryName?: string | null, + /** Normalized MCP registry base URL when installed from an MCP registry. */ + registryUrl?: string | null, }; /** Agents › MCP Server: agents use the IDE's built-in tools. */ @@ -13097,6 +13201,10 @@ export type McpServer_Deserialize = { pluginId?: string | null, /** Display name of the parent agent plugin. */ pluginName?: string | null, + /** Canonical MCP registry server identifier when installed from an MCP registry. */ + registryName?: string | null, + /** Normalized MCP registry base URL when installed from an MCP registry. */ + registryUrl?: string | null, }; /** One configured Model Context Protocol (MCP) server. */ @@ -13119,6 +13227,10 @@ export type McpServer_Serialize = { pluginId?: string | null, /** Display name of the parent agent plugin. */ pluginName?: string | null, + /** Canonical MCP registry server identifier when installed from an MCP registry. */ + registryName?: string | null, + /** Normalized MCP registry base URL when installed from an MCP registry. */ + registryUrl?: string | null, }; /** One tool advertised by an MCP server during `tools/list`. */ diff --git a/src/features/agents/AgentPluginsPage.module.css b/src/features/agents/AgentPluginsPage.module.css index 79fbcdac81..7d89491795 100644 --- a/src/features/agents/AgentPluginsPage.module.css +++ b/src/features/agents/AgentPluginsPage.module.css @@ -218,6 +218,10 @@ min-width: 0; } +.chipSep { + color: var(--fg-faint); +} + .dialogBody { display: flex; flex-direction: column; diff --git a/src/features/agents/AgentPluginsPage.test.tsx b/src/features/agents/AgentPluginsPage.test.tsx index 9fe56caa99..0d0c895253 100644 --- a/src/features/agents/AgentPluginsPage.test.tsx +++ b/src/features/agents/AgentPluginsPage.test.tsx @@ -114,10 +114,27 @@ function createMockBackend(initial: AgentPluginCatalog = SAMPLE_CATALOG) { const calls = { setEnabled: [] as Array<{ id: string; scope: McpScope; enabled: boolean; approve: boolean }>, install: [] as InstallAgentPluginRequest[], + addMarketplace: [] as Array<{ scope: McpScope; source: string }>, + browsed: [] as string[], }; const backend: PluginsBackend = { list: async () => structuredClone(state), + addMarketplace: async (scope, source) => { + calls.addMarketplace.push({ scope, source }); + state = { + ...state, + marketplaces: [ + ...state.marketplaces, + { id: source, name: source.split("/").pop() ?? source, source, scope, discovered: false }, + ], + }; + return structuredClone(state); + }, + removeMarketplace: async (_scope, source) => { + state = { ...state, marketplaces: state.marketplaces.filter((m) => m.source !== source) }; + return structuredClone(state); + }, setEnabled: async (id, scope, enabled, approveCapabilities = false) => { calls.setEnabled.push({ id, scope, enabled, approve: approveCapabilities }); state = { @@ -135,27 +152,30 @@ function createMockBackend(initial: AgentPluginCatalog = SAMPLE_CATALOG) { }; return structuredClone(state); }, - browseMarketplace: async (source) => ({ - source, - marketplaceName: "acme-mkt", - owner: "acme", - repo: "plugins", - gitRef: "main", - treeSha: "1111111111111111111111111111111111111111", - candidates: [ - { - name: "k8s-ops", - displayName: "k8s-ops", - version: "2.1.0", - description: "Kubernetes cluster diagnostics", - marketplace: "acme-mkt", - sourceSpec: "acme/plugins/k8s-ops#main", - subpath: "k8s-ops", - alreadyInstalledUser: false, - alreadyInstalledWorkspace: false, - }, - ], - }), + browseMarketplace: async (source) => { + calls.browsed.push(source); + return { + source, + marketplaceName: "acme-mkt", + owner: "acme", + repo: "plugins", + gitRef: "main", + treeSha: "1111111111111111111111111111111111111111", + candidates: [ + { + name: "k8s-ops", + displayName: "k8s-ops", + version: "2.1.0", + description: "Kubernetes cluster diagnostics", + marketplace: "acme-mkt", + sourceSpec: "acme/plugins/k8s-ops#main", + subpath: "k8s-ops", + alreadyInstalledUser: false, + alreadyInstalledWorkspace: false, + }, + ], + }; + }, preview: async (): Promise => ({ sourceKind: "github", owner: "acme", @@ -312,4 +332,26 @@ describe("AgentPluginsPage", () => { confirmWarnings: true, }); }); + + it("offers unregistered suggested plugin marketplaces for one-click browse or add", async () => { + const { backend, calls } = createMockBackend(); + render(); + + // `github/awesome-copilot` is already registered in SAMPLE_CATALOG, so only Claude Official Plugins is suggested. + expect(await screen.findByText("Claude Official Plugins")).toBeInTheDocument(); + expect(screen.queryByText("Awesome Copilot")).toBeNull(); + + // Open Marketplaces dialog and add Claude Official Plugins in one click. + fireEvent.click(screen.getByRole("button", { name: "Marketplaces (1)…" })); + const dialog = await screen.findByRole("dialog", { name: "Plugin Marketplaces" }); + expect(within(dialog).getByText("Suggested Marketplaces")).toBeInTheDocument(); + const suggestedRow = within(dialog).getByText("Claude Official Plugins").closest("div")?.parentElement; + expect(suggestedRow).not.toBeNull(); + fireEvent.click(within(suggestedRow!).getByRole("button", { name: "Add" })); + + await waitFor(() => + expect(calls.addMarketplace).toEqual([{ scope: "user", source: "anthropics/claude-plugins-official" }]), + ); + await waitFor(() => expect(within(dialog).queryByText("Suggested Marketplaces")).toBeNull()); + }); }); diff --git a/src/features/agents/AgentPluginsPage.tsx b/src/features/agents/AgentPluginsPage.tsx index 15645ca736..b00f5a010d 100644 --- a/src/features/agents/AgentPluginsPage.tsx +++ b/src/features/agents/AgentPluginsPage.tsx @@ -34,6 +34,7 @@ import { pluginFormatLabel, pluginGroupPath, pluginGroupTitle, + unregisteredSuggestedMarketplaces, usePluginsCatalog, type PluginsBackend, } from "./pluginsModel"; @@ -150,6 +151,11 @@ export function AgentPluginsPage({ backend = defaultPluginsBackend }: { backend? }); }, [catalog.plugins, query, tab]); + const suggestedMarketplaces = useMemo( + () => unregisteredSuggestedMarketplaces(catalog.marketplaces), + [catalog.marketplaces], + ); + const grouped = useMemo(() => { const order = Object.keys(PLUGIN_SOURCE_GROUPS) as AgentPluginSource[]; const out: Array<{ source: AgentPluginSource; scope: McpScope; items: AgentPluginState[]; key: string }> = []; @@ -246,7 +252,7 @@ export function AgentPluginsPage({ backend = defaultPluginsBackend }: { backend? - {catalog.marketplaces.length > 0 && ( + {(catalog.marketplaces.length > 0 || (suggestedMarketplaces.length > 0 && backend.browseMarketplace)) && (
{catalog.marketplaces.map((m) => ( @@ -260,6 +266,35 @@ export function AgentPluginsPage({ backend = defaultPluginsBackend }: { backend? )} ))} + {backend.browseMarketplace && + suggestedMarketplaces.map((preset) => ( + + + {preset.name} + + {backend.addMarketplace && ( + <> + + + + )} + + ))}
)} @@ -755,14 +790,16 @@ function MarketplacesDialog({ const [busy, setBusy] = useState(false); const [error, setError] = useState(null); - const add = async () => { - if (!backend.addMarketplace || !source.trim()) return; + const suggested = useMemo(() => unregisteredSuggestedMarketplaces(catalog.marketplaces), [catalog.marketplaces]); + + const addSource = async (targetSource: string) => { + if (!backend.addMarketplace || !targetSource.trim()) return; setBusy(true); setError(null); try { - const next = await backend.addMarketplace(scope, source.trim()); + const next = await backend.addMarketplace(scope, targetSource.trim()); onUpdated(next); - setSource(""); + if (targetSource === source) setSource(""); } catch (e: unknown) { setError(e instanceof Error ? e.message : String(e)); } finally { @@ -770,6 +807,8 @@ function MarketplacesDialog({ } }; + const add = () => addSource(source); + const remove = async (mScope: McpScope, mSource: string) => { if (!backend.removeMarketplace) return; setBusy(true); @@ -844,6 +883,37 @@ function MarketplacesDialog({ )} + {suggested.length > 0 && ( +
+ + Suggested Marketplaces + +
+ {suggested.map((preset) => ( +
+
+ {preset.name} + {preset.source} +
+
+ + +
+
+ ))} +
+
+ )} + {error && (
diff --git a/src/features/agents/McpRegistryBrowse.tsx b/src/features/agents/McpRegistryBrowse.tsx new file mode 100644 index 0000000000..35393acfc5 --- /dev/null +++ b/src/features/agents/McpRegistryBrowse.tsx @@ -0,0 +1,972 @@ +/** + * In-app MCP Registry browser (open MCP Registry v0.1 / v0 API) with one-click install & + * uninstall, custom registry support, runtime availability hints, and secret input prompts. + */ +import clsx from "clsx"; +import { useCallback, useEffect, useId, useMemo, useRef, useState } from "react"; +import type { + McpRegistryInputField, + McpRegistryInstallOption, + McpRegistryServer, + McpScope, + McpServer, + McpServerInput, +} from "@/bindings"; +import { formatMessage, useTx } from "@/platform/i18n"; +import { nextRequestId } from "@/platform/ipc"; +import { openExternalUrl } from "@/platform/openUrl"; +import { useProject } from "@/platform/project"; +import { Button, Dialog, Icon, IconButton, Input, Select, Spinner, T } from "@/ui"; +import { + MCP_REGISTRY_PRESETS, + canOneClickInstall, + findInstalledRegistryServer, + formatOptionPreview, + formatStarCount, + initialRegistryInputValues, + normalizeRegistryBaseUrl, + pickDefaultInstallOption, + resolveRegistryInstallInput, + type McpBackend, +} from "./mcpModel"; +import { providerIcon } from "./model"; +import page from "./SettingsPage.module.css"; +import styles from "./McpServers.module.css"; + +const CUSTOM_REGISTRY_ID = "__custom__"; +const SEARCH_DEBOUNCE_MS = 250; +const INFINITE_SCROLL_ROOT_MARGIN = "320px 0px"; + +function findScrollParent(el: HTMLElement): HTMLElement | null { + let cur = el.parentElement; + while (cur) { + const { overflowY } = window.getComputedStyle(cur); + if (overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay") { + return cur; + } + cur = cur.parentElement; + } + return null; +} + +interface Props { + backend: McpBackend; + query: string; + servers: readonly McpServer[]; + hasProject: boolean; + agentOptions: ReadonlyArray<{ id: string; name: string }>; + onInstalled: (next: McpServer[], serverName: string, scope: McpScope) => void; + onUninstalled: (next: McpServer[], serverName: string) => void; +} + +export function McpRegistryBrowse({ + backend, + query, + servers, + hasProject, + agentOptions, + onInstalled, + onUninstalled, +}: Props) { + const tx = useTx(); + const configuredUrl = useProject((s) => s.settings?.agents?.mcpRegistryUrl ?? ""); + const initialRegistryUrl = normalizeRegistryBaseUrl(configuredUrl); + const initialPreset = MCP_REGISTRY_PRESETS.find((p) => p.url === initialRegistryUrl); + + const [selectedSource, setSelectedSource] = useState(initialPreset ? initialPreset.url : CUSTOM_REGISTRY_ID); + const [customUrlDraft, setCustomUrlDraft] = useState(initialPreset ? "" : initialRegistryUrl); + const [activeRegistryUrl, setActiveRegistryUrl] = useState(initialRegistryUrl); + const [installScope, setInstallScope] = useState("user"); + const effectiveScope: McpScope = hasProject ? installScope : "user"; + const [items, setItems] = useState([]); + const [resolvedUrl, setResolvedUrl] = useState(initialRegistryUrl); + const [nextCursor, setNextCursor] = useState(null); + const [total, setTotal] = useState(null); + const [loading, setLoading] = useState(false); + const [loadingMore, setLoadingMore] = useState(false); + const [error, setError] = useState(null); + const [loadMoreError, setLoadMoreError] = useState(null); + const [busyKey, setBusyKey] = useState(null); + const [expanded, setExpanded] = useState>({}); + const [configuring, setConfiguring] = useState<{ + entry: McpRegistryServer; + optionId?: string; + } | null>(null); + const [savingRegistry, setSavingRegistry] = useState(false); + + const activeReqRef = useRef(null); + const generationRef = useRef(0); + const loadMoreInFlightRef = useRef(false); + const sentinelRef = useRef(null); + + const cancelInFlight = useCallback(() => { + if (activeReqRef.current !== null) { + const prev = activeReqRef.current; + activeReqRef.current = null; + void backend.cancelRequest?.(prev); + } + }, [backend]); + + const fetchPage = useCallback( + async (registryUrl: string, searchText: string, cursor: string | null, append: boolean): Promise => { + if (!backend.searchRegistry) return null; + cancelInFlight(); + const requestId = nextRequestId(); + activeReqRef.current = requestId; + const gen = ++generationRef.current; + + if (append) { + setLoadingMore(true); + setLoadMoreError(null); + } else { + setLoading(true); + setError(null); + setLoadMoreError(null); + } + + try { + const res = await backend.searchRegistry({ + registryUrl, + query: searchText.trim() || null, + cursor, + limit: 30, + requestId, + }); + if (generationRef.current !== gen) return null; + setResolvedUrl(res.registryUrl); + const returnedCursor = res.nextCursor ?? null; + // Stop auto-paging if a registry repeats the same cursor. + setNextCursor(append && returnedCursor === cursor ? null : returnedCursor); + setTotal(res.total ?? null); + setItems((prev) => { + if (!append) return res.servers; + const seen = new Set(prev.map((s) => s.name)); + return [...prev, ...res.servers.filter((s) => !seen.has(s.name))]; + }); + return res.registryUrl; + } catch (e: unknown) { + if (generationRef.current !== gen) return null; + const message = e instanceof Error ? e.message : String(e); + if (append) { + setLoadMoreError(message); + } else { + setError(message); + } + return null; + } finally { + if (generationRef.current === gen) { + activeReqRef.current = null; + setLoading(false); + setLoadingMore(false); + } + } + }, + [backend, cancelInFlight], + ); + + // Debounce search text changes; fetch immediately on initial mount or registry switch. + const prevRegistryRef = useRef(null); + const skipNextFetchRef = useRef(false); + useEffect(() => { + if (skipNextFetchRef.current) { + skipNextFetchRef.current = false; + prevRegistryRef.current = activeRegistryUrl; + return; + } + const registryChanged = prevRegistryRef.current !== activeRegistryUrl; + prevRegistryRef.current = activeRegistryUrl; + const delay = registryChanged || !query.trim() ? 0 : SEARCH_DEBOUNCE_MS; + const timer = window.setTimeout(() => { + void fetchPage(activeRegistryUrl, query, null, false); + }, delay); + return () => { + window.clearTimeout(timer); + }; + }, [activeRegistryUrl, query, fetchPage]); + + useEffect(() => cancelInFlight, [cancelInFlight]); + + // Pageless infinite scroll: prefetch the next page when the bottom sentinel nears view. + useEffect(() => { + if (!nextCursor || loading || loadingMore || loadMoreError) return; + if (typeof IntersectionObserver === "undefined") return; + const el = sentinelRef.current; + if (!el) return; + const root = findScrollParent(el); + const observer = new IntersectionObserver( + (entries) => { + if (!entries.some((entry) => entry.isIntersecting)) return; + if (loadMoreInFlightRef.current) return; + loadMoreInFlightRef.current = true; + void fetchPage(activeRegistryUrl, query, nextCursor, true).finally(() => { + loadMoreInFlightRef.current = false; + }); + }, + { root, rootMargin: INFINITE_SCROLL_ROOT_MARGIN }, + ); + observer.observe(el); + return () => observer.disconnect(); + }, [activeRegistryUrl, query, nextCursor, loading, loadingMore, loadMoreError, fetchPage]); + + const selectRegistrySource = (val: string) => { + setSelectedSource(val); + if (val !== CUSTOM_REGISTRY_ID) { + setActiveRegistryUrl(val); + void backend.saveRegistryUrl?.(val === MCP_REGISTRY_PRESETS[0].url ? "" : val); + } + }; + + const applyCustomRegistry = async () => { + const clean = customUrlDraft.trim(); + if (!clean) return; + setSavingRegistry(true); + setError(null); + try { + const verifiedUrl = await fetchPage(clean, query, null, false); + if (verifiedUrl) { + skipNextFetchRef.current = true; + setActiveRegistryUrl(verifiedUrl); + setCustomUrlDraft(verifiedUrl); + await backend.saveRegistryUrl?.(verifiedUrl); + } + } catch (e: unknown) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setSavingRegistry(false); + } + }; + + const runDirectInstall = async (entry: McpRegistryServer, option: McpRegistryInstallOption) => { + setBusyKey(entry.name); + setError(null); + try { + const input = resolveRegistryInstallInput(entry, option, initialRegistryInputValues(option), { + scope: effectiveScope, + registryUrl: resolvedUrl, + }); + const next = await backend.save(input); + onInstalled(next, input.name, input.scope); + } catch (e: unknown) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusyKey(null); + } + }; + + const runUninstall = async (entry: McpRegistryServer, installed: McpServer) => { + setBusyKey(entry.name); + setError(null); + try { + const next = await backend.remove(installed.id); + onUninstalled(next, installed.name); + } catch (e: unknown) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setBusyKey(null); + } + }; + + const registrySelectOptions = useMemo( + () => [ + ...MCP_REGISTRY_PRESETS.map((p) => ({ value: p.url, label: tx(p.label) })), + { value: CUSTOM_REGISTRY_ID, label: tx("Custom Registry…") }, + ], + [tx], + ); + + const scopeOptions = useMemo( + () => [ + { value: "user", label: tx("Install to Global (settings.toml)") }, + ...(hasProject ? [{ value: "workspace", label: tx("Install to Project (.openidea/settings.toml)") }] : []), + ], + [hasProject, tx], + ); + + if (!backend.searchRegistry) { + return ( +
+ MCP Registry browsing is unavailable in this environment. +
+ ); + } + + return ( +
+
+
+ setInstallScope(v as McpScope)} + /> +
+
+ {total !== null && !loading && ( + {formatMessage(tx("{count} servers"), { count: total })} + )} + void fetchPage(activeRegistryUrl, query, null, false)} + /> +
+
+ + {selectedSource === CUSTOM_REGISTRY_ID && ( +
+ setCustomUrlDraft(e.target.value)} + onKeyDown={(e) => { + if (e.key === "Enter") { + e.preventDefault(); + void applyCustomRegistry(); + } + }} + /> + +
+ )} + + {error && ( +
+ + {error} +
+ )} + + {loading && items.length === 0 ? ( +
+ + + Loading MCP registry… + +
+ ) : items.length === 0 && !error ? ( +
+ {query.trim() ? ( + formatMessage(tx("No MCP servers matching “{query}”."), { query: query.trim() }) + ) : ( + No MCP servers found in this registry. + )} +
+ ) : ( +
+ {items.map((entry) => { + const installed = findInstalledRegistryServer(servers, entry, effectiveScope); + const primaryOption = pickDefaultInstallOption(entry); + const oneClick = canOneClickInstall(entry); + const isBusy = busyKey === entry.name; + const isExpanded = !!expanded[entry.name]; + const previewText = primaryOption ? formatOptionPreview(primaryOption) : null; + + return ( +
+
+ + +
+ {installed ? ( + + ) : primaryOption ? ( + oneClick ? ( + + ) : ( + + ) + ) : ( + + Manual setup + + )} +
+
+ + {isExpanded && ( +
+
+ + Registry ID + + {entry.name} + {entry.publisher && ( + <> + + Publisher + + {entry.publisher} + + )} + {entry.license && ( + <> + + License + + {entry.license} + + )} +
+ + {entry.installOptions.length > 0 && ( +
+ {entry.installOptions.map((opt) => ( +
+
+
+ {opt.label} + {!opt.runtimeAvailable && opt.command && ( + + {formatMessage(tx("Missing {cmd} on PATH"), { cmd: opt.command })} + + )} + {opt.inputs.length > 0 && ( + + {formatMessage(tx("{count} inputs"), { count: opt.inputs.length })} + + )} +
+ {formatOptionPreview(opt)} +
+ {!installed && ( + + )} +
+ ))} +
+ )} + +
+
+ {entry.repositoryUrl && ( + + )} + {entry.websiteUrl && ( + + )} + {!installed && primaryOption && ( + + )} +
+
+
+ )} +
+ ); + })} +
+ )} + + {nextCursor && ( +
+ {loadingMore && ( +
+ + + Loading more servers… + +
+ )} + {loadMoreError && !loadingMore && ( +
+ + {loadMoreError} + +
+ )} +
+ )} + + {configuring && ( + setConfiguring(null)} + onInstalled={(next, name, scope) => { + setConfiguring(null); + onInstalled(next, name, scope); + }} + /> + )} +
+ ); +} + +function McpRegistryIcon({ iconUrl, iconDarkUrl }: { iconUrl?: string | null; iconDarkUrl?: string | null }) { + const [failedLightUrl, setFailedLightUrl] = useState(null); + const [failedDarkUrl, setFailedDarkUrl] = useState(null); + + const light = iconUrl && failedLightUrl !== iconUrl ? iconUrl : null; + const dark = iconDarkUrl && failedDarkUrl !== iconDarkUrl ? iconDarkUrl : null; + const effLight = light ?? dark; + const effDark = dark ?? light; + + if (!effLight) { + return ( + + ); + } + + if (effDark && effDark !== effLight) { + return ( + + ); + } + + return ( + + ); +} + +function McpRegistryInstallDialog({ + backend, + entry, + initialOptionId, + initialScope, + hasProject, + registryUrl, + agentOptions, + onClose, + onInstalled, +}: { + backend: McpBackend; + entry: McpRegistryServer; + initialOptionId?: string; + initialScope: McpScope; + hasProject: boolean; + registryUrl: string; + agentOptions: ReadonlyArray<{ id: string; name: string }>; + onClose: () => void; + onInstalled: (next: McpServer[], serverName: string, scope: McpScope) => void; +}) { + const tx = useTx(); + const baseId = useId(); + const initialOpt = + entry.installOptions.find((o) => o.id === initialOptionId) ?? + pickDefaultInstallOption(entry) ?? + entry.installOptions[0]!; + + const [optionId, setOptionId] = useState(initialOpt.id); + const option = entry.installOptions.find((o) => o.id === optionId) ?? initialOpt; + + const [scope, setScope] = useState(hasProject ? initialScope : "user"); + const [serverName, setServerName] = useState(entry.suggestedName); + const [valuesByOpt, setValuesByOpt] = useState>>(() => ({ + [initialOpt.id]: initialRegistryInputValues(initialOpt), + })); + const [selectedAgents, setSelectedAgents] = useState([]); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(null); + + const values = useMemo(() => valuesByOpt[option.id] ?? initialRegistryInputValues(option), [valuesByOpt, option]); + + const setFieldValue = (key: string, value: string) => { + setValuesByOpt((prev) => ({ + ...prev, + [option.id]: { + ...(prev[option.id] ?? initialRegistryInputValues(option)), + [key]: value, + }, + })); + }; + + const sortedInputs = useMemo( + () => [...option.inputs].sort((a, b) => Number(b.required) - Number(a.required)), + [option.inputs], + ); + + const previewInput: McpServerInput = useMemo( + () => + resolveRegistryInstallInput(entry, option, values, { + scope, + name: serverName, + agents: selectedAgents, + registryUrl, + maskSecrets: true, + }), + [entry, option, values, scope, serverName, selectedAgents, registryUrl], + ); + + const previewSummary = + previewInput.transport === "stdio" + ? [previewInput.command, ...(previewInput.args ?? [])].filter(Boolean).join(" ") + : `${previewInput.transport.toUpperCase()} · ${previewInput.url ?? ""}`; + + const missingRequired = useMemo( + () => sortedInputs.filter((f) => f.required && !(values[f.key] ?? "").trim()), + [sortedInputs, values], + ); + + const toggleAgent = (id: string) => { + setSelectedAgents((prev) => (prev.includes(id) ? prev.filter((a) => a !== id) : [...prev, id])); + }; + + const submit = async () => { + if (!serverName.trim()) { + setError(tx("Server name is required")); + return; + } + if (missingRequired.length > 0) { + setError(formatMessage(tx("Required field missing: {name}"), { name: missingRequired[0]!.label })); + return; + } + setSaving(true); + setError(null); + try { + const input = resolveRegistryInstallInput(entry, option, values, { + scope, + name: serverName, + agents: selectedAgents, + registryUrl, + }); + const next = await backend.save(input); + onInstalled(next, input.name, input.scope); + } catch (e: unknown) { + setError(e instanceof Error ? e.message : String(e)); + } finally { + setSaving(false); + } + }; + + const fieldId = (suffix: string) => `${baseId}-${suffix}`; + + return ( + + + + + } + > +
{ + e.preventDefault(); + void submit(); + }} + > + +
+ setServerName(e.target.value)} + placeholder={entry.suggestedName} + /> +
+ + +
+ ({ + value: o.id, + label: o.runtimeAvailable ? o.label : `${o.label} (${tx("runtime missing")})`, + }))} + onChange={setOptionId} + /> +
+ + )} + + + Preview + +
+
{previewSummary}
+ {!option.runtimeAvailable && option.command && ( + + {formatMessage(tx("`{cmd}` was not found on PATH. Install it before using this server."), { + cmd: option.command, + })} + + )} +
+ + {sortedInputs.length > 0 &&
} + + {sortedInputs.map((field: McpRegistryInputField) => ( + setFieldValue(field.key, val)} + /> + ))} + +
+ + + Agents + +
+
+ {agentOptions.map((agent) => { + const active = selectedAgents.includes(agent.id); + return ( + + ); + })} +
+ + Leave all unselected to enable this server for every agent. + +
+ + {error && ( +
+ + {error} +
+ )} + +
+ ); +} + +function RegistryInputRow({ + id, + field, + value, + scope, + onChange, +}: { + id: string; + field: McpRegistryInputField; + value: string; + scope: McpScope; + onChange: (value: string) => void; +}) { + const tx = useTx(); + return ( + <> + +
+ {field.choices.length > 0 ? ( + onChange(e.target.value)} + /> + )} + {(field.description || (field.secret && scope === "user")) && ( + + {field.description} + {field.description && field.secret && scope === "user" ? " · " : ""} + {field.secret && scope === "user" ? tx("Stored in OS Keychain") : ""} + + )} +
+ + ); +} diff --git a/src/features/agents/McpServers.module.css b/src/features/agents/McpServers.module.css index d10441214c..77767c8c95 100644 --- a/src/features/agents/McpServers.module.css +++ b/src/features/agents/McpServers.module.css @@ -349,3 +349,161 @@ color: var(--fg-muted); line-height: 1.4; } + +/* MCP Registry browser. */ +.registryExpandBtn { + align-items: flex-start; + gap: var(--space-2); +} + +.registryExpandBtn > svg { + margin-top: 9px; +} + +.registryIconBox { + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + width: 32px; + height: 32px; + margin-top: 1px; + border-radius: var(--radius-control); + background: var(--bg-elev); + box-shadow: inset 0 0 0 1px var(--border); + overflow: hidden; +} + +.registryIconImg { + width: 28px; + height: 28px; + object-fit: contain; + border-radius: var(--radius-small); +} + +.registryIconFallback { + color: var(--fg-muted); +} + +.registryIconDark { + display: none; +} + +:global(:root[data-theme^="dark"]) .registryIconLight { + display: none; +} + +:global(:root[data-theme^="dark"]) .registryIconDark { + display: block; +} + +.registryCount { + color: var(--fg-muted); + font-size: var(--fs-small); + font-variant-numeric: tabular-nums; +} + +.customRegistryBar { + display: flex; + align-items: center; + gap: var(--space-1-5); +} + +.loadingRow { + display: flex; + align-items: center; + gap: var(--space-2); + padding: 12px 14px; + border-radius: var(--radius-control); + background: var(--bg-elev); + box-shadow: inset 0 0 0 1px var(--border); + color: var(--fg-muted); + font-size: var(--fs-small); +} + +.registryDesc { + display: -webkit-box; + overflow: hidden; + -webkit-box-orient: vertical; + -webkit-line-clamp: 2; + color: var(--fg-secondary); + font-size: var(--fs-small); + line-height: 1.4; +} + +.registryOptions { + display: flex; + flex-direction: column; + gap: var(--space-1-5); + padding-top: var(--space-1); + border-top: 1px solid var(--border); +} + +.registryOptionRow { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-2); + padding: 6px 8px; + border-radius: var(--radius-small); + background: var(--bg-elev); + box-shadow: inset 0 0 0 1px var(--border); +} + +.registryOptionInfo { + display: flex; + flex-direction: column; + gap: var(--space-0-5); + min-width: 0; + flex: 1; +} + +.optionLabel { + font-weight: 600; + font-size: var(--fs-small); + color: var(--fg-strong); +} + +.scrollSentinel { + min-height: 1px; +} + +.loadingMoreRow { + display: flex; + align-items: center; + justify-content: center; + gap: var(--space-1-5); + padding: var(--space-2) 0; + color: var(--fg-muted); + font-size: var(--fs-small); +} + +.loadMoreError { + align-items: center; +} + +.loadMoreErrorText { + flex: 1; + min-width: 0; +} + +.previewBox { + padding: 6px 8px; + border-radius: var(--radius-small); + background: var(--bg-elev); + box-shadow: inset 0 0 0 1px var(--border); + color: var(--fg-strong); + font-family: var(--font-mono); + font-size: var(--fs-small); + overflow-wrap: anywhere; +} + +.runtimeWarn { + color: var(--warning); + font-size: var(--fs-small); + line-height: 1.4; +} + +.requiredMark { + color: var(--danger); +} diff --git a/src/features/agents/McpServersPage.tsx b/src/features/agents/McpServersPage.tsx index 8a9f5c5f47..0dc325f5ba 100644 --- a/src/features/agents/McpServersPage.tsx +++ b/src/features/agents/McpServersPage.tsx @@ -50,6 +50,7 @@ import { useMcpCatalog, type McpBackend, } from "./mcpModel"; +import { McpRegistryBrowse } from "./McpRegistryBrowse"; import { AGENT_PLUGINS_PAGE, providerIcon } from "./model"; import { useAgents } from "./store"; import page from "./SettingsPage.module.css"; @@ -58,9 +59,8 @@ import styles from "./McpServers.module.css"; export { defaultMcpBackend, type McpBackend }; const MCP_DOCS_URL = "https://modelcontextprotocol.io"; -const MCP_BROWSE_URL = "https://github.com/modelcontextprotocol/servers"; -type LevelTab = "all" | "user" | "workspace" | "discovered"; +type LevelTab = "all" | "user" | "workspace" | "discovered" | "browse"; interface SectionSpec { scope: McpScope; @@ -731,6 +731,15 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB ) : undefined, }, + ...(backend.searchRegistry + ? [ + { + id: "browse", + label: tx("Browse"), + text: tx("Browse"), + }, + ] + : []), ]} />
@@ -740,8 +749,8 @@ export function McpServersPage({ backend = defaultMcpBackend }: { backend?: McpB className={page.search} value={query} onChange={setQuery} - placeholder={tx("Type to search...")} - aria-label={tx("Search MCP servers")} + placeholder={tab === "browse" ? tx("Search MCP registry...") : tx("Type to search...")} + aria-label={tab === "browse" ? tx("Search MCP registry") : tx("Search MCP servers")} />