| 1 | //! MCP Registry sync tool. |
| 2 | //! |
| 3 | //! `registry_sync` fetches the MCP Registry index, filters stdio servers, |
| 4 | //! caches locally, and returns a summary. The snapshot is reused while |
| 5 | //! fresh (`INCREMENTAL_INTERVAL_SECS`); refresh is incremental via |
| 6 | //! `updated_since`, with a full pagination only when the snapshot is |
| 7 | //! missing or older than `FULL_RESYNC_INTERVAL_SECS`. Downloads run in the |
| 8 | //! background; the cache file is replaced atomically and doubles as the |
| 9 | //! launch-metadata store for `start_registry_mcp_server` (a failed sync |
| 10 | //! leaves the previous snapshot untouched). |
| 11 | //! |
| 12 | //! Upstream contract (MCP Registry, preview — breaking changes possible): |
| 13 | //! * List operation `GET /v0.1/servers` (cursor / limit / search / version |
| 14 | //! / include_deleted params): |
| 15 | //! <https://registry.modelcontextprotocol.io/docs#/operations/list-servers-v0.1> |
| 16 | //! OpenAPI source: <https://github.com/modelcontextprotocol/registry/blob/main/docs/reference/api/openapi.yaml> |
| 17 | //! * Aggregator integration guide (pagination format, server status |
| 18 | //! lifecycle): |
| 19 | //! <https://github.com/modelcontextprotocol/registry/blob/main/docs/modelcontextprotocol-io/registry-aggregators.mdx> |
| 20 | |
| 21 | use std::collections::{HashMap, HashSet}; |
| 22 | use std::path::{Path, PathBuf}; |
| 23 | use std::sync::{Arc, OnceLock}; |
| 24 | |
| 25 | use anyhow::Result; |
| 26 | use chrono::{DateTime, Utc}; |
| 27 | use serde::{Deserialize, Serialize}; |
| 28 | use serde_json::{Value, json}; |
| 29 | use tokio::sync::{Mutex as AsyncMutex, MutexGuard}; |
| 30 | |
| 31 | use crate::mcp::McpPool; |
| 32 | use crate::tools::spec::{ |
| 33 | ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec, |
| 34 | }; |
| 35 | use codewhale_util::utils::write_atomic; |
| 36 | |
| 37 | // === Registry API response types === |
| 38 | |
| 39 | #[derive(Deserialize)] |
| 40 | struct RegistryResponse { |
| 41 | servers: Vec<RegistryServerEntry>, |
| 42 | metadata: Option<RegistryMetadata>, |
| 43 | } |
| 44 | |
| 45 | #[derive(Deserialize)] |
| 46 | struct RegistryServerEntry { |
| 47 | server: RegistryServer, |
| 48 | // Registry-managed metadata. Carries the lifecycle `status` under the |
| 49 | // official extension key (see `RegistryOfficialMeta`); the |
| 50 | // publisher-provided subkey is deliberately not declared. |
| 51 | #[serde(rename = "_meta", default)] |
| 52 | meta: Option<RegistryResponseMeta>, |
| 53 | } |
| 54 | |
| 55 | impl RegistryServerEntry { |
| 56 | /// Lifecycle status reported by the official registry extension. |
| 57 | /// `"active"` (or an absent extension) keeps the entry; `"deprecated"`, |
| 58 | /// `"deleted"` and any status this client does not know retire it — the aggregator guide recommends dropping |
| 59 | /// `deleted` entries (moderation takedowns: spam/malware/illegal) from |
| 60 | /// downstream indexes, and we treat `deprecated` the same so the model |
| 61 | /// is only offered servers the publisher still stands behind. |
| 62 | /// <https://github.com/modelcontextprotocol/registry/blob/main/docs/modelcontextprotocol-io/registry-aggregators.mdx> |
| 63 | fn lifecycle_status(&self) -> Option<&str> { |
| 64 | self.meta |
| 65 | .as_ref() |
| 66 | .and_then(|m| m.official.as_ref()) |
| 67 | .and_then(|o| o.status.as_deref()) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | #[derive(Deserialize)] |
| 72 | struct RegistryResponseMeta { |
| 73 | #[serde(rename = "io.modelcontextprotocol.registry/official", default)] |
| 74 | official: Option<RegistryOfficialMeta>, |
| 75 | } |
| 76 | |
| 77 | /// `status` is required upstream (enum `active | deprecated | deleted`); |
| 78 | /// kept Optional here so a missing extension never fails a page parse. |
| 79 | #[derive(Deserialize)] |
| 80 | struct RegistryOfficialMeta { |
| 81 | #[serde(default)] |
| 82 | status: Option<String>, |
| 83 | } |
| 84 | |
| 85 | #[derive(Deserialize)] |
| 86 | struct RegistryServer { |
| 87 | name: String, |
| 88 | description: String, |
| 89 | // `title`, `version`, `repository` are deliberately not declared — |
| 90 | // the cache no longer carries them (see `McpRegistryServerEntry`) |
| 91 | // and serde silently drops any extra fields, so we don't pay to |
| 92 | // validate or store data we'd immediately throw away. All three are |
| 93 | // optional in the upstream 2025-12 schema. |
| 94 | #[serde(default)] |
| 95 | packages: Option<Vec<RegistryPackage>>, |
| 96 | } |
| 97 | |
| 98 | #[derive(Deserialize)] |
| 99 | struct RegistryPackage { |
| 100 | #[serde(rename = "registryType")] |
| 101 | registry_type: String, |
| 102 | identifier: String, |
| 103 | // The upstream OCI entries (e.g. docker.io/foo/bar:1.2.3) omit the |
| 104 | // top-level `version` field because the tag is the version. Mirror that |
| 105 | // — Optional, with a fallback that parses the trailing `:tag` from the |
| 106 | // identifier when missing. |
| 107 | #[serde(default)] |
| 108 | version: Option<String>, |
| 109 | // The upstream 2025-12 schema dropped `runtimeHint` for nearly every |
| 110 | // entry (35/36 in the first page omit it; the runner is implied by |
| 111 | // `registryType`). Keep it Optional and fall back to a registry-type |
| 112 | // table when absent. |
| 113 | #[serde(rename = "runtimeHint", default)] |
| 114 | runtime_hint: Option<String>, |
| 115 | // The upstream schema now models `transport` as an object: |
| 116 | // `{"type": "stdio"}`. Older docs showed a bare string. Accept both |
| 117 | // so a future flip-back doesn't break us. |
| 118 | #[serde(deserialize_with = "deserialize_transport", default)] |
| 119 | transport: Option<String>, |
| 120 | #[serde(default)] |
| 121 | #[serde(rename = "packageArguments")] |
| 122 | package_arguments: Vec<RegistryArg>, |
| 123 | #[serde( |
| 124 | rename = "runtimeArguments", |
| 125 | deserialize_with = "deserialize_runtime_arguments", |
| 126 | default |
| 127 | )] |
| 128 | runtime_arguments: Vec<String>, |
| 129 | /// Registry-provided environment requirements are intentionally kept |
| 130 | /// transient. Runtime-discovered servers have no configuration channel |
| 131 | /// for secrets/API keys, so any package declaring environment variables |
| 132 | /// is ineligible and never reaches the on-disk cache. |
| 133 | #[serde(rename = "environmentVariables", default)] |
| 134 | environment_variables: Value, |
| 135 | } |
| 136 | |
| 137 | impl RegistryPackage { |
| 138 | fn declares_environment_variables(&self) -> bool { |
| 139 | match &self.environment_variables { |
| 140 | Value::Null => false, |
| 141 | Value::Array(values) => !values.is_empty(), |
| 142 | Value::Object(values) => !values.is_empty(), |
| 143 | // Fail closed if a future Registry schema uses an unexpected shape. |
| 144 | _ => true, |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /// Deserialize `transport` as either a bare string (`"stdio"`) or an object |
| 150 | /// (`{"type": "stdio"}`). The MCP Registry 2025-12 schema ships the object |
| 151 | /// shape; older/draft docs showed the bare string. We accept both. |
| 152 | fn deserialize_transport<'de, D>(deserializer: D) -> Result<Option<String>, D::Error> |
| 153 | where |
| 154 | D: serde::Deserializer<'de>, |
| 155 | { |
| 156 | #[derive(Deserialize)] |
| 157 | #[serde(untagged)] |
| 158 | enum OneOrString { |
| 159 | Bare(String), |
| 160 | Wrapped { |
| 161 | #[serde(rename = "type")] |
| 162 | r#type: String, |
| 163 | }, |
| 164 | } |
| 165 | |
| 166 | let opt: Option<OneOrString> = Option::deserialize(deserializer)?; |
| 167 | Ok(opt.map(|v| match v { |
| 168 | OneOrString::Bare(s) => s, |
| 169 | OneOrString::Wrapped { r#type } => r#type, |
| 170 | })) |
| 171 | } |
| 172 | |
| 173 | /// Deserialize `runtimeArguments` as either `Vec<String>` (old schema) |
| 174 | /// or `Vec<{value, name, default, type, ...}>` (2025-12 schema). In the |
| 175 | /// object case we derive a string value from the available fields: |
| 176 | /// - Named args (`type: "named"`): `"{name} {default}"` or just `name` |
| 177 | /// - Positional args (`type: "positional"`): `default` |
| 178 | /// - Legacy objects with `value`: use `value` directly |
| 179 | fn deserialize_runtime_arguments<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error> |
| 180 | where |
| 181 | D: serde::Deserializer<'de>, |
| 182 | { |
| 183 | #[derive(Deserialize)] |
| 184 | #[serde(untagged)] |
| 185 | enum StringOrArg { |
| 186 | Bare(String), |
| 187 | Wrapped { |
| 188 | #[serde(default)] |
| 189 | value: Option<String>, |
| 190 | #[serde(default)] |
| 191 | name: Option<String>, |
| 192 | #[serde(default)] |
| 193 | default: Option<String>, |
| 194 | }, |
| 195 | } |
| 196 | |
| 197 | let raw: Vec<StringOrArg> = Vec::deserialize(deserializer)?; |
| 198 | let mut args = Vec::new(); |
| 199 | for arg in raw { |
| 200 | match arg { |
| 201 | StringOrArg::Bare(value) => args.push(value), |
| 202 | StringOrArg::Wrapped { |
| 203 | value: Some(value), .. |
| 204 | } => args.push(value), |
| 205 | StringOrArg::Wrapped { name, default, .. } => { |
| 206 | if let Some(name) = name { |
| 207 | args.push(name); |
| 208 | } |
| 209 | if let Some(default) = default { |
| 210 | args.push(default); |
| 211 | } |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | Ok(args) |
| 216 | } |
| 217 | |
| 218 | /// Derive a runtime hint from `registryType` when the upstream omits one. |
| 219 | /// Kept small on purpose: only the runtimes we know how to launch. |
| 220 | fn default_runtime_hint(registry_type: &str) -> Option<&'static str> { |
| 221 | match registry_type { |
| 222 | "npm" => Some("npx"), |
| 223 | "pypi" => Some("uvx"), |
| 224 | _ => None, |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | #[derive(Deserialize)] |
| 229 | struct RegistryArg { |
| 230 | // Positional arguments ship without a name — only `value` and |
| 231 | // `type`. Named arguments (`{"name": "--foo", "value": "bar", ...}`) |
| 232 | // carry it. Accept both: when missing, downstream code uses `value` |
| 233 | // as the arg name. |
| 234 | #[serde(default)] |
| 235 | name: Option<String>, |
| 236 | description: Option<String>, |
| 237 | // Upstream allows omitting `isRequired`; default false per spec. |
| 238 | #[serde(rename = "isRequired", default)] |
| 239 | is_required: bool, |
| 240 | // Upstream `type` discriminator (`"positional"` / `"named"`). Drives |
| 241 | // cmd-format decisions downstream. Renamed because `type` is a |
| 242 | // reserved word in Rust. |
| 243 | #[serde(rename = "type", default)] |
| 244 | kind: Option<String>, |
| 245 | #[serde(default)] |
| 246 | value: Option<String>, |
| 247 | default: Option<String>, |
| 248 | // `format` dropped — never read by any consumer. |
| 249 | } |
| 250 | |
| 251 | // === Cached index types === |
| 252 | |
| 253 | #[derive(Deserialize)] |
| 254 | struct RegistryMetadata { |
| 255 | #[serde(rename = "nextCursor")] |
| 256 | next_cursor: Option<String>, |
| 257 | } |
| 258 | |
| 259 | // === Cached index types === |
| 260 | // |
| 261 | // The cache file (`~/.codewhale/mcp-index.json`) is the on-disk source of |
| 262 | // truth for Registry-discovered local MCP launch metadata. |
| 263 | |
| 264 | /// Bumped whenever the cache shape changes. Lets the loader detect an old |
| 265 | /// cache file and trigger a full resync instead of failing to deserialize. |
| 266 | pub const MCP_REGISTRY_CACHE_VERSION: u32 = 6; |
| 267 | |
| 268 | #[derive(Serialize, Deserialize, Clone)] |
| 269 | pub struct McpRegistryIndex { |
| 270 | pub version: u32, |
| 271 | pub count: usize, |
| 272 | pub servers: Vec<McpRegistryServerEntry>, |
| 273 | /// RFC3339 timestamp of the last successful sync. Absent or older |
| 274 | /// than `INCREMENTAL_INTERVAL_SECS` triggers the next refresh; |
| 275 | /// older than `FULL_RESYNC_INTERVAL_SECS` makes it a full resync. |
| 276 | #[serde(default)] |
| 277 | pub synced_at: Option<DateTime<Utc>>, |
| 278 | } |
| 279 | |
| 280 | /// One Registry catalog entry exposed to the model for contextual selection. |
| 281 | #[derive(Serialize, Deserialize, Clone)] |
| 282 | pub struct DigestEntry { |
| 283 | pub name: String, |
| 284 | pub description: String, |
| 285 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 286 | pub required_args: Vec<McpRegistryArgEntry>, |
| 287 | } |
| 288 | |
| 289 | /// One cached server entry used by discovery and structured startup. |
| 290 | /// |
| 291 | /// Everything else that the upstream Registry ships (`title`, repository, |
| 292 | /// `packages[]`, optional named args, |
| 293 | /// runtime_arguments at package level) is dropped. Fixed positional |
| 294 | /// `packageArguments` (e.g. an `mcp` subcommand) are folded into |
| 295 | /// `run_command` at render time rather than kept as fields. |
| 296 | #[derive(Serialize, Deserialize, Clone)] |
| 297 | pub struct McpRegistryServerEntry { |
| 298 | pub name: String, |
| 299 | pub description: String, |
| 300 | pub launch: McpLaunchSpec, |
| 301 | } |
| 302 | |
| 303 | /// Host-owned launch data for one zero-environment stdio server. |
| 304 | #[derive(Serialize, Deserialize, Clone)] |
| 305 | pub struct McpLaunchSpec { |
| 306 | /// Template for the run command. The literal substring `<ARGS>` is |
| 307 | /// replaced by host-rendered structured argument values. |
| 308 | pub run_command: String, |
| 309 | pub required_args: Vec<McpRegistryArgEntry>, |
| 310 | } |
| 311 | |
| 312 | /// One CLI argument required at install time. `is_required` was dropped |
| 313 | /// because the cache only stores required args (others are filtered out |
| 314 | /// during sync). `kind` carries the upstream `type` discriminator |
| 315 | /// (`"positional"` vs `"named"`) so the cmd builder can decide whether |
| 316 | /// to emit `--name value` or just `value`. |
| 317 | #[derive(Serialize, Deserialize, Clone)] |
| 318 | pub struct McpRegistryArgEntry { |
| 319 | pub name: String, |
| 320 | pub kind: Option<String>, |
| 321 | pub description: Option<String>, |
| 322 | pub default: Option<String>, |
| 323 | } |
| 324 | |
| 325 | // === Tool implementation === |
| 326 | |
| 327 | pub struct McpSyncRegistry { |
| 328 | cache_path_override: Option<PathBuf>, |
| 329 | } |
| 330 | |
| 331 | impl McpSyncRegistry { |
| 332 | /// Default instance; resolves the cache under `dirs::home_dir()`. |
| 333 | pub(crate) fn new() -> Self { |
| 334 | Self { |
| 335 | cache_path_override: None, |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | /// Test hook: pin the cache file to an explicit path. `dirs::home_dir()` |
| 340 | /// resolves the OS profile directory on Windows via SHGetKnownFolderPath, |
| 341 | /// which no environment variable can redirect, so tests that need a |
| 342 | /// hermetic cache inject the path directly on every platform. |
| 343 | #[cfg(any(test, feature = "test-support"))] |
| 344 | pub fn with_cache_path(path: PathBuf) -> Self { |
| 345 | Self { |
| 346 | cache_path_override: Some(path), |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | fn cache_path(&self) -> Result<PathBuf, ToolError> { |
| 351 | match &self.cache_path_override { |
| 352 | Some(path) => Ok(path.clone()), |
| 353 | None => dirs::home_dir() |
| 354 | .ok_or_else(|| ToolError::execution_failed("Cannot determine home directory")) |
| 355 | .map(|h| h.join(".codewhale").join("mcp-index.json")), |
| 356 | } |
| 357 | } |
| 358 | } |
| 359 | |
| 360 | const REGISTRY_API: &str = "https://registry.modelcontextprotocol.io/v0.1/servers"; |
| 361 | const PER_PAGE: usize = 100; |
| 362 | const REQUEST_TIMEOUT_SECS: u64 = 30; |
| 363 | /// Inter-page delay: the upstream stalls under request bursts. |
| 364 | const PAGE_PACING_MS: u64 = 500; |
| 365 | /// Freshness window: within it `registry_sync` serves the cache with zero |
| 366 | /// network requests; past it a background refresh starts. |
| 367 | const INCREMENTAL_INTERVAL_SECS: i64 = 24 * 60 * 60; |
| 368 | /// Age at which the background refresh falls back to a full pagination, |
| 369 | /// reconciling servers that vanished from the listing entirely. |
| 370 | const FULL_RESYNC_INTERVAL_SECS: i64 = 30 * 24 * 60 * 60; |
| 371 | /// Identifies the client (RFC 9110); matches the crate-wide convention in |
| 372 | /// `web/fetch.rs`. HTTP hygiene, not a fix for upstream stalls. |
| 373 | const USER_AGENT: &str = concat!( |
| 374 | "Mozilla/5.0 (compatible; codewhale/", |
| 375 | env!("CARGO_PKG_VERSION"), |
| 376 | "; +https://github.com/codewhale-hq/CodeWhale)" |
| 377 | ); |
| 378 | /// Bounded retries for one sync. The on-disk cache only changes at the |
| 379 | /// final atomic replace, so a failed fetch (HTTP/parse error) never |
| 380 | /// mutates state and retrying is side-effect free. |
| 381 | const MAX_SYNC_ATTEMPTS: usize = 3; |
| 382 | /// Connect budget for Registry-launched servers. The 10s global default is |
| 383 | /// meant for pre-installed servers; Registry packages are typically fetched |
| 384 | /// on first launch via npx/uvx, which routinely exceeds it. |
| 385 | const REGISTRY_CONNECT_TIMEOUT_SECS: u64 = 60; |
| 386 | |
| 387 | fn cache_path() -> Result<PathBuf, ToolError> { |
| 388 | dirs::home_dir() |
| 389 | .ok_or_else(|| ToolError::execution_failed("Cannot determine home directory")) |
| 390 | .map(|h| h.join(".codewhale").join("mcp-index.json")) |
| 391 | } |
| 392 | |
| 393 | const MAX_REGISTRY_CACHE_BYTES: u64 = 64 * 1024 * 1024; |
| 394 | const MAX_REGISTRY_PAGES: usize = 500; |
| 395 | const MAX_REGISTRY_ENTRIES: usize = 50_000; |
| 396 | const MAX_REGISTRY_CURSOR_BYTES: usize = 1024; |
| 397 | const MAX_REGISTRY_PAGE_BYTES: usize = 8 * 1024 * 1024; |
| 398 | |
| 399 | fn read_cache(path: &Path) -> anyhow::Result<Option<McpRegistryIndex>> { |
| 400 | let Some(data) = crate::mcp::read_bounded_mcp_config_file(path, MAX_REGISTRY_CACHE_BYTES)? |
| 401 | else { |
| 402 | return Ok(None); |
| 403 | }; |
| 404 | serde_json::from_str(&data).map(Some).map_err(|error| { |
| 405 | anyhow::anyhow!("malformed MCP Registry cache {}: {error}", path.display()) |
| 406 | }) |
| 407 | } |
| 408 | |
| 409 | async fn read_cache_or_rebuild(path: &Path) -> Option<McpRegistryIndex> { |
| 410 | let owned = path.to_path_buf(); |
| 411 | let read = tokio::task::spawn_blocking(move || read_cache(&owned)) |
| 412 | .await |
| 413 | .unwrap_or_else(|error| Err(anyhow::anyhow!(error))); |
| 414 | read.unwrap_or_else(|error| { |
| 415 | tracing::warn!(target: "mcp", %error, "ignoring unreadable MCP Registry cache"); |
| 416 | None |
| 417 | }) |
| 418 | } |
| 419 | |
| 420 | fn is_retired(entry: &RegistryServerEntry) -> bool { |
| 421 | match entry.lifecycle_status() { |
| 422 | None | Some("active") => false, |
| 423 | Some("deprecated" | "deleted") => true, |
| 424 | Some(other) => { |
| 425 | tracing::warn!( |
| 426 | target: "mcp", |
| 427 | server = %entry.server.name, |
| 428 | status = %other, |
| 429 | "retiring MCP Registry server with unrecognized lifecycle status" |
| 430 | ); |
| 431 | true |
| 432 | } |
| 433 | } |
| 434 | } |
| 435 | |
| 436 | /// True when the snapshot is fresh enough to serve without a network |
| 437 | /// round-trip. Version mismatch or missing timestamp count as stale. |
| 438 | fn cache_is_fresh(cache: &McpRegistryIndex, now: DateTime<Utc>) -> bool { |
| 439 | if cache.version != MCP_REGISTRY_CACHE_VERSION { |
| 440 | return false; |
| 441 | } |
| 442 | cache.synced_at.is_some_and(|synced| { |
| 443 | now.signed_duration_since(synced).num_seconds() < INCREMENTAL_INTERVAL_SECS |
| 444 | }) |
| 445 | } |
| 446 | |
| 447 | /// Convert one fetched listing into launchable cache entries. Servers the |
| 448 | /// upstream marks `deleted`/`deprecated` are dropped (the aggregator guide |
| 449 | /// recommends removing `deleted` entries — moderation takedowns — from |
| 450 | /// downstream indexes), as is anything the structured launcher cannot run. |
| 451 | /// The cache is a full snapshot every sync, so this filtering is the whole |
| 452 | /// story: retired servers simply never enter the fresh index. |
| 453 | /// Status lives in registry-managed `_meta` |
| 454 | /// (`ServerResponse._meta["io.modelcontextprotocol.registry/official"] |
| 455 | /// .status`, enum `active | deprecated | deleted`). |
| 456 | /// <https://github.com/modelcontextprotocol/registry/blob/main/docs/reference/api/openapi.yaml> |
| 457 | fn viable_entries(entries: Vec<RegistryServerEntry>) -> Vec<McpRegistryServerEntry> { |
| 458 | entries |
| 459 | .into_iter() |
| 460 | .filter(|entry| !is_retired(entry)) |
| 461 | .filter_map(|entry| server_to_entry(entry.server)) |
| 462 | .collect() |
| 463 | } |
| 464 | |
| 465 | /// Render the run command template. Positional `packageArguments` with a |
| 466 | /// fixed literal (or defaulted) value are part of the invocation itself — |
| 467 | /// e.g. the `mcp` subcommand in `npx -y agentic-mermaid@0.1.2 mcp` — so |
| 468 | /// they are folded into the command right after the package spec. |
| 469 | /// `<ARGS>` is the splice point for everything user-supplied: positional |
| 470 | /// placeholders plus each `required_args` entry, rendered as named or |
| 471 | /// positional arguments by the structured Registry launcher. |
| 472 | fn build_run_command( |
| 473 | runtime_hint: &str, |
| 474 | identifier: &str, |
| 475 | version: &str, |
| 476 | runtime_arguments: &[String], |
| 477 | package_arguments: &[RegistryArg], |
| 478 | ) -> String { |
| 479 | let runtime = runtime_hint; |
| 480 | let mut normalized_runtime_arguments = runtime_arguments.to_vec(); |
| 481 | if runtime_hint == "npx" |
| 482 | && !normalized_runtime_arguments |
| 483 | .iter() |
| 484 | .any(|argument| matches!(argument.as_str(), "-y" | "--yes")) |
| 485 | { |
| 486 | normalized_runtime_arguments.insert(0, "-y".to_string()); |
| 487 | } |
| 488 | let mid = normalized_runtime_arguments |
| 489 | .iter() |
| 490 | .map(|argument| shell_words::quote(argument)) |
| 491 | .collect::<Vec<_>>() |
| 492 | .join(" "); |
| 493 | let mid_with_space = if mid.is_empty() { |
| 494 | String::new() |
| 495 | } else { |
| 496 | format!("{mid} ") |
| 497 | }; |
| 498 | let (sep, tail) = match runtime_hint { |
| 499 | "npx" => ("@", version.to_string()), |
| 500 | "uvx" => ("==", version.to_string()), |
| 501 | _ => return String::new(), |
| 502 | }; |
| 503 | // Upstream positional packageArguments ship without a `name`; named |
| 504 | // args always carry one. A nameless arg with a literal `value` (or a |
| 505 | // `default`) is a fixed token of the invocation, not user input — |
| 506 | // dropping it renders a command that cannot start the server (the |
| 507 | // agentic-mermaid `mcp` subcommand bug). |
| 508 | let fixed: Vec<String> = package_arguments |
| 509 | .iter() |
| 510 | .filter(|a| !a.is_required) |
| 511 | .filter(|a| a.name.is_none()) |
| 512 | .filter_map(|a| a.value.as_deref().or(a.default.as_deref())) |
| 513 | .map(|value| shell_words::quote(value).into_owned()) |
| 514 | .collect(); |
| 515 | let fixed_str = if fixed.is_empty() { |
| 516 | String::new() |
| 517 | } else { |
| 518 | format!(" {}", fixed.join(" ")) |
| 519 | }; |
| 520 | let package_spec = format!("{identifier}{sep}{tail}"); |
| 521 | let package = shell_words::quote(&package_spec); |
| 522 | format!("{runtime} {mid_with_space}{package}{fixed_str} <ARGS>") |
| 523 | } |
| 524 | |
| 525 | fn build_launch_spec( |
| 526 | runtime_hint: &str, |
| 527 | identifier: &str, |
| 528 | version: &str, |
| 529 | pkg: &RegistryPackage, |
| 530 | ) -> McpLaunchSpec { |
| 531 | McpLaunchSpec { |
| 532 | run_command: build_run_command( |
| 533 | runtime_hint, |
| 534 | identifier, |
| 535 | version, |
| 536 | &pkg.runtime_arguments, |
| 537 | &pkg.package_arguments, |
| 538 | ), |
| 539 | required_args: pkg |
| 540 | .package_arguments |
| 541 | .iter() |
| 542 | .filter(|a| a.is_required) |
| 543 | .enumerate() |
| 544 | .map(|(index, a)| McpRegistryArgEntry { |
| 545 | // Positional args omit `name` upstream; fall back to the |
| 546 | // value so the cache still carries something the cmd |
| 547 | // builder can render. |
| 548 | name: a |
| 549 | .name |
| 550 | .clone() |
| 551 | .or_else(|| a.value.clone()) |
| 552 | .unwrap_or_else(|| format!("arg_{}", index + 1)), |
| 553 | kind: a.kind.clone(), |
| 554 | description: a.description.clone(), |
| 555 | default: a.default.clone(), |
| 556 | }) |
| 557 | .collect(), |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | fn server_to_entry(server: RegistryServer) -> Option<McpRegistryServerEntry> { |
| 562 | // We only need the FIRST viable stdio package per server for |
| 563 | // launch metadata; everything beyond it would just duplicate |
| 564 | // info. Filter to stdio, resolve runtime_hint + version, and stop |
| 565 | // at the first hit. |
| 566 | let first_pkg = server |
| 567 | .packages |
| 568 | .unwrap_or_default() |
| 569 | .into_iter() |
| 570 | .filter(|p| p.transport.as_deref() == Some("stdio")) |
| 571 | .filter(|p| !p.declares_environment_variables()) |
| 572 | // The automatic launcher currently has deterministic install/run |
| 573 | // semantics for package-manager-backed npm and PyPI entries only. |
| 574 | .filter(|p| matches!(p.registry_type.as_str(), "npm" | "pypi")) |
| 575 | .find_map(|p| { |
| 576 | let expected_hint = default_runtime_hint(&p.registry_type)?; |
| 577 | let hint = p |
| 578 | .runtime_hint |
| 579 | .clone() |
| 580 | .unwrap_or_else(|| expected_hint.to_string()); |
| 581 | if hint != expected_hint { |
| 582 | return None; |
| 583 | } |
| 584 | let version = p.version.clone()?; |
| 585 | Some((p, hint, version)) |
| 586 | }); |
| 587 | |
| 588 | let (pkg, hint, version) = first_pkg?; |
| 589 | |
| 590 | Some(McpRegistryServerEntry { |
| 591 | name: server.name, |
| 592 | description: server.description, |
| 593 | launch: build_launch_spec(&hint, &pkg.identifier, &version, &pkg), |
| 594 | }) |
| 595 | } |
| 596 | |
| 597 | /// Prompt attached to every `registry_sync` result. |
| 598 | /// |
| 599 | /// A scored list is not a verdict. This used to read "you must call |
| 600 | /// start_registry_mcp_server ... before using shell commands, local programs, |
| 601 | /// custom code, or a manual implementation", which turned any near-miss row |
| 602 | /// into an obligation: a turn that only had to write an HTML file and read a |
| 603 | /// fixture matched a browser-automation server and spent itself on starting |
| 604 | /// that server. The result now describes the list and leaves the choice with |
| 605 | /// the model, while keeping the one instruction the host actually depends on — |
| 606 | /// start an entry through `start_registry_mcp_server`, never by running its |
| 607 | /// package command through the shell. |
| 608 | const REGISTRY_FIRST_PROMPT: &str = concat!( |
| 609 | "These are the top scored matches for your query from the local Registry ", |
| 610 | "snapshot; the full catalog stays on the host. A match is only worth ", |
| 611 | "starting when it covers a capability you do not already have — if an ", |
| 612 | "available tool, a project script, or a few lines of local code already ", |
| 613 | "does the job, use that and ignore these results. To start one, call ", |
| 614 | "start_registry_mcp_server with its exact name; never install or run its ", |
| 615 | "package command through the shell. If nothing here covers the missing ", |
| 616 | "capability, refine the query once, then continue with local tools.", |
| 617 | ); |
| 618 | |
| 619 | /// Host-side cap on model-visible Registry matches. The complete catalog |
| 620 | /// stays on disk; only this many matched entries ever reach the model. |
| 621 | const MAX_REGISTRY_MATCHES: usize = 8; |
| 622 | |
| 623 | #[derive(Serialize)] |
| 624 | struct RegistryCatalogResult { |
| 625 | instruction: &'static str, |
| 626 | /// Total entries in the on-disk catalog (reported, never shipped). |
| 627 | total: usize, |
| 628 | query: String, |
| 629 | servers: Vec<DigestEntry>, |
| 630 | } |
| 631 | |
| 632 | fn catalog_from_cache(cache: &McpRegistryIndex, query: &str) -> RegistryCatalogResult { |
| 633 | let servers = search_registry_entries(&cache.servers, query, MAX_REGISTRY_MATCHES); |
| 634 | RegistryCatalogResult { |
| 635 | instruction: REGISTRY_FIRST_PROMPT, |
| 636 | total: cache.servers.len(), |
| 637 | query: query.to_string(), |
| 638 | servers, |
| 639 | } |
| 640 | } |
| 641 | |
| 642 | /// Deterministic host-side scoring: name hits outrank description hits, |
| 643 | /// exact name match outranks substring, ties break alphabetically. The model |
| 644 | /// never sees the un-matched remainder of the catalog. |
| 645 | fn search_registry_entries( |
| 646 | entries: &[McpRegistryServerEntry], |
| 647 | query: &str, |
| 648 | limit: usize, |
| 649 | ) -> Vec<DigestEntry> { |
| 650 | let terms = query |
| 651 | .split_whitespace() |
| 652 | .map(str::to_ascii_lowercase) |
| 653 | .filter(|term| !term.is_empty()) |
| 654 | .collect::<Vec<_>>(); |
| 655 | let mut scored = entries |
| 656 | .iter() |
| 657 | .map(|server| { |
| 658 | let name = server.name.to_ascii_lowercase(); |
| 659 | let description = server.description.to_ascii_lowercase(); |
| 660 | let mut score = 0u32; |
| 661 | for term in &terms { |
| 662 | if name == *term { |
| 663 | score = score.saturating_add(100); |
| 664 | } else if name.contains(term) { |
| 665 | score = score.saturating_add(50); |
| 666 | } |
| 667 | if description.contains(term) { |
| 668 | score = score.saturating_add(10); |
| 669 | } |
| 670 | } |
| 671 | (score, server) |
| 672 | }) |
| 673 | .filter(|(score, _)| *score > 0) |
| 674 | .collect::<Vec<_>>(); |
| 675 | scored.sort_by(|(a_score, a), (b_score, b)| { |
| 676 | b_score.cmp(a_score).then_with(|| a.name.cmp(&b.name)) |
| 677 | }); |
| 678 | scored |
| 679 | .into_iter() |
| 680 | .take(limit) |
| 681 | .map(|(_, server)| DigestEntry { |
| 682 | name: server.name.clone(), |
| 683 | description: server.description.clone(), |
| 684 | required_args: server.launch.required_args.clone(), |
| 685 | }) |
| 686 | .collect() |
| 687 | } |
| 688 | |
| 689 | /// Always fast: serve the local snapshot and start a background download |
| 690 | /// only when it is missing or stale. |
| 691 | async fn load_registry_catalog( |
| 692 | path: &Path, |
| 693 | query: &str, |
| 694 | ) -> Result<RegistryCatalogResult, ToolError> { |
| 695 | let existing = read_cache_or_rebuild(path).await; |
| 696 | let fresh = existing |
| 697 | .as_ref() |
| 698 | .is_some_and(|cache| cache_is_fresh(cache, Utc::now())); |
| 699 | if !fresh { |
| 700 | spawn_background_sync(path); |
| 701 | } |
| 702 | Ok(catalog_for_snapshot(existing, query)) |
| 703 | } |
| 704 | |
| 705 | /// Decide what `registry_sync` returns: the scored top matches for the |
| 706 | /// query from the cached entries (they pin their own package versions, so |
| 707 | /// snapshot age is irrelevant), or an empty match set when no snapshot |
| 708 | /// exists yet. |
| 709 | fn catalog_for_snapshot(existing: Option<McpRegistryIndex>, query: &str) -> RegistryCatalogResult { |
| 710 | match existing { |
| 711 | Some(cache) => catalog_from_cache(&cache, query), |
| 712 | // No snapshot yet: an empty match set has no candidates to act on; |
| 713 | // a background sync has already been queued. |
| 714 | None => RegistryCatalogResult { |
| 715 | instruction: "", |
| 716 | total: 0, |
| 717 | query: query.to_string(), |
| 718 | servers: Vec::new(), |
| 719 | }, |
| 720 | } |
| 721 | } |
| 722 | |
| 723 | /// Process-wide lock so at most one background sync runs at a time; |
| 724 | /// released when the sync settles, so the next call can retry. |
| 725 | fn try_acquire_sync_permit() -> Option<MutexGuard<'static, ()>> { |
| 726 | static SYNC_GUARD: OnceLock<AsyncMutex<()>> = OnceLock::new(); |
| 727 | SYNC_GUARD |
| 728 | .get_or_init(|| AsyncMutex::new(())) |
| 729 | .try_lock() |
| 730 | .ok() |
| 731 | } |
| 732 | |
| 733 | /// Start the download in the background. Returns false when one is |
| 734 | /// already running. |
| 735 | fn spawn_background_sync(path: &Path) -> bool { |
| 736 | let Some(permit) = try_acquire_sync_permit() else { |
| 737 | return false; |
| 738 | }; |
| 739 | let path = path.to_path_buf(); |
| 740 | tokio::spawn(async move { |
| 741 | if let Err(error) = sync_once(&path).await { |
| 742 | tracing::warn!("background Registry sync failed: {error}"); |
| 743 | } |
| 744 | drop(permit); |
| 745 | }); |
| 746 | true |
| 747 | } |
| 748 | |
| 749 | struct RegistryFetchLimits { |
| 750 | max_pages: usize, |
| 751 | max_entries: usize, |
| 752 | max_page_bytes: usize, |
| 753 | page_pacing: std::time::Duration, |
| 754 | } |
| 755 | |
| 756 | async fn read_bounded_response_bytes( |
| 757 | mut resp: reqwest::Response, |
| 758 | max_bytes: usize, |
| 759 | ) -> Result<Vec<u8>, ToolError> { |
| 760 | if let Some(len) = resp.content_length() |
| 761 | && len > max_bytes as u64 |
| 762 | { |
| 763 | return Err(ToolError::execution_failed(format!( |
| 764 | "Registry response body exceeds {max_bytes} bytes" |
| 765 | ))); |
| 766 | } |
| 767 | let mut bytes = Vec::new(); |
| 768 | while let Some(chunk) = resp |
| 769 | .chunk() |
| 770 | .await |
| 771 | .map_err(|e| ToolError::execution_failed(format!("Registry body: {e}")))? |
| 772 | { |
| 773 | if bytes.len().saturating_add(chunk.len()) > max_bytes { |
| 774 | return Err(ToolError::execution_failed(format!( |
| 775 | "Registry response body exceeds {max_bytes} bytes" |
| 776 | ))); |
| 777 | } |
| 778 | bytes.extend_from_slice(&chunk); |
| 779 | } |
| 780 | Ok(bytes) |
| 781 | } |
| 782 | |
| 783 | /// Paginate the listing; with `updated_since`, only servers updated after |
| 784 | /// it. The filter MUST be repeated on every page — the cursor alone does |
| 785 | /// not carry it (verified against the live API). Never writes anything. |
| 786 | async fn fetch_registry_entries( |
| 787 | client: &reqwest::Client, |
| 788 | updated_since: Option<DateTime<Utc>>, |
| 789 | ) -> Result<Vec<RegistryServerEntry>, ToolError> { |
| 790 | fetch_registry_entries_from( |
| 791 | client, |
| 792 | REGISTRY_API, |
| 793 | updated_since, |
| 794 | RegistryFetchLimits { |
| 795 | max_pages: MAX_REGISTRY_PAGES, |
| 796 | max_entries: MAX_REGISTRY_ENTRIES, |
| 797 | max_page_bytes: MAX_REGISTRY_PAGE_BYTES, |
| 798 | page_pacing: std::time::Duration::from_millis(PAGE_PACING_MS), |
| 799 | }, |
| 800 | ) |
| 801 | .await |
| 802 | } |
| 803 | |
| 804 | async fn fetch_registry_entries_from( |
| 805 | client: &reqwest::Client, |
| 806 | base_url: &str, |
| 807 | updated_since: Option<DateTime<Utc>>, |
| 808 | limits: RegistryFetchLimits, |
| 809 | ) -> Result<Vec<RegistryServerEntry>, ToolError> { |
| 810 | let mut all_entries: Vec<RegistryServerEntry> = Vec::new(); |
| 811 | let mut cursor: Option<String> = None; |
| 812 | let mut seen_cursors = HashSet::new(); |
| 813 | for _page in 0..limits.max_pages { |
| 814 | let mut url = format!("{base_url}?version=latest&limit={PER_PAGE}"); |
| 815 | if let Some(since) = updated_since { |
| 816 | url.push_str(&format!( |
| 817 | "&updated_since={}", |
| 818 | urlencoding::encode(&since.to_rfc3339()) |
| 819 | )); |
| 820 | } |
| 821 | if let Some(ref c) = cursor { |
| 822 | url.push_str(&format!("&cursor={}", urlencoding::encode(c))); |
| 823 | } |
| 824 | let resp = client |
| 825 | .get(&url) |
| 826 | .send() |
| 827 | .await |
| 828 | .and_then(reqwest::Response::error_for_status) |
| 829 | .map_err(|e| ToolError::execution_failed(format!("Registry API: {e}")))?; |
| 830 | let bytes = read_bounded_response_bytes(resp, limits.max_page_bytes).await?; |
| 831 | let body: RegistryResponse = serde_json::from_slice(&bytes) |
| 832 | .map_err(|e| ToolError::execution_failed(format!("Registry JSON parse: {e}")))?; |
| 833 | all_entries.extend(body.servers); |
| 834 | if all_entries.len() > limits.max_entries { |
| 835 | return Err(ToolError::execution_failed(format!( |
| 836 | "Registry listing exceeds {} entries", |
| 837 | limits.max_entries |
| 838 | ))); |
| 839 | } |
| 840 | cursor = body.metadata.and_then(|m| m.next_cursor); |
| 841 | let Some(next) = &cursor else { |
| 842 | return Ok(all_entries); |
| 843 | }; |
| 844 | if next.len() > MAX_REGISTRY_CURSOR_BYTES || !seen_cursors.insert(next.clone()) { |
| 845 | return Err(ToolError::execution_failed( |
| 846 | "Registry pagination returned an oversized or repeated cursor", |
| 847 | )); |
| 848 | } |
| 849 | if !limits.page_pacing.is_zero() { |
| 850 | tokio::time::sleep(limits.page_pacing).await; |
| 851 | } |
| 852 | } |
| 853 | Err(ToolError::execution_failed(format!( |
| 854 | "Registry listing exceeds {} pages", |
| 855 | limits.max_pages |
| 856 | ))) |
| 857 | } |
| 858 | |
| 859 | /// Refresh strategy: full listing, or `updated_since` delta from the |
| 860 | /// snapshot's last sync (full when the snapshot is missing, legacy, or |
| 861 | /// older than `FULL_RESYNC_INTERVAL_SECS`). |
| 862 | #[derive(Debug, PartialEq)] |
| 863 | enum SyncStrategy { |
| 864 | Full, |
| 865 | Incremental { since: DateTime<Utc> }, |
| 866 | } |
| 867 | |
| 868 | fn sync_strategy(cache: Option<&McpRegistryIndex>, now: DateTime<Utc>) -> SyncStrategy { |
| 869 | match cache { |
| 870 | None => SyncStrategy::Full, |
| 871 | Some(cache) if cache.version != MCP_REGISTRY_CACHE_VERSION => SyncStrategy::Full, |
| 872 | Some(cache) => match cache.synced_at { |
| 873 | None => SyncStrategy::Full, |
| 874 | Some(synced) |
| 875 | if now.signed_duration_since(synced).num_seconds() >= FULL_RESYNC_INTERVAL_SECS => |
| 876 | { |
| 877 | SyncStrategy::Full |
| 878 | } |
| 879 | Some(synced) => SyncStrategy::Incremental { since: synced }, |
| 880 | }, |
| 881 | } |
| 882 | } |
| 883 | |
| 884 | /// Merge an incremental listing into the snapshot (in memory). Delta |
| 885 | /// entries replace by name; retired or no-longer-launchable servers are |
| 886 | /// dropped; everything else keeps its cached copy. |
| 887 | fn merge_incremental_entries( |
| 888 | base: &[McpRegistryServerEntry], |
| 889 | entries: Vec<RegistryServerEntry>, |
| 890 | ) -> Vec<McpRegistryServerEntry> { |
| 891 | let mut merged: HashMap<String, McpRegistryServerEntry> = base |
| 892 | .iter() |
| 893 | .map(|entry| (entry.name.clone(), entry.clone())) |
| 894 | .collect(); |
| 895 | for entry in entries { |
| 896 | let name = entry.server.name.clone(); |
| 897 | if is_retired(&entry) { |
| 898 | merged.remove(&name); |
| 899 | continue; |
| 900 | } |
| 901 | match server_to_entry(entry.server) { |
| 902 | Some(updated) => { |
| 903 | merged.insert(name, updated); |
| 904 | } |
| 905 | None => { |
| 906 | merged.remove(&name); |
| 907 | } |
| 908 | } |
| 909 | } |
| 910 | merged.into_values().collect() |
| 911 | } |
| 912 | |
| 913 | /// Fetch the index (full or incremental), assemble the next snapshot in |
| 914 | /// memory, and atomically replace the cache file. Retried on failure; |
| 915 | /// the old snapshot survives any failed sync. |
| 916 | async fn sync_once(path: &Path) -> Result<(), ToolError> { |
| 917 | let client = crate::platform_client_builder() |
| 918 | .user_agent(USER_AGENT) |
| 919 | .timeout(std::time::Duration::from_secs(REQUEST_TIMEOUT_SECS)) |
| 920 | .build() |
| 921 | .map_err(|e| ToolError::execution_failed(format!("HTTP client: {e}")))?; |
| 922 | |
| 923 | let now = Utc::now(); |
| 924 | let cached = read_cache_or_rebuild(path).await; |
| 925 | let strategy = sync_strategy(cached.as_ref(), now); |
| 926 | let updated_since = match strategy { |
| 927 | SyncStrategy::Full => None, |
| 928 | SyncStrategy::Incremental { since } => Some(since), |
| 929 | }; |
| 930 | |
| 931 | let mut last_error: Option<ToolError> = None; |
| 932 | let mut servers: Option<Vec<McpRegistryServerEntry>> = None; |
| 933 | for _attempt in 0..MAX_SYNC_ATTEMPTS { |
| 934 | match fetch_registry_entries(&client, updated_since).await { |
| 935 | Ok(entries) => { |
| 936 | servers = Some(match strategy { |
| 937 | SyncStrategy::Full => viable_entries(entries), |
| 938 | SyncStrategy::Incremental { .. } => merge_incremental_entries( |
| 939 | &cached.expect("incremental needs a cache").servers, |
| 940 | entries, |
| 941 | ), |
| 942 | }); |
| 943 | break; |
| 944 | } |
| 945 | Err(error) => last_error = Some(error), |
| 946 | } |
| 947 | } |
| 948 | let servers = servers.ok_or_else(|| { |
| 949 | last_error.unwrap_or_else(|| ToolError::execution_failed("Registry sync failed")) |
| 950 | })?; |
| 951 | let index = McpRegistryIndex { |
| 952 | version: MCP_REGISTRY_CACHE_VERSION, |
| 953 | count: servers.len(), |
| 954 | servers, |
| 955 | synced_at: Some(now), |
| 956 | }; |
| 957 | // Blocking filesystem work (including `write_atomic`'s publish-retry) |
| 958 | // runs on the blocking pool — tool handlers execute on the Tokio |
| 959 | // runtime (blocking-call convention, #6149). |
| 960 | let json_str = serde_json::to_string_pretty(&index) |
| 961 | .map_err(|e| ToolError::execution_failed(format!("Serialize: {e}")))?; |
| 962 | let path = path.to_path_buf(); |
| 963 | tokio::task::spawn_blocking(move || { |
| 964 | if let Some(parent) = path.parent() { |
| 965 | std::fs::create_dir_all(parent) |
| 966 | .map_err(|e| ToolError::execution_failed(format!("Create cache dir: {e}")))?; |
| 967 | } |
| 968 | write_atomic(&path, json_str.as_bytes()) |
| 969 | .map_err(|e| ToolError::execution_failed(format!("Write cache: {e}"))) |
| 970 | }) |
| 971 | .await |
| 972 | .map_err(|e| ToolError::execution_failed(format!("Write cache task: {e}")))??; |
| 973 | Ok(()) |
| 974 | } |
| 975 | |
| 976 | #[async_trait::async_trait] |
| 977 | impl ToolSpec for McpSyncRegistry { |
| 978 | fn name(&self) -> &str { |
| 979 | "registry_sync" |
| 980 | } |
| 981 | |
| 982 | fn description(&self) -> &str { |
| 983 | "Search installable local MCP servers for a capability this session \ |
| 984 | does not already have, and return at most eight scored matches; the \ |
| 985 | full Registry index stays host-side. Describe the missing capability \ |
| 986 | in the query. The index contains only stdio packages that declare no \ |
| 987 | environment variables or API keys. The Registry is a fallback for a \ |
| 988 | specific missing capability you would otherwise install or reimplement \ |
| 989 | (a converter, an external database or service, a protocol client) — \ |
| 990 | prefer tools already in this catalog, project scripts, and ordinary \ |
| 991 | local work first, and do not search for work you can already do. To \ |
| 992 | use a match, call start_registry_mcp_server with its exact name; do \ |
| 993 | not run its package command through the shell. If nothing matches, \ |
| 994 | refine the query once, then continue with local tools. If a call \ |
| 995 | reports it only loaded this schema, retry once with that schema." |
| 996 | } |
| 997 | |
| 998 | fn input_schema(&self) -> Value { |
| 999 | json!({ |
| 1000 | "type": "object", |
| 1001 | "properties": { |
| 1002 | "query": { |
| 1003 | "type": "string", |
| 1004 | "description": "Required. The specialized capability to \ |
| 1005 | search for, e.g. 'convert PDF to markdown' or 'postgres \ |
| 1006 | database access'. Matched server names and descriptions \ |
| 1007 | are scored host-side; at most eight matches return." |
| 1008 | } |
| 1009 | }, |
| 1010 | "required": ["query"], |
| 1011 | "additionalProperties": false |
| 1012 | }) |
| 1013 | } |
| 1014 | |
| 1015 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 1016 | vec![ToolCapability::Network] |
| 1017 | } |
| 1018 | |
| 1019 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 1020 | ApprovalRequirement::Auto |
| 1021 | } |
| 1022 | |
| 1023 | fn supports_parallel(&self) -> bool { |
| 1024 | true |
| 1025 | } |
| 1026 | |
| 1027 | async fn execute(&self, input: Value, _ctx: &ToolContext) -> Result<ToolResult, ToolError> { |
| 1028 | let query = input |
| 1029 | .get("query") |
| 1030 | .and_then(Value::as_str) |
| 1031 | .map(str::trim) |
| 1032 | .filter(|query| !query.is_empty()) |
| 1033 | .ok_or_else(|| { |
| 1034 | ToolError::invalid_input( |
| 1035 | "registry_sync requires a non-empty 'query' describing the \ |
| 1036 | specialized capability to search for.", |
| 1037 | ) |
| 1038 | })?; |
| 1039 | let path = self.cache_path()?; |
| 1040 | let result = load_registry_catalog(&path, query).await?; |
| 1041 | let json = serde_json::to_string(&result) |
| 1042 | .map_err(|e| ToolError::execution_failed(format!("Serialize: {e}")))?; |
| 1043 | Ok(ToolResult::success(json)) |
| 1044 | } |
| 1045 | } |
| 1046 | |
| 1047 | /// Start one zero-environment stdio server selected from the Registry cache. |
| 1048 | /// The model supplies a Registry identity and structured CLI values; the host |
| 1049 | /// owns command construction, so no arbitrary shell command or environment |
| 1050 | /// channel is exposed by the discovery flow. |
| 1051 | pub struct StartRegistryMcpServer { |
| 1052 | pool: Arc<AsyncMutex<McpPool>>, |
| 1053 | } |
| 1054 | |
| 1055 | impl StartRegistryMcpServer { |
| 1056 | pub fn new(pool: Arc<AsyncMutex<McpPool>>) -> Self { |
| 1057 | Self { pool } |
| 1058 | } |
| 1059 | } |
| 1060 | |
| 1061 | #[async_trait::async_trait] |
| 1062 | impl ToolSpec for StartRegistryMcpServer { |
| 1063 | fn name(&self) -> &str { |
| 1064 | "start_registry_mcp_server" |
| 1065 | } |
| 1066 | |
| 1067 | fn description(&self) -> &str { |
| 1068 | "Install and start a local stdio MCP server previously returned by \ |
| 1069 | registry_sync. Only Registry packages that declare no environment \ |
| 1070 | variables are eligible. Pass the exact registry_name and, when the \ |
| 1071 | discovery result lists required_args, provide their values in the \ |
| 1072 | structured arguments object. The connected server's complete tool \ |
| 1073 | schemas become callable in the same turn." |
| 1074 | } |
| 1075 | |
| 1076 | fn input_schema(&self) -> Value { |
| 1077 | json!({ |
| 1078 | "type": "object", |
| 1079 | "properties": { |
| 1080 | "registry_name": { |
| 1081 | "type": "string", |
| 1082 | "description": "Exact server name returned by registry_sync" |
| 1083 | }, |
| 1084 | "arguments": { |
| 1085 | "type": "object", |
| 1086 | "additionalProperties": { "type": "string" }, |
| 1087 | "description": "Values keyed by required_args[].name; omit when none are required" |
| 1088 | } |
| 1089 | }, |
| 1090 | "required": ["registry_name"] |
| 1091 | }) |
| 1092 | } |
| 1093 | |
| 1094 | fn capabilities(&self) -> Vec<ToolCapability> { |
| 1095 | vec![ToolCapability::Network, ToolCapability::ExecutesCode] |
| 1096 | } |
| 1097 | |
| 1098 | fn approval_requirement(&self) -> ApprovalRequirement { |
| 1099 | ApprovalRequirement::Required |
| 1100 | } |
| 1101 | |
| 1102 | async fn execute(&self, input: Value, ctx: &ToolContext) -> Result<ToolResult, ToolError> { |
| 1103 | let registry_name = input |
| 1104 | .get("registry_name") |
| 1105 | .and_then(Value::as_str) |
| 1106 | .ok_or_else(|| ToolError::invalid_input("missing required field: registry_name"))?; |
| 1107 | let supplied: HashMap<String, String> = match input.get("arguments") { |
| 1108 | Some(value) => serde_json::from_value(value.clone()) |
| 1109 | .map_err(|error| ToolError::invalid_input(format!("invalid arguments: {error}")))?, |
| 1110 | None => HashMap::new(), |
| 1111 | }; |
| 1112 | |
| 1113 | let path = cache_path()?; |
| 1114 | let read_path = path.clone(); |
| 1115 | let cache = tokio::task::spawn_blocking(move || read_cache(&read_path)) |
| 1116 | .await |
| 1117 | .map_err(|error| ToolError::execution_failed(format!("Registry cache read: {error}")))? |
| 1118 | .map_err(|error| { |
| 1119 | ToolError::execution_failed(format!("{error:#}; run registry_sync to rebuild it")) |
| 1120 | })? |
| 1121 | .ok_or_else(|| { |
| 1122 | ToolError::execution_failed(format!( |
| 1123 | "no current Registry cache at {}; run registry_sync first", |
| 1124 | path.display() |
| 1125 | )) |
| 1126 | })?; |
| 1127 | if cache.version != MCP_REGISTRY_CACHE_VERSION { |
| 1128 | return Err(ToolError::execution_failed(format!( |
| 1129 | "cache at {} is from an older schema version; run registry_sync first", |
| 1130 | path.display() |
| 1131 | ))); |
| 1132 | } |
| 1133 | let entry = cache |
| 1134 | .servers |
| 1135 | .iter() |
| 1136 | .find(|server| server.name == registry_name) |
| 1137 | .ok_or_else(|| ToolError::invalid_input("registry_name is not present in the cache"))?; |
| 1138 | |
| 1139 | let expected: HashSet<&str> = entry |
| 1140 | .launch |
| 1141 | .required_args |
| 1142 | .iter() |
| 1143 | .map(|arg| arg.name.as_str()) |
| 1144 | .collect(); |
| 1145 | if let Some(unknown) = supplied |
| 1146 | .keys() |
| 1147 | .find(|name| !expected.contains(name.as_str())) |
| 1148 | { |
| 1149 | return Err(ToolError::invalid_input(format!( |
| 1150 | "unknown argument '{unknown}' for {registry_name}" |
| 1151 | ))); |
| 1152 | } |
| 1153 | |
| 1154 | let mut rendered_args = Vec::new(); |
| 1155 | for argument in &entry.launch.required_args { |
| 1156 | let value = supplied |
| 1157 | .get(&argument.name) |
| 1158 | .cloned() |
| 1159 | .or_else(|| argument.default.clone()) |
| 1160 | .ok_or_else(|| { |
| 1161 | ToolError::invalid_input(format!( |
| 1162 | "missing required argument '{}' for {registry_name}", |
| 1163 | argument.name |
| 1164 | )) |
| 1165 | })?; |
| 1166 | if matches!(argument.kind.as_deref(), Some("named")) && !argument.name.is_empty() { |
| 1167 | rendered_args.push(shell_words::quote(&argument.name).into_owned()); |
| 1168 | } |
| 1169 | rendered_args.push(shell_words::quote(&value).into_owned()); |
| 1170 | } |
| 1171 | |
| 1172 | let command = entry |
| 1173 | .launch |
| 1174 | .run_command |
| 1175 | .replace("<ARGS>", &rendered_args.join(" ")); |
| 1176 | let delegated = json!({ |
| 1177 | "server": command.trim(), |
| 1178 | "name": registry_name, |
| 1179 | // Registry packages cold-start through npx/uvx downloads; the |
| 1180 | // 10s default connect budget is routinely exceeded on first |
| 1181 | // launch. This override is host-supplied only — it is not part |
| 1182 | // of the model-facing schema of either tool. |
| 1183 | "connect_timeout": REGISTRY_CONNECT_TIMEOUT_SECS, |
| 1184 | }); |
| 1185 | crate::tools::runtime_mcp::StartRuntimeMcpServer::new(Arc::clone(&self.pool)) |
| 1186 | .execute(delegated, ctx) |
| 1187 | .await |
| 1188 | } |
| 1189 | } |
| 1190 | |
| 1191 | #[cfg(test)] |
| 1192 | mod tests { |
| 1193 | use super::*; |
| 1194 | |
| 1195 | #[test] |
| 1196 | fn server_no_packages_filtered() { |
| 1197 | let server = RegistryServer { |
| 1198 | name: "test".into(), |
| 1199 | description: "desc".into(), |
| 1200 | packages: None, |
| 1201 | }; |
| 1202 | assert!(server_to_entry(server).is_none()); |
| 1203 | } |
| 1204 | |
| 1205 | #[test] |
| 1206 | fn server_remote_only_filtered() { |
| 1207 | let server = RegistryServer { |
| 1208 | name: "test".into(), |
| 1209 | description: "desc".into(), |
| 1210 | packages: Some(vec![RegistryPackage { |
| 1211 | registry_type: "npm".into(), |
| 1212 | identifier: "@test/pkg".into(), |
| 1213 | version: Some("1.0.0".into()), |
| 1214 | runtime_hint: Some("npx".into()), |
| 1215 | transport: Some("streamable-http".into()), |
| 1216 | package_arguments: vec![], |
| 1217 | runtime_arguments: vec![], |
| 1218 | environment_variables: Value::Null, |
| 1219 | }]), |
| 1220 | }; |
| 1221 | assert!(server_to_entry(server).is_none()); |
| 1222 | } |
| 1223 | |
| 1224 | #[test] |
| 1225 | fn server_stdio_kept() { |
| 1226 | let server = RegistryServer { |
| 1227 | name: "test".into(), |
| 1228 | description: "desc".into(), |
| 1229 | packages: Some(vec![RegistryPackage { |
| 1230 | registry_type: "npm".into(), |
| 1231 | identifier: "@test/pkg".into(), |
| 1232 | version: Some("1.0.0".into()), |
| 1233 | runtime_hint: Some("npx".into()), |
| 1234 | transport: Some("stdio".into()), |
| 1235 | package_arguments: vec![], |
| 1236 | runtime_arguments: vec!["-y".into()], |
| 1237 | environment_variables: Value::Null, |
| 1238 | }]), |
| 1239 | }; |
| 1240 | let entry = server_to_entry(server).unwrap(); |
| 1241 | assert_eq!(entry.launch.run_command, "npx -y @test/pkg@1.0.0 <ARGS>"); |
| 1242 | } |
| 1243 | |
| 1244 | #[test] |
| 1245 | fn server_declaring_environment_variables_is_filtered() { |
| 1246 | let server = RegistryServer { |
| 1247 | name: "needs-secret".into(), |
| 1248 | description: "requires an API key".into(), |
| 1249 | packages: Some(vec![RegistryPackage { |
| 1250 | registry_type: "npm".into(), |
| 1251 | identifier: "@test/secret-server".into(), |
| 1252 | version: Some("1.0.0".into()), |
| 1253 | runtime_hint: Some("npx".into()), |
| 1254 | transport: Some("stdio".into()), |
| 1255 | package_arguments: vec![], |
| 1256 | runtime_arguments: vec!["-y".into()], |
| 1257 | environment_variables: json!([{ "name": "API_KEY", "isRequired": true }]), |
| 1258 | }]), |
| 1259 | }; |
| 1260 | assert!(server_to_entry(server).is_none()); |
| 1261 | } |
| 1262 | |
| 1263 | #[test] |
| 1264 | fn fixed_positional_package_arguments_render_into_run_command() { |
| 1265 | // Regression for the agentic-mermaid launch failure: upstream |
| 1266 | // declares `packageArguments: [{"value": "mcp", "type": |
| 1267 | // "positional"}]` (no `isRequired`), and dropping that token |
| 1268 | // produced `npx -y agentic-mermaid@0.1.2 <ARGS>` — which starts |
| 1269 | // the package's default entrypoint, not the MCP server. |
| 1270 | let server = RegistryServer { |
| 1271 | name: "io.github.adewale/agentic-mermaid".into(), |
| 1272 | description: "Render Mermaid diagrams through MCP.".into(), |
| 1273 | packages: Some(vec![RegistryPackage { |
| 1274 | registry_type: "npm".into(), |
| 1275 | identifier: "agentic-mermaid".into(), |
| 1276 | version: Some("0.1.2".into()), |
| 1277 | runtime_hint: Some("npx".into()), |
| 1278 | transport: Some("stdio".into()), |
| 1279 | package_arguments: vec![RegistryArg { |
| 1280 | name: None, |
| 1281 | description: None, |
| 1282 | is_required: false, |
| 1283 | kind: Some("positional".into()), |
| 1284 | value: Some("mcp".into()), |
| 1285 | default: None, |
| 1286 | }], |
| 1287 | runtime_arguments: vec!["-y".into()], |
| 1288 | environment_variables: Value::Null, |
| 1289 | }]), |
| 1290 | }; |
| 1291 | let entry = server_to_entry(server).unwrap(); |
| 1292 | assert_eq!( |
| 1293 | entry.launch.run_command, |
| 1294 | "npx -y agentic-mermaid@0.1.2 mcp <ARGS>" |
| 1295 | ); |
| 1296 | assert!(entry.launch.required_args.is_empty()); |
| 1297 | } |
| 1298 | |
| 1299 | #[test] |
| 1300 | fn placeholder_positional_package_argument_stays_in_required_args() { |
| 1301 | // The flip side: a positional arg with neither `value` nor |
| 1302 | // `default` is user input (e.g. an allowed directory), not a |
| 1303 | // fixed token — it must NOT leak into the rendered command. |
| 1304 | let server = RegistryServer { |
| 1305 | name: "test".into(), |
| 1306 | description: "desc".into(), |
| 1307 | packages: Some(vec![RegistryPackage { |
| 1308 | registry_type: "npm".into(), |
| 1309 | identifier: "@test/fs".into(), |
| 1310 | version: Some("1.0.0".into()), |
| 1311 | runtime_hint: Some("npx".into()), |
| 1312 | transport: Some("stdio".into()), |
| 1313 | package_arguments: vec![RegistryArg { |
| 1314 | name: None, |
| 1315 | description: Some("Directory to expose".into()), |
| 1316 | is_required: true, |
| 1317 | kind: Some("positional".into()), |
| 1318 | value: None, |
| 1319 | default: None, |
| 1320 | }], |
| 1321 | runtime_arguments: vec!["-y".into()], |
| 1322 | environment_variables: Value::Null, |
| 1323 | }]), |
| 1324 | }; |
| 1325 | let entry = server_to_entry(server).unwrap(); |
| 1326 | assert_eq!(entry.launch.run_command, "npx -y @test/fs@1.0.0 <ARGS>"); |
| 1327 | assert_eq!(entry.launch.required_args.len(), 1); |
| 1328 | } |
| 1329 | |
| 1330 | #[test] |
| 1331 | fn fixed_argument_with_spaces_preserves_one_process_argument() { |
| 1332 | let command = build_run_command( |
| 1333 | "npx", |
| 1334 | "@test/fs", |
| 1335 | "1.0.0", |
| 1336 | &[], |
| 1337 | &[RegistryArg { |
| 1338 | name: None, |
| 1339 | description: None, |
| 1340 | is_required: false, |
| 1341 | kind: Some("positional".into()), |
| 1342 | value: Some("/tmp/a folder".into()), |
| 1343 | default: None, |
| 1344 | }], |
| 1345 | ); |
| 1346 | let parsed = shell_words::split(command.replace("<ARGS>", "").trim()).unwrap(); |
| 1347 | assert_eq!(parsed.last().map(String::as_str), Some("/tmp/a folder")); |
| 1348 | } |
| 1349 | |
| 1350 | #[test] |
| 1351 | fn server_without_explicit_stdio_transport_is_filtered() { |
| 1352 | let server = RegistryServer { |
| 1353 | name: "test".into(), |
| 1354 | description: "desc".into(), |
| 1355 | packages: Some(vec![RegistryPackage { |
| 1356 | registry_type: "npm".into(), |
| 1357 | identifier: "@test/pkg".into(), |
| 1358 | version: Some("1.0.0".into()), |
| 1359 | runtime_hint: Some("npx".into()), |
| 1360 | transport: None, |
| 1361 | package_arguments: vec![], |
| 1362 | runtime_arguments: vec![], |
| 1363 | environment_variables: Value::Null, |
| 1364 | }]), |
| 1365 | }; |
| 1366 | assert!(server_to_entry(server).is_none()); |
| 1367 | } |
| 1368 | |
| 1369 | #[test] |
| 1370 | fn unsupported_registry_runtime_is_not_advertised() { |
| 1371 | let server = RegistryServer { |
| 1372 | name: "container-only".into(), |
| 1373 | description: "OCI stdio server".into(), |
| 1374 | packages: Some(vec![RegistryPackage { |
| 1375 | registry_type: "oci".into(), |
| 1376 | identifier: "docker.io/example/server:1.0.0".into(), |
| 1377 | version: None, |
| 1378 | runtime_hint: Some("docker".into()), |
| 1379 | transport: Some("stdio".into()), |
| 1380 | package_arguments: vec![], |
| 1381 | runtime_arguments: vec![], |
| 1382 | environment_variables: Value::Null, |
| 1383 | }]), |
| 1384 | }; |
| 1385 | assert!(server_to_entry(server).is_none()); |
| 1386 | } |
| 1387 | |
| 1388 | #[test] |
| 1389 | fn registry_type_and_runtime_must_match() { |
| 1390 | let server = RegistryServer { |
| 1391 | name: "mismatched".into(), |
| 1392 | description: "invalid npm runner".into(), |
| 1393 | packages: Some(vec![RegistryPackage { |
| 1394 | registry_type: "npm".into(), |
| 1395 | identifier: "example".into(), |
| 1396 | version: Some("1.0.0".into()), |
| 1397 | runtime_hint: Some("uvx".into()), |
| 1398 | transport: Some("stdio".into()), |
| 1399 | package_arguments: vec![], |
| 1400 | runtime_arguments: vec![], |
| 1401 | environment_variables: Value::Null, |
| 1402 | }]), |
| 1403 | }; |
| 1404 | assert!(server_to_entry(server).is_none()); |
| 1405 | } |
| 1406 | |
| 1407 | /// End-to-end smoke test: cold-start `McpSyncRegistry::execute()` |
| 1408 | /// against the live Registry, wait for the background download to |
| 1409 | /// land, then verify the cache file and the next payload. |
| 1410 | /// |
| 1411 | /// Ignored: needs network + minutes of wall clock (page pacing, flaky |
| 1412 | /// upstream). Run manually with: |
| 1413 | /// cargo test -p codewhale-tui --bin codewhale-tui --locked \ |
| 1414 | /// execute_writes_cache_file_and_returns_summary -- --ignored --nocapture |
| 1415 | /// |
| 1416 | /// The cache path is injected into a tempdir so the real cache is |
| 1417 | /// untouched (works on every platform). |
| 1418 | #[tokio::test] |
| 1419 | #[ignore = "requires network access to the public MCP Registry; \ |
| 1420 | run with `cargo test -- --ignored`"] |
| 1421 | async fn execute_writes_cache_file_and_returns_summary() { |
| 1422 | use crate::tools::spec::ToolContext; |
| 1423 | |
| 1424 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1425 | // Persist the tempdir so we can inspect the cache file after the |
| 1426 | // test returns. `TempDir::keep` (newer API) disables Drop's |
| 1427 | // cleanup so the directory leaks — acceptable for a manual-run |
| 1428 | // integration smoke test that intentionally outlives its scope. |
| 1429 | let tmp_path = tmp.keep(); |
| 1430 | let cache_path = tmp_path.join(".codewhale").join("mcp-index.json"); |
| 1431 | |
| 1432 | let ctx = ToolContext::new(tmp_path.clone()); |
| 1433 | |
| 1434 | let input = json!({ "query": "filesystem file access" }); |
| 1435 | |
| 1436 | let result = McpSyncRegistry::with_cache_path(cache_path.clone()) |
| 1437 | .execute(input, &ctx) |
| 1438 | .await |
| 1439 | .expect("execute() should not error against the live Registry"); |
| 1440 | |
| 1441 | assert!( |
| 1442 | result.success, |
| 1443 | "execute returned non-success: content={}", |
| 1444 | result.content |
| 1445 | ); |
| 1446 | // Cold start: empty catalog returned immediately, download in the |
| 1447 | // background. |
| 1448 | let first_payload: serde_json::Value = |
| 1449 | serde_json::from_str(&result.content).expect("result content must parse"); |
| 1450 | assert_eq!(first_payload["total"], 0, "no cache ⇒ empty catalog"); |
| 1451 | |
| 1452 | // Poll for the background download to land, then assert on the |
| 1453 | // final snapshot (page pacing + upstream stalls take minutes). |
| 1454 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600); |
| 1455 | let cache = loop { |
| 1456 | if let Ok(raw) = std::fs::read_to_string(&cache_path) |
| 1457 | && let Ok(cache) = serde_json::from_str::<McpRegistryIndex>(&raw) |
| 1458 | { |
| 1459 | break cache; |
| 1460 | } |
| 1461 | assert!( |
| 1462 | std::time::Instant::now() < deadline, |
| 1463 | "cache file did not appear at {:?} within 600s", |
| 1464 | cache_path |
| 1465 | ); |
| 1466 | tokio::time::sleep(std::time::Duration::from_millis(500)).await; |
| 1467 | }; |
| 1468 | |
| 1469 | // The Registry has hundreds of stdio servers as of 2026; expect at |
| 1470 | // least 1 from a single page. If this fails the upstream either |
| 1471 | // removed all stdio entries or our filter is wrong. |
| 1472 | assert!( |
| 1473 | cache.count > 0, |
| 1474 | "expected at least 1 stdio server, got count={}", |
| 1475 | cache.count |
| 1476 | ); |
| 1477 | assert_eq!( |
| 1478 | cache.servers.len(), |
| 1479 | cache.count, |
| 1480 | "cache.count must equal cache.servers.len()" |
| 1481 | ); |
| 1482 | for entry in &cache.servers { |
| 1483 | assert!(!entry.name.is_empty(), "server entry has empty name"); |
| 1484 | assert!( |
| 1485 | entry.launch.run_command.ends_with("<ARGS>"), |
| 1486 | "kept entry {} run_command should end with <ARGS>; got: {}", |
| 1487 | entry.name, |
| 1488 | entry.launch.run_command |
| 1489 | ); |
| 1490 | } |
| 1491 | |
| 1492 | // After the background download lands, the next call serves the |
| 1493 | // fresh snapshot and its payload must match the cache file. |
| 1494 | let result = McpSyncRegistry::with_cache_path(cache_path.clone()) |
| 1495 | .execute(json!({ "query": "filesystem file access" }), &ctx) |
| 1496 | .await |
| 1497 | .expect("execute() should succeed once the cache is fresh"); |
| 1498 | let payload: serde_json::Value = |
| 1499 | serde_json::from_str(&result.content).expect("result content must parse"); |
| 1500 | assert_eq!(payload["total"].as_u64(), Some(cache.count as u64)); |
| 1501 | let matches = payload["servers"].as_array().map(Vec::len); |
| 1502 | assert!( |
| 1503 | matches.is_some_and(|len| len <= 8), |
| 1504 | "model-visible matches must stay bounded: {matches:?}" |
| 1505 | ); |
| 1506 | assert!( |
| 1507 | matches.is_some_and(|len| len >= 1), |
| 1508 | "the filesystem fixture must match the filesystem query" |
| 1509 | ); |
| 1510 | } |
| 1511 | |
| 1512 | fn make_test_cache() -> McpRegistryIndex { |
| 1513 | let server = McpRegistryServerEntry { |
| 1514 | name: "io.modelcontextprotocol/filesystem".into(), |
| 1515 | description: "Read/write local files with sandboxed paths".into(), |
| 1516 | launch: McpLaunchSpec { |
| 1517 | run_command: "npx -y @modelcontextprotocol/server-filesystem@1.0.0 <ARGS>".into(), |
| 1518 | required_args: vec![], |
| 1519 | }, |
| 1520 | }; |
| 1521 | McpRegistryIndex { |
| 1522 | version: MCP_REGISTRY_CACHE_VERSION, |
| 1523 | count: 1, |
| 1524 | servers: vec![server], |
| 1525 | synced_at: Some(Utc::now()), |
| 1526 | } |
| 1527 | } |
| 1528 | |
| 1529 | #[test] |
| 1530 | fn catalog_search_reports_total_and_returns_only_matches() { |
| 1531 | let cache = make_test_cache(); |
| 1532 | let catalog = catalog_from_cache(&cache, "filesystem"); |
| 1533 | assert_eq!(catalog.total, 1); |
| 1534 | assert_eq!(catalog.servers.len(), 1); |
| 1535 | assert_eq!( |
| 1536 | catalog.servers[0].name, |
| 1537 | "io.modelcontextprotocol/filesystem" |
| 1538 | ); |
| 1539 | assert_eq!( |
| 1540 | catalog.servers[0].description, |
| 1541 | "Read/write local files with sandboxed paths" |
| 1542 | ); |
| 1543 | // A query that does not match still reports the total, but returns |
| 1544 | // an empty match set — never the full catalog. |
| 1545 | let miss = catalog_from_cache(&cache, "database"); |
| 1546 | assert_eq!(miss.total, 1); |
| 1547 | assert!(miss.servers.is_empty()); |
| 1548 | } |
| 1549 | |
| 1550 | /// A scored row must not read as an obligation. The prompt this result |
| 1551 | /// carries used to say the model "must call start_registry_mcp_server ... |
| 1552 | /// before using shell commands, local programs, custom code, or a manual |
| 1553 | /// implementation", which is how a turn that only needed to write an HTML |
| 1554 | /// file and read a fixture ended up trying to start a browser server. |
| 1555 | #[test] |
| 1556 | fn result_prompt_does_not_oblige_starting_a_match() { |
| 1557 | let catalog = catalog_from_cache(&make_test_cache(), "filesystem"); |
| 1558 | let instruction = catalog.instruction; |
| 1559 | |
| 1560 | assert!(!instruction.contains("must call")); |
| 1561 | assert!(!instruction.contains("custom code")); |
| 1562 | assert!(!instruction.contains("manual implementation")); |
| 1563 | |
| 1564 | // What the result is still responsible for saying: the matches are |
| 1565 | // only worth starting for a capability the session lacks, and a |
| 1566 | // package is started through the approved host path, never the shell. |
| 1567 | assert!(instruction.contains("a capability you do not already have")); |
| 1568 | assert!(instruction.contains("start_registry_mcp_server with its exact name")); |
| 1569 | assert!(instruction.contains("never install or run its package command through the shell")); |
| 1570 | } |
| 1571 | |
| 1572 | /// Parse one `ServerResponse` JSON object the way the upstream list |
| 1573 | /// endpoint ships it. Lifecycle status travels in registry-managed |
| 1574 | /// `_meta` (`io.modelcontextprotocol.registry/official`), as a |
| 1575 | /// SIBLING of `server` — not inside the server body — and this |
| 1576 | /// helper keeps the tests honest about that path. |
| 1577 | /// <https://github.com/modelcontextprotocol/registry/blob/main/docs/reference/api/openapi.yaml> |
| 1578 | fn parse_server_entry(server_json: Value, status: Option<&str>) -> RegistryServerEntry { |
| 1579 | let mut response = json!({ "server": server_json }); |
| 1580 | if let Some(status) = status { |
| 1581 | response["_meta"] = |
| 1582 | json!({ "io.modelcontextprotocol.registry/official": { "status": status } }); |
| 1583 | } |
| 1584 | serde_json::from_value(response).expect("ServerResponse must deserialize") |
| 1585 | } |
| 1586 | |
| 1587 | #[test] |
| 1588 | fn viable_entries_keeps_only_active_launchable_servers() { |
| 1589 | let launchable = |name: &str, status: Option<&str>| { |
| 1590 | parse_server_entry( |
| 1591 | json!({ |
| 1592 | "name": name, |
| 1593 | "description": "d", |
| 1594 | "packages": [{ |
| 1595 | "registryType": "npm", |
| 1596 | "identifier": "@test/pkg", |
| 1597 | "version": "1.0.0", |
| 1598 | "runtimeHint": "npx", |
| 1599 | "transport": "stdio", |
| 1600 | "packageArguments": [], |
| 1601 | "runtimeArguments": [], |
| 1602 | "environmentVariables": null |
| 1603 | }] |
| 1604 | }), |
| 1605 | status, |
| 1606 | ) |
| 1607 | }; |
| 1608 | let entries = vec![ |
| 1609 | launchable("a/active", Some("active")), |
| 1610 | launchable("b/deprecated", Some("deprecated")), |
| 1611 | launchable("c/deleted", Some("deleted")), |
| 1612 | launchable("c/quarantined", Some("quarantined")), |
| 1613 | // No `_meta` at all: treated as active. |
| 1614 | launchable("d/no-meta", None), |
| 1615 | // Missing a launchable package: dropped by the launcher filter. |
| 1616 | parse_server_entry(json!({ "name": "e/no-pkg", "description": "d" }), None), |
| 1617 | ]; |
| 1618 | |
| 1619 | let viable = viable_entries(entries); |
| 1620 | |
| 1621 | let names: Vec<&str> = viable.iter().map(|s| s.name.as_str()).collect(); |
| 1622 | assert_eq!(names, ["a/active", "d/no-meta"]); |
| 1623 | } |
| 1624 | |
| 1625 | /// Minimal cache entry — only `name`/`description`/launch matter to the |
| 1626 | /// catalog conversion tests. |
| 1627 | fn cache_entry(name: &str, description: &str) -> McpRegistryServerEntry { |
| 1628 | McpRegistryServerEntry { |
| 1629 | name: name.into(), |
| 1630 | description: description.into(), |
| 1631 | launch: McpLaunchSpec { |
| 1632 | run_command: "npx pkg@1.0.0 <ARGS>".into(), |
| 1633 | required_args: vec![], |
| 1634 | }, |
| 1635 | } |
| 1636 | } |
| 1637 | |
| 1638 | #[test] |
| 1639 | fn catalog_search_caps_model_visible_matches() { |
| 1640 | let servers = (0..12) |
| 1641 | .map(|index| cache_entry(&format!("example/file-{index}"), "file server")) |
| 1642 | .collect::<Vec<_>>(); |
| 1643 | let cache = McpRegistryIndex { |
| 1644 | version: MCP_REGISTRY_CACHE_VERSION, |
| 1645 | count: servers.len(), |
| 1646 | servers, |
| 1647 | synced_at: Some(Utc::now()), |
| 1648 | }; |
| 1649 | let result = catalog_from_cache(&cache, "file"); |
| 1650 | assert_eq!(result.total, 12); |
| 1651 | assert!( |
| 1652 | result.servers.len() <= MAX_REGISTRY_MATCHES, |
| 1653 | "model-visible matches stay bounded" |
| 1654 | ); |
| 1655 | } |
| 1656 | |
| 1657 | #[test] |
| 1658 | fn cache_is_fresh_honors_ttl_version_and_missing_timestamp() { |
| 1659 | let now = Utc::now(); |
| 1660 | let base = make_test_cache(); |
| 1661 | |
| 1662 | // Within the window: fresh. |
| 1663 | let mut fresh = base.clone(); |
| 1664 | fresh.synced_at = Some(now - chrono::Duration::minutes(30)); |
| 1665 | assert!(cache_is_fresh(&fresh, now)); |
| 1666 | |
| 1667 | // At/over the incremental window boundary: stale. |
| 1668 | let mut expired = base.clone(); |
| 1669 | expired.synced_at = Some(now - chrono::Duration::seconds(INCREMENTAL_INTERVAL_SECS + 1)); |
| 1670 | assert!(!cache_is_fresh(&expired, now)); |
| 1671 | |
| 1672 | // Legacy cache without a timestamp: stale (triggers one resync). |
| 1673 | let mut legacy = base.clone(); |
| 1674 | legacy.synced_at = None; |
| 1675 | assert!(!cache_is_fresh(&legacy, now)); |
| 1676 | |
| 1677 | // Schema version mismatch: always stale. |
| 1678 | let mut old_schema = base.clone(); |
| 1679 | old_schema.version = MCP_REGISTRY_CACHE_VERSION - 1; |
| 1680 | old_schema.synced_at = Some(now); |
| 1681 | assert!(!cache_is_fresh(&old_schema, now)); |
| 1682 | |
| 1683 | // Clock skew: a future-stamped cache stays fresh. |
| 1684 | let mut future = base.clone(); |
| 1685 | future.synced_at = Some(now + chrono::Duration::hours(2)); |
| 1686 | assert!(cache_is_fresh(&future, now)); |
| 1687 | } |
| 1688 | |
| 1689 | #[test] |
| 1690 | fn catalog_for_snapshot_returns_empty_catalog_when_no_cache() { |
| 1691 | let result = catalog_for_snapshot(None, "anything"); |
| 1692 | assert_eq!(result.total, 0); |
| 1693 | assert!(result.servers.is_empty()); |
| 1694 | } |
| 1695 | |
| 1696 | #[test] |
| 1697 | fn catalog_for_snapshot_serves_cached_entries_without_flags() { |
| 1698 | let result = catalog_for_snapshot(Some(make_test_cache()), "filesystem"); |
| 1699 | assert_eq!(result.total, 1); |
| 1700 | assert_eq!(result.servers.len(), 1); |
| 1701 | } |
| 1702 | |
| 1703 | #[test] |
| 1704 | fn catalog_for_snapshot_serves_old_snapshot_as_is() { |
| 1705 | // Snapshot age is invisible to the model: every entry pins its own |
| 1706 | // package version, so even a month-old snapshot is served as-is. |
| 1707 | let mut cache = make_test_cache(); |
| 1708 | cache.synced_at = Some(Utc::now() - chrono::Duration::days(31)); |
| 1709 | let result = catalog_for_snapshot(Some(cache), "filesystem"); |
| 1710 | assert_eq!(result.total, 1); |
| 1711 | assert_eq!(result.servers.len(), 1); |
| 1712 | } |
| 1713 | |
| 1714 | #[test] |
| 1715 | fn sync_strategy_decides_full_vs_incremental() { |
| 1716 | let now = Utc::now(); |
| 1717 | |
| 1718 | // No cache at all: full. |
| 1719 | assert_eq!(sync_strategy(None, now), SyncStrategy::Full); |
| 1720 | |
| 1721 | // Legacy schema version: full. |
| 1722 | let mut old = make_test_cache(); |
| 1723 | old.version = MCP_REGISTRY_CACHE_VERSION - 1; |
| 1724 | assert_eq!(sync_strategy(Some(&old), now), SyncStrategy::Full); |
| 1725 | |
| 1726 | // Missing timestamp: full. |
| 1727 | let mut no_ts = make_test_cache(); |
| 1728 | no_ts.synced_at = None; |
| 1729 | assert_eq!(sync_strategy(Some(&no_ts), now), SyncStrategy::Full); |
| 1730 | |
| 1731 | // Older than the full-resync window: full (reconciliation — an |
| 1732 | // incremental delta cannot observe vanished servers). |
| 1733 | let mut ancient = make_test_cache(); |
| 1734 | ancient.synced_at = Some(now - chrono::Duration::days(31)); |
| 1735 | assert_eq!(sync_strategy(Some(&ancient), now), SyncStrategy::Full); |
| 1736 | |
| 1737 | // Past the incremental window but inside the full-resync window: |
| 1738 | // incremental from the last sync. |
| 1739 | let mut stale = make_test_cache(); |
| 1740 | stale.synced_at = Some(now - chrono::Duration::days(2)); |
| 1741 | assert_eq!( |
| 1742 | sync_strategy(Some(&stale), now), |
| 1743 | SyncStrategy::Incremental { |
| 1744 | since: stale.synced_at.expect("set above") |
| 1745 | } |
| 1746 | ); |
| 1747 | } |
| 1748 | |
| 1749 | /// One launchable delta entry (active stdio npm package); `status` |
| 1750 | /// None means no `_meta` (treated as active). |
| 1751 | fn delta_entry(name: &str, status: Option<&str>) -> RegistryServerEntry { |
| 1752 | parse_server_entry( |
| 1753 | json!({ |
| 1754 | "name": name, |
| 1755 | "description": "d", |
| 1756 | "packages": [{ |
| 1757 | "registryType": "npm", |
| 1758 | "identifier": "@test/pkg", |
| 1759 | "version": "2.0.0", |
| 1760 | "runtimeHint": "npx", |
| 1761 | "transport": "stdio", |
| 1762 | "packageArguments": [], |
| 1763 | "runtimeArguments": [], |
| 1764 | "environmentVariables": null |
| 1765 | }] |
| 1766 | }), |
| 1767 | status, |
| 1768 | ) |
| 1769 | } |
| 1770 | |
| 1771 | #[test] |
| 1772 | fn merge_incremental_entries_updates_inserts_and_removes() { |
| 1773 | let base = vec![ |
| 1774 | cache_entry("a/unchanged", "unchanged"), |
| 1775 | cache_entry("b/updated", "old description"), |
| 1776 | cache_entry("c/deleted", "will be removed"), |
| 1777 | cache_entry("d/deprecated", "will be removed"), |
| 1778 | cache_entry("e/unlaunchable", "will be removed"), |
| 1779 | ]; |
| 1780 | let entries = vec![ |
| 1781 | // Replace the cached copy by name. |
| 1782 | delta_entry("b/updated", Some("active")), |
| 1783 | // Insert a brand-new server. |
| 1784 | delta_entry("f/new", Some("active")), |
| 1785 | // Retired servers are dropped from the snapshot. |
| 1786 | delta_entry("c/deleted", Some("deleted")), |
| 1787 | delta_entry("d/deprecated", Some("deprecated")), |
| 1788 | // Present but no longer launchable (npm package whose runner |
| 1789 | // no longer matches): the stale cached copy is dropped too. |
| 1790 | parse_server_entry( |
| 1791 | json!({ |
| 1792 | "name": "e/unlaunchable", |
| 1793 | "description": "d", |
| 1794 | "packages": [{ |
| 1795 | "registryType": "npm", |
| 1796 | "identifier": "@test/pkg", |
| 1797 | "version": "2.0.0", |
| 1798 | "runtimeHint": "uvx", |
| 1799 | "transport": "stdio", |
| 1800 | "packageArguments": [], |
| 1801 | "runtimeArguments": [], |
| 1802 | "environmentVariables": null |
| 1803 | }] |
| 1804 | }), |
| 1805 | Some("active"), |
| 1806 | ), |
| 1807 | ]; |
| 1808 | |
| 1809 | let merged = merge_incremental_entries(&base, entries); |
| 1810 | let by_name: HashMap<&str, &McpRegistryServerEntry> = merged |
| 1811 | .iter() |
| 1812 | .map(|entry| (entry.name.as_str(), entry)) |
| 1813 | .collect(); |
| 1814 | |
| 1815 | assert_eq!(merged.len(), 3); |
| 1816 | assert!( |
| 1817 | by_name.contains_key("a/unchanged"), |
| 1818 | "entries absent from the delta must keep their cached copy" |
| 1819 | ); |
| 1820 | assert!( |
| 1821 | by_name.contains_key("f/new"), |
| 1822 | "a new server in the delta must be inserted" |
| 1823 | ); |
| 1824 | assert_eq!( |
| 1825 | by_name["b/updated"].description, "d", |
| 1826 | "an updated entry must replace the cached copy" |
| 1827 | ); |
| 1828 | assert!(!by_name.contains_key("c/deleted")); |
| 1829 | assert!(!by_name.contains_key("d/deprecated")); |
| 1830 | assert!( |
| 1831 | !by_name.contains_key("e/unlaunchable"), |
| 1832 | "an entry that lost its launchable package must be dropped" |
| 1833 | ); |
| 1834 | } |
| 1835 | |
| 1836 | /// The sync permit is exclusive while held (no duplicate background |
| 1837 | /// downloads) and reusable after release (failed syncs get retried). |
| 1838 | /// Direct acceptance: a 4,786-entry fixture must never expose more |
| 1839 | /// than eight model-visible matches, and the serialized payload stays |
| 1840 | /// bounded regardless of catalog size. |
| 1841 | #[test] |
| 1842 | fn huge_catalog_search_stays_bounded_at_eight_matches() { |
| 1843 | let entries = (0..4_786) |
| 1844 | .map(|index| McpRegistryServerEntry { |
| 1845 | name: format!("com.example/server-{index}"), |
| 1846 | description: format!("Specialized capability server number {index} for conversion"), |
| 1847 | launch: McpLaunchSpec { |
| 1848 | run_command: "npx -y com.example/server <ARGS>".into(), |
| 1849 | required_args: vec![], |
| 1850 | }, |
| 1851 | }) |
| 1852 | .collect::<Vec<_>>(); |
| 1853 | |
| 1854 | let matches = search_registry_entries(&entries, "conversion server", MAX_REGISTRY_MATCHES); |
| 1855 | assert_eq!(matches.len(), MAX_REGISTRY_MATCHES, "cap at eight matches"); |
| 1856 | |
| 1857 | let payload = serde_json::to_string(&matches).expect("serialize matches"); |
| 1858 | assert!( |
| 1859 | payload.len() < 16_000, |
| 1860 | "bounded payload, got {} bytes", |
| 1861 | payload.len() |
| 1862 | ); |
| 1863 | |
| 1864 | // A query that matches nothing returns an empty set — never the |
| 1865 | // whole catalog. |
| 1866 | let none = search_registry_entries(&entries, "nothing matches this", MAX_REGISTRY_MATCHES); |
| 1867 | assert!(none.is_empty()); |
| 1868 | } |
| 1869 | |
| 1870 | #[test] |
| 1871 | fn search_ranks_exact_name_over_substring_and_ties_break_alphabetically() { |
| 1872 | let entries = [ |
| 1873 | entry("b/convert", "converts documents"), |
| 1874 | entry("a/convert-pro", "converts documents better"), |
| 1875 | entry( |
| 1876 | "zzz-unrelated", |
| 1877 | "but mentions convert deep in a long description", |
| 1878 | ), |
| 1879 | ]; |
| 1880 | let matches = search_registry_entries(&entries, "convert", MAX_REGISTRY_MATCHES); |
| 1881 | let names = matches.iter().map(|m| m.name.as_str()).collect::<Vec<_>>(); |
| 1882 | assert_eq!(names, vec!["a/convert-pro", "b/convert", "zzz-unrelated"]); |
| 1883 | } |
| 1884 | |
| 1885 | #[test] |
| 1886 | fn empty_query_matches_nothing_instead_of_everything() { |
| 1887 | let entries = [entry("a/server", "does things")]; |
| 1888 | assert!(search_registry_entries(&entries, " ", MAX_REGISTRY_MATCHES).is_empty()); |
| 1889 | } |
| 1890 | |
| 1891 | fn entry(name: &str, description: &str) -> McpRegistryServerEntry { |
| 1892 | McpRegistryServerEntry { |
| 1893 | name: name.into(), |
| 1894 | description: description.into(), |
| 1895 | launch: McpLaunchSpec { |
| 1896 | run_command: "npx -y pkg <ARGS>".into(), |
| 1897 | required_args: vec![], |
| 1898 | }, |
| 1899 | } |
| 1900 | } |
| 1901 | |
| 1902 | #[tokio::test] |
| 1903 | async fn background_sync_permit_is_exclusive_until_released() { |
| 1904 | let first = try_acquire_sync_permit(); |
| 1905 | assert!(first.is_some(), "first acquisition must succeed"); |
| 1906 | assert!( |
| 1907 | try_acquire_sync_permit().is_none(), |
| 1908 | "second acquisition must fail while the first is held" |
| 1909 | ); |
| 1910 | drop(first); |
| 1911 | let again = try_acquire_sync_permit(); |
| 1912 | assert!(again.is_some(), "permit must be reusable after release"); |
| 1913 | drop(again); |
| 1914 | } |
| 1915 | |
| 1916 | /// With a fresh snapshot on disk, `registry_sync` must serve it |
| 1917 | /// without touching the network: the fixture is a single synthetic |
| 1918 | /// server, so any live sync would return a different catalog and fail |
| 1919 | /// the assertion. The cache path is injected explicitly because |
| 1920 | /// `dirs::home_dir()` resolves the OS profile directory on Windows via |
| 1921 | /// SHGetKnownFolderPath — no environment variable can redirect it. |
| 1922 | #[tokio::test] |
| 1923 | async fn fresh_cache_serves_catalog_without_network() { |
| 1924 | use crate::tools::spec::ToolContext; |
| 1925 | |
| 1926 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1927 | let cache_dir = tmp.path().join(".codewhale"); |
| 1928 | std::fs::create_dir_all(&cache_dir).expect("create cache dir"); |
| 1929 | let cache_file = cache_dir.join("mcp-index.json"); |
| 1930 | let index = make_test_cache(); |
| 1931 | std::fs::write( |
| 1932 | &cache_file, |
| 1933 | serde_json::to_string_pretty(&index).expect("serialize fixture"), |
| 1934 | ) |
| 1935 | .expect("write fixture cache"); |
| 1936 | |
| 1937 | let ctx = ToolContext::new(tmp.path().to_path_buf()); |
| 1938 | let result = McpSyncRegistry::with_cache_path(cache_file) |
| 1939 | .execute(json!({ "query": "filesystem" }), &ctx) |
| 1940 | .await |
| 1941 | .expect("fresh cache must serve without network"); |
| 1942 | |
| 1943 | let payload: serde_json::Value = |
| 1944 | serde_json::from_str(&result.content).expect("result content must parse"); |
| 1945 | assert_eq!(payload["total"], 1, "fixture catalog is reported in full"); |
| 1946 | assert_eq!( |
| 1947 | payload["servers"][0]["name"], "io.modelcontextprotocol/filesystem", |
| 1948 | "cache-first path must return the cached entry, not a live sync" |
| 1949 | ); |
| 1950 | } |
| 1951 | |
| 1952 | /// Manual smoke run: cold-start against the live Registry, wait for |
| 1953 | /// the background download, then print the final payload to stdout. |
| 1954 | /// Run with: |
| 1955 | /// cargo test -p codewhale-tui --bin codewhale-tui --locked \ |
| 1956 | /// execute_and_print_catalog_for_manual_inspection -- --ignored --nocapture |
| 1957 | #[tokio::test] |
| 1958 | #[ignore = "manual smoke run; prints the tool result to stdout \ |
| 1959 | (requires network access to registry.modelcontextprotocol.io)"] |
| 1960 | // The module tree denies `print_stderr` (scroll-demon guard, #1085) so |
| 1961 | // TUI runtime code can never leak into ratatui's buffer. This test is |
| 1962 | // the deliberate exception: it only runs manually (`--ignored`) and its |
| 1963 | // entire purpose is printing the payload for operator inspection. |
| 1964 | #[allow(clippy::print_stderr)] |
| 1965 | async fn execute_and_print_catalog_for_manual_inspection() { |
| 1966 | use crate::tools::spec::ToolContext; |
| 1967 | |
| 1968 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 1969 | // Persist the tempdir past the test so the cache file survives and |
| 1970 | // can be inspected from the shell after the test returns. |
| 1971 | let tmp_path = tmp.keep(); |
| 1972 | let cache_path = tmp_path.join(".codewhale").join("mcp-index.json"); |
| 1973 | |
| 1974 | let ctx = ToolContext::new(tmp_path.clone()); |
| 1975 | |
| 1976 | let input = json!({ "query": "filesystem file access" }); |
| 1977 | |
| 1978 | let result = McpSyncRegistry::with_cache_path(cache_path.clone()) |
| 1979 | .execute(input, &ctx) |
| 1980 | .await |
| 1981 | .expect("execute() should not error against the live Registry"); |
| 1982 | |
| 1983 | // The cold-start call returns immediately (empty catalog + |
| 1984 | // background download). Wait for the download to land, then call |
| 1985 | // again and print the final payload the model would receive. |
| 1986 | eprintln!("cold-start payload (background download flagged):"); |
| 1987 | eprintln!("{}", result.content); |
| 1988 | eprintln!("waiting for the background download to land..."); |
| 1989 | let deadline = std::time::Instant::now() + std::time::Duration::from_secs(600); |
| 1990 | while !cache_path.exists() { |
| 1991 | assert!( |
| 1992 | std::time::Instant::now() < deadline, |
| 1993 | "cache file did not appear at {:?} within 600s", |
| 1994 | cache_path |
| 1995 | ); |
| 1996 | tokio::time::sleep(std::time::Duration::from_millis(500)).await; |
| 1997 | } |
| 1998 | |
| 1999 | let result = McpSyncRegistry::with_cache_path(cache_path.clone()) |
| 2000 | .execute(json!({}), &ctx) |
| 2001 | .await |
| 2002 | .expect("execute() should succeed once the cache is fresh"); |
| 2003 | |
| 2004 | eprintln!("\n=== registry_sync output ==="); |
| 2005 | eprintln!("tool: registry_sync"); |
| 2006 | eprintln!( |
| 2007 | "status: {}", |
| 2008 | if result.success { "ok" } else { "fail" } |
| 2009 | ); |
| 2010 | eprintln!("cache_path: {}", cache_path.display()); |
| 2011 | eprintln!("cache_exists: {}", cache_path.exists()); |
| 2012 | if cache_path.exists() { |
| 2013 | match std::fs::metadata(&cache_path) { |
| 2014 | Ok(meta) => eprintln!("cache_size_bytes: {}", meta.len()), |
| 2015 | Err(e) => eprintln!("cache_stat_error: {e}"), |
| 2016 | } |
| 2017 | } |
| 2018 | eprintln!("--- catalog payload (what the model sees) ---"); |
| 2019 | eprintln!("{}", result.content); |
| 2020 | eprintln!("=== end ===\n"); |
| 2021 | } |
| 2022 | |
| 2023 | #[test] |
| 2024 | fn unknown_lifecycle_statuses_are_retired_in_full_and_incremental_sync() { |
| 2025 | let launchable = |name: &str, status: Option<&str>| { |
| 2026 | parse_server_entry( |
| 2027 | json!({ |
| 2028 | "name": name, |
| 2029 | "description": "d", |
| 2030 | "packages": [{ |
| 2031 | "registryType": "npm", |
| 2032 | "identifier": "@test/pkg", |
| 2033 | "version": "1.0.0", |
| 2034 | "runtimeHint": "npx", |
| 2035 | "transport": "stdio", |
| 2036 | "packageArguments": [], |
| 2037 | "runtimeArguments": [], |
| 2038 | "environmentVariables": null |
| 2039 | }] |
| 2040 | }), |
| 2041 | status, |
| 2042 | ) |
| 2043 | }; |
| 2044 | |
| 2045 | let full = viable_entries(vec![ |
| 2046 | launchable("a/active", Some("active")), |
| 2047 | launchable("b/upper-deleted", Some("DELETED")), |
| 2048 | launchable("c/retired", Some("retired")), |
| 2049 | launchable("d/trailing-space", Some("active ")), |
| 2050 | ]); |
| 2051 | let full_names: Vec<&str> = full.iter().map(|s| s.name.as_str()).collect(); |
| 2052 | assert_eq!(full_names, ["a/active"]); |
| 2053 | |
| 2054 | let base = vec![ |
| 2055 | cache_entry("a/keep", "old"), |
| 2056 | cache_entry("b/upper-deleted", "old"), |
| 2057 | cache_entry("c/retired", "old"), |
| 2058 | ]; |
| 2059 | let merged = merge_incremental_entries( |
| 2060 | &base, |
| 2061 | vec![ |
| 2062 | launchable("b/upper-deleted", Some("DELETED")), |
| 2063 | launchable("c/retired", Some("retired")), |
| 2064 | ], |
| 2065 | ); |
| 2066 | let merged_names: Vec<&str> = merged.iter().map(|s| s.name.as_str()).collect(); |
| 2067 | assert_eq!(merged_names, ["a/keep"]); |
| 2068 | } |
| 2069 | |
| 2070 | #[test] |
| 2071 | fn read_cache_distinguishes_missing_corrupt_and_oversized_files() { |
| 2072 | let tmp = tempfile::tempdir().expect("tempdir"); |
| 2073 | let missing = tmp.path().join("missing.json"); |
| 2074 | assert!(read_cache(&missing).expect("missing is Ok(None)").is_none()); |
| 2075 | |
| 2076 | let corrupt = tmp.path().join("corrupt.json"); |
| 2077 | std::fs::write(&corrupt, "{not valid json").expect("write corrupt cache"); |
| 2078 | let err = read_cache(&corrupt) |
| 2079 | .err() |
| 2080 | .expect("corrupt cache must fail, not report missing"); |
| 2081 | assert!( |
| 2082 | err.to_string().contains("malformed MCP Registry cache"), |
| 2083 | "unexpected error: {err}" |
| 2084 | ); |
| 2085 | |
| 2086 | let oversized = tmp.path().join("oversized.json"); |
| 2087 | std::fs::write(&oversized, "x".repeat(256)).expect("write oversized file"); |
| 2088 | let size_err = crate::mcp::read_bounded_mcp_config_file(&oversized, 64) |
| 2089 | .expect_err("oversized file must be rejected"); |
| 2090 | assert!( |
| 2091 | size_err.to_string().contains("exceeds"), |
| 2092 | "unexpected size error: {size_err}" |
| 2093 | ); |
| 2094 | } |
| 2095 | |
| 2096 | async fn spawn_mock_registry( |
| 2097 | raw_replies: Vec<String>, |
| 2098 | ) -> (String, tokio::task::JoinHandle<usize>) { |
| 2099 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 2100 | |
| 2101 | let listener = tokio::net::TcpListener::bind("127.0.0.1:0") |
| 2102 | .await |
| 2103 | .expect("bind mock registry"); |
| 2104 | let addr = listener.local_addr().expect("mock registry addr"); |
| 2105 | let handle = tokio::spawn(async move { |
| 2106 | let mut served = 0usize; |
| 2107 | for reply in raw_replies { |
| 2108 | let Ok((mut stream, _)) = listener.accept().await else { |
| 2109 | break; |
| 2110 | }; |
| 2111 | let mut req_buf = [0u8; 4096]; |
| 2112 | let _ = stream.read(&mut req_buf).await; |
| 2113 | let _ = stream.write_all(reply.as_bytes()).await; |
| 2114 | let _ = stream.shutdown().await; |
| 2115 | served += 1; |
| 2116 | } |
| 2117 | served |
| 2118 | }); |
| 2119 | (format!("http://{addr}/v0.1/servers"), handle) |
| 2120 | } |
| 2121 | |
| 2122 | fn http_json_reply(body: &str) -> String { |
| 2123 | format!( |
| 2124 | "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", |
| 2125 | body.len() |
| 2126 | ) |
| 2127 | } |
| 2128 | |
| 2129 | fn test_registry_client() -> reqwest::Client { |
| 2130 | crate::platform_client_builder() |
| 2131 | .no_proxy() |
| 2132 | .timeout(std::time::Duration::from_secs(5)) |
| 2133 | .build() |
| 2134 | .expect("test client") |
| 2135 | } |
| 2136 | |
| 2137 | #[tokio::test] |
| 2138 | async fn fetch_registry_entries_rejects_repeated_cursor() { |
| 2139 | let page = |
| 2140 | json!({ "servers": [], "metadata": { "nextCursor": "same-cursor" } }).to_string(); |
| 2141 | let (url, server) = |
| 2142 | spawn_mock_registry(vec![http_json_reply(&page), http_json_reply(&page)]).await; |
| 2143 | let err = fetch_registry_entries_from( |
| 2144 | &test_registry_client(), |
| 2145 | &url, |
| 2146 | None, |
| 2147 | RegistryFetchLimits { |
| 2148 | max_pages: 10, |
| 2149 | max_entries: 100, |
| 2150 | max_page_bytes: 64 * 1024, |
| 2151 | page_pacing: std::time::Duration::ZERO, |
| 2152 | }, |
| 2153 | ) |
| 2154 | .await |
| 2155 | .err() |
| 2156 | .expect("repeated cursor must fail"); |
| 2157 | assert!(err.to_string().contains("repeated cursor"), "{err}"); |
| 2158 | assert_eq!(server.await.unwrap(), 2); |
| 2159 | } |
| 2160 | |
| 2161 | #[tokio::test] |
| 2162 | async fn fetch_registry_entries_rejects_oversized_cursor() { |
| 2163 | let huge_cursor = "a".repeat(MAX_REGISTRY_CURSOR_BYTES + 1); |
| 2164 | let page = json!({ "servers": [], "metadata": { "nextCursor": huge_cursor } }).to_string(); |
| 2165 | let (url, server) = spawn_mock_registry(vec![http_json_reply(&page)]).await; |
| 2166 | let err = fetch_registry_entries_from( |
| 2167 | &test_registry_client(), |
| 2168 | &url, |
| 2169 | None, |
| 2170 | RegistryFetchLimits { |
| 2171 | max_pages: 10, |
| 2172 | max_entries: 100, |
| 2173 | max_page_bytes: 64 * 1024, |
| 2174 | page_pacing: std::time::Duration::ZERO, |
| 2175 | }, |
| 2176 | ) |
| 2177 | .await |
| 2178 | .err() |
| 2179 | .expect("oversized cursor must fail"); |
| 2180 | assert!(err.to_string().contains("oversized"), "{err}"); |
| 2181 | assert_eq!(server.await.unwrap(), 1); |
| 2182 | } |
| 2183 | |
| 2184 | #[tokio::test] |
| 2185 | async fn fetch_registry_entries_enforces_page_limit() { |
| 2186 | let p1 = json!({ "servers": [], "metadata": { "nextCursor": "c1" } }).to_string(); |
| 2187 | let p2 = json!({ "servers": [], "metadata": { "nextCursor": "c2" } }).to_string(); |
| 2188 | let (url, server) = |
| 2189 | spawn_mock_registry(vec![http_json_reply(&p1), http_json_reply(&p2)]).await; |
| 2190 | let err = fetch_registry_entries_from( |
| 2191 | &test_registry_client(), |
| 2192 | &url, |
| 2193 | None, |
| 2194 | RegistryFetchLimits { |
| 2195 | max_pages: 2, |
| 2196 | max_entries: 100, |
| 2197 | max_page_bytes: 64 * 1024, |
| 2198 | page_pacing: std::time::Duration::ZERO, |
| 2199 | }, |
| 2200 | ) |
| 2201 | .await |
| 2202 | .err() |
| 2203 | .expect("exceeding max_pages must fail"); |
| 2204 | assert!(err.to_string().contains("exceeds 2 pages"), "{err}"); |
| 2205 | assert_eq!(server.await.unwrap(), 2); |
| 2206 | } |
| 2207 | |
| 2208 | #[tokio::test] |
| 2209 | async fn fetch_registry_entries_rejects_oversized_response_body() { |
| 2210 | let oversized_body = format!("{{\"servers\":[],\"pad\":\"{}\"}}", "x".repeat(512)); |
| 2211 | |
| 2212 | // 1. Declared Content-Length over the cap. |
| 2213 | let (url, server) = spawn_mock_registry(vec![http_json_reply(&oversized_body)]).await; |
| 2214 | let err = fetch_registry_entries_from( |
| 2215 | &test_registry_client(), |
| 2216 | &url, |
| 2217 | None, |
| 2218 | RegistryFetchLimits { |
| 2219 | max_pages: 5, |
| 2220 | max_entries: 100, |
| 2221 | max_page_bytes: 128, |
| 2222 | page_pacing: std::time::Duration::ZERO, |
| 2223 | }, |
| 2224 | ) |
| 2225 | .await |
| 2226 | .err() |
| 2227 | .expect("declared oversized body must be refused"); |
| 2228 | assert!(err.to_string().contains("exceeds 128 bytes"), "{err}"); |
| 2229 | assert_eq!(server.await.unwrap(), 1); |
| 2230 | |
| 2231 | // 2. Streaming body without Content-Length over the cap. |
| 2232 | let streaming_reply = format!( |
| 2233 | "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{oversized_body}" |
| 2234 | ); |
| 2235 | let (url, server) = spawn_mock_registry(vec![streaming_reply]).await; |
| 2236 | let err = fetch_registry_entries_from( |
| 2237 | &test_registry_client(), |
| 2238 | &url, |
| 2239 | None, |
| 2240 | RegistryFetchLimits { |
| 2241 | max_pages: 5, |
| 2242 | max_entries: 100, |
| 2243 | max_page_bytes: 128, |
| 2244 | page_pacing: std::time::Duration::ZERO, |
| 2245 | }, |
| 2246 | ) |
| 2247 | .await |
| 2248 | .err() |
| 2249 | .expect("streaming oversized body must be refused"); |
| 2250 | assert!(err.to_string().contains("exceeds 128 bytes"), "{err}"); |
| 2251 | assert_eq!(server.await.unwrap(), 1); |
| 2252 | } |
| 2253 | } |
| 2254 |