| 1 | //! Async MCP (Model Context Protocol) Implementation |
| 2 | //! |
| 3 | //! This module provides full async support for MCP servers with: |
| 4 | //! - Connection pooling for server reuse |
| 5 | //! - Automatic tool discovery via `tools/list` |
| 6 | //! - Configurable timeouts per-server and globally |
| 7 | |
| 8 | use std::collections::{BTreeSet, HashMap, HashSet}; |
| 9 | use std::ffi::{OsStr, OsString}; |
| 10 | use std::fs; |
| 11 | use std::future::Future; |
| 12 | use std::io::{Read, Seek}; |
| 13 | use std::path::{Component, Path, PathBuf}; |
| 14 | use std::sync::Arc; |
| 15 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 16 | use std::time::Duration; |
| 17 | |
| 18 | use anyhow::{Context, Result}; |
| 19 | use codewhale_config::McpBackend; |
| 20 | use codewhale_runtime::credentials::AuthContext; |
| 21 | use codewhale_runtime::credentials::context::ProcessAuthContext; |
| 22 | use futures_util::FutureExt; |
| 23 | use parking_lot::RwLock; |
| 24 | use serde::{Deserialize, Serialize}; |
| 25 | use sha2::Digest as _; |
| 26 | |
| 27 | pub type SharedRuntimeMcpServers = Arc<RwLock<HashMap<String, McpServerConfig>>>; |
| 28 | |
| 29 | pub mod external_import; |
| 30 | mod headers; |
| 31 | mod http; |
| 32 | pub mod http_client; |
| 33 | pub mod oauth; |
| 34 | pub mod process_broker; |
| 35 | pub mod project_authority; |
| 36 | pub mod sse; |
| 37 | mod stdio; |
| 38 | mod streamable_http; |
| 39 | pub mod wire; |
| 40 | |
| 41 | use self::http::HttpTransport; |
| 42 | use self::http_client::McpHttpAuth; |
| 43 | use self::oauth::McpServerConfigOAuthExt; |
| 44 | #[cfg(all(test, unix))] |
| 45 | use self::process_broker::STDIO_SHUTDOWN_GRACE; |
| 46 | use self::sse::SseTransport; |
| 47 | use self::stdio::StdioTransport; |
| 48 | pub use self::wire::MAX_MCP_RESPONSE_BYTES; |
| 49 | pub use self::wire::read_line_capped; |
| 50 | use self::wire::{ |
| 51 | is_mcp_connection_lost_error, is_mcp_server_reply_unsupported_error, |
| 52 | is_mcp_session_rejected_error, is_mcp_stale_session_body, |
| 53 | }; |
| 54 | use codewhale_mcp::config::{ |
| 55 | McpConfig, McpProvenance, McpServerConfig, McpServerOAuthConfig, McpTimeouts, |
| 56 | is_relative_stdio_path_arg, |
| 57 | }; |
| 58 | use codewhale_net::network_policy::{Decision, NetworkPolicyDecider, host_from_url}; |
| 59 | use codewhale_util::utils::write_atomic; |
| 60 | |
| 61 | pub trait McpServerConfigExt { |
| 62 | fn reviewed_plugin_source(&self) -> Option<&ReviewedPluginMcpSource>; |
| 63 | } |
| 64 | |
| 65 | impl McpServerConfigExt for McpServerConfig { |
| 66 | fn reviewed_plugin_source(&self) -> Option<&ReviewedPluginMcpSource> { |
| 67 | self.reviewed_plugin.as_ref()?.downcast_ref() |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | pub fn provenance_of(source: ReviewedPluginMcpSource) -> Option<McpProvenance> { |
| 72 | Some(McpProvenance::new(source)) |
| 73 | } |
| 74 | |
| 75 | // === Error diagnostics helpers (#71) === |
| 76 | |
| 77 | /// Bytes of a non-2xx response body to surface in connection errors. |
| 78 | pub const ERROR_BODY_PREVIEW_BYTES: usize = 200; |
| 79 | |
| 80 | /// Preferred dated MCP protocol revision for the legacy Rust client. |
| 81 | pub const MCP_PROTOCOL_VERSION: &str = "2025-06-18"; |
| 82 | pub const MCP_MODERN_PROTOCOL_VERSION: &str = "2026-07-28"; |
| 83 | /// Revisions a *server* may answer our client `initialize` with, newest first. |
| 84 | /// Servers built on current SDKs (Pi, OMP and the 2025-11-25 TypeScript and |
| 85 | /// Python SDKs) answer `2025-11-25` even when offered an older revision; the |
| 86 | /// message shapes our client uses are unchanged in that revision, so ending |
| 87 | /// the handshake there only turns a working server into a failed row. |
| 88 | pub const MCP_CLIENT_ACCEPTED_PROTOCOL_VERSIONS: &[&str] = &[ |
| 89 | "2025-11-25", |
| 90 | MCP_PROTOCOL_VERSION, |
| 91 | "2025-03-26", |
| 92 | "2024-11-05", |
| 93 | ]; |
| 94 | |
| 95 | fn validate_mcp_config_path(path: &Path) -> Result<()> { |
| 96 | if path.as_os_str().is_empty() { |
| 97 | anyhow::bail!("MCP config path cannot be empty"); |
| 98 | } |
| 99 | if path |
| 100 | .components() |
| 101 | .any(|component| matches!(component, Component::ParentDir)) |
| 102 | { |
| 103 | anyhow::bail!("MCP config path cannot contain '..' components"); |
| 104 | } |
| 105 | Ok(()) |
| 106 | } |
| 107 | |
| 108 | /// Refuse to write a workspace's `.codewhale/mcp.json` through a link: when |
| 109 | /// the file lives under a `<workspace>/.codewhale`, no component from the |
| 110 | /// workspace down may be a link. The user's own home config (`~/.codewhale`) is |
| 111 | /// exempt, because users relocate it on purpose. Writers only: reading a linked |
| 112 | /// file is still allowed, as before. |
| 113 | fn reject_linked_workspace_state_path(path: &Path) -> Result<()> { |
| 114 | let Some(root) = path |
| 115 | .ancestors() |
| 116 | .find(|ancestor| ancestor.file_name() == Some(std::ffi::OsStr::new(".codewhale"))) |
| 117 | .and_then(Path::parent) |
| 118 | else { |
| 119 | return Ok(()); |
| 120 | }; |
| 121 | if codewhale_util::files::workspace_is_user_home(root) { |
| 122 | return Ok(()); |
| 123 | } |
| 124 | codewhale_util::files::reject_linked_path(root, path) |
| 125 | .with_context(|| format!("MCP config {} is not safe to write", path.display())) |
| 126 | } |
| 127 | |
| 128 | #[derive(Clone)] |
| 129 | pub struct McpAuthContext(pub Arc<dyn AuthContext>); |
| 130 | |
| 131 | impl std::fmt::Debug for McpAuthContext { |
| 132 | fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 133 | formatter.write_str("McpAuthContext(<host authority>)") |
| 134 | } |
| 135 | } |
| 136 | |
| 137 | impl Default for McpAuthContext { |
| 138 | fn default() -> Self { |
| 139 | Self(process_mcp_auth_context()) |
| 140 | } |
| 141 | } |
| 142 | |
| 143 | pub fn process_mcp_auth_context() -> Arc<dyn AuthContext> { |
| 144 | static CONTEXT: std::sync::OnceLock<Arc<dyn AuthContext>> = std::sync::OnceLock::new(); |
| 145 | Arc::clone(CONTEXT.get_or_init(|| Arc::new(ProcessAuthContext))) |
| 146 | } |
| 147 | |
| 148 | fn mcp_secret_var( |
| 149 | reviewed_plugin: Option<&ReviewedPluginMcpSource>, |
| 150 | name: &str, |
| 151 | auth_context: &dyn AuthContext, |
| 152 | ) -> Option<String> { |
| 153 | match reviewed_plugin { |
| 154 | Some(source) => source.host_environment.var(name).ok(), |
| 155 | None => auth_context.env(name), |
| 156 | } |
| 157 | } |
| 158 | |
| 159 | const MCP_CREDENTIAL_CONFIGURATION_ERROR_PREFIX: &str = "MCP credential configuration error:"; |
| 160 | |
| 161 | #[derive(Debug)] |
| 162 | struct McpCredentialConfigurationError(String); |
| 163 | |
| 164 | impl std::fmt::Display for McpCredentialConfigurationError { |
| 165 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 166 | write!(f, "{MCP_CREDENTIAL_CONFIGURATION_ERROR_PREFIX} {}", self.0) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | impl std::error::Error for McpCredentialConfigurationError {} |
| 171 | |
| 172 | fn required_mcp_secret_var( |
| 173 | reviewed_plugin: Option<&ReviewedPluginMcpSource>, |
| 174 | name: &str, |
| 175 | auth_context: &dyn AuthContext, |
| 176 | ) -> Result<String> { |
| 177 | mcp_secret_var(reviewed_plugin, name, auth_context) |
| 178 | .filter(|value| !value.trim().is_empty()) |
| 179 | .ok_or_else(|| { |
| 180 | let message = if reviewed_plugin.is_some() { |
| 181 | "Reviewed plugin MCP credential configuration is unavailable (details suppressed)".to_string() |
| 182 | } else if name == "CODEWHALE_BROWSER_TOOLS_TOKEN" { |
| 183 | "Codewhale desktop browser tools are available only in their owning desktop window; this process has no desktop browser credential".to_string() |
| 184 | } else { |
| 185 | format!("Required MCP environment variable {name} is missing; configure it for this process before reconnecting") |
| 186 | }; |
| 187 | anyhow::Error::new(McpCredentialConfigurationError(message)) |
| 188 | }) |
| 189 | } |
| 190 | |
| 191 | pub fn mcp_secret_available( |
| 192 | server: &McpServerConfig, |
| 193 | name: &str, |
| 194 | auth_context: &dyn AuthContext, |
| 195 | ) -> bool { |
| 196 | mcp_secret_var(server.reviewed_plugin_source(), name, auth_context) |
| 197 | .is_some_and(|value| !value.trim().is_empty()) |
| 198 | } |
| 199 | |
| 200 | /// Expand `${NAME}` placeholders in an MCP config value from its permitted |
| 201 | /// environment source. This lets secrets (API keys, bearer tokens, …) be supplied |
| 202 | /// through environment variables instead of being written in cleartext into |
| 203 | /// the MCP config file on disk. |
| 204 | /// |
| 205 | /// On a missing or malformed placeholder the error names only the offending |
| 206 | /// variable, never the surrounding value, so a secret-bearing string is never |
| 207 | /// echoed into logs or error output. |
| 208 | fn expand_env_placeholders_with( |
| 209 | value: &str, |
| 210 | reviewed_plugin: Option<&ReviewedPluginMcpSource>, |
| 211 | auth_context: &dyn AuthContext, |
| 212 | ) -> Result<String> { |
| 213 | let mut out = String::new(); |
| 214 | let mut rest = value; |
| 215 | while let Some(start) = rest.find("${") { |
| 216 | out.push_str(&rest[..start]); |
| 217 | let after = &rest[start + 2..]; |
| 218 | let Some(end) = after.find('}') else { |
| 219 | anyhow::bail!("unterminated environment placeholder in MCP config value"); |
| 220 | }; |
| 221 | let name = &after[..end]; |
| 222 | if name.is_empty() || !name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_') { |
| 223 | anyhow::bail!("invalid environment placeholder in MCP config value"); |
| 224 | } |
| 225 | let env_value = mcp_secret_var(reviewed_plugin, name, auth_context).with_context(|| { |
| 226 | format!("environment variable {name} required by MCP config is not set") |
| 227 | })?; |
| 228 | out.push_str(&env_value); |
| 229 | rest = &after[end + 1..]; |
| 230 | } |
| 231 | out.push_str(rest); |
| 232 | Ok(out) |
| 233 | } |
| 234 | |
| 235 | #[cfg(test)] |
| 236 | fn expand_env_placeholders(value: &str) -> Result<String> { |
| 237 | expand_env_placeholders_with(value, None, &ProcessAuthContext) |
| 238 | } |
| 239 | |
| 240 | /// Expand `${NAME}` placeholders across every value of an MCP config map |
| 241 | /// (e.g. the stdio child `env`). `context` only labels expansion errors so a |
| 242 | /// failure can be attributed to the right map. |
| 243 | fn expand_env_placeholders_map_with_environment( |
| 244 | values: &HashMap<String, String>, |
| 245 | context: &str, |
| 246 | reviewed_plugin: Option<&ReviewedPluginMcpSource>, |
| 247 | auth_context: &dyn AuthContext, |
| 248 | ) -> Result<HashMap<String, String>> { |
| 249 | let mut expanded = HashMap::with_capacity(values.len()); |
| 250 | for (key, value) in values { |
| 251 | expanded.insert( |
| 252 | key.clone(), |
| 253 | expand_env_placeholders_with(value, reviewed_plugin, auth_context) |
| 254 | .with_context(|| format!("failed to expand MCP {context} value for {key}"))?, |
| 255 | ); |
| 256 | } |
| 257 | Ok(expanded) |
| 258 | } |
| 259 | |
| 260 | #[cfg(test)] |
| 261 | fn expand_env_placeholders_map( |
| 262 | values: &HashMap<String, String>, |
| 263 | context: &str, |
| 264 | ) -> Result<HashMap<String, String>> { |
| 265 | expand_env_placeholders_map_with_environment(values, context, None, &ProcessAuthContext) |
| 266 | } |
| 267 | |
| 268 | #[cfg(test)] |
| 269 | fn expanded_mcp_stdio_env(config: &McpServerConfig) -> Result<HashMap<String, String>> { |
| 270 | expanded_mcp_stdio_env_with_auth_context(config, &ProcessAuthContext) |
| 271 | } |
| 272 | |
| 273 | fn expanded_mcp_stdio_env_with_auth_context( |
| 274 | config: &McpServerConfig, |
| 275 | auth_context: &dyn AuthContext, |
| 276 | ) -> Result<HashMap<String, String>> { |
| 277 | expand_env_placeholders_map_with_environment( |
| 278 | &config.env, |
| 279 | "env", |
| 280 | config.reviewed_plugin_source(), |
| 281 | auth_context, |
| 282 | ) |
| 283 | } |
| 284 | |
| 285 | /// Mirror the exact expanded and sanitized environment applied by the MCP |
| 286 | /// stdio spawn path, without constructing or starting a process. |
| 287 | #[cfg(test)] |
| 288 | fn mcp_stdio_child_env(config: &McpServerConfig) -> Result<Vec<(OsString, OsString)>> { |
| 289 | mcp_stdio_child_env_with_auth_context(config, &ProcessAuthContext) |
| 290 | } |
| 291 | |
| 292 | fn mcp_stdio_child_env_with_auth_context( |
| 293 | config: &McpServerConfig, |
| 294 | auth_context: &dyn AuthContext, |
| 295 | ) -> Result<Vec<(OsString, OsString)>> { |
| 296 | let expanded_env = expanded_mcp_stdio_env_with_auth_context(config, auth_context)?; |
| 297 | let overrides = codewhale_runtime::child_env::string_map_env(&expanded_env); |
| 298 | Ok(if let Some(source) = config.reviewed_plugin_source() { |
| 299 | // Plugin reviews name every extra environment source explicitly. Do |
| 300 | // not silently widen that consent to the compatibility-oriented MCP |
| 301 | // bootstrap namespace (for example NPM_CONFIG_*). |
| 302 | codewhale_runtime::child_env::sanitized_plugin_mcp_env_from( |
| 303 | source.host_environment.entries().iter().cloned(), |
| 304 | overrides, |
| 305 | ) |
| 306 | } else { |
| 307 | codewhale_runtime::child_env::sanitized_mcp_env(overrides) |
| 308 | }) |
| 309 | } |
| 310 | |
| 311 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 312 | pub enum McpCommandAvailability { |
| 313 | Available, |
| 314 | Missing, |
| 315 | NotApplicable, |
| 316 | NotChecked, |
| 317 | } |
| 318 | |
| 319 | impl McpCommandAvailability { |
| 320 | pub fn as_str(self) -> &'static str { |
| 321 | match self { |
| 322 | Self::Available => "available", |
| 323 | Self::Missing => "missing", |
| 324 | Self::NotApplicable => "not_applicable", |
| 325 | Self::NotChecked => "not_checked", |
| 326 | } |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | fn env_value<'a>(env: &'a [(OsString, OsString)], name: &str) -> Option<&'a OsStr> { |
| 331 | env.iter() |
| 332 | .rev() |
| 333 | .find(|(key, _)| { |
| 334 | #[cfg(windows)] |
| 335 | { |
| 336 | key.to_string_lossy().eq_ignore_ascii_case(name) |
| 337 | } |
| 338 | #[cfg(not(windows))] |
| 339 | { |
| 340 | key == OsStr::new(name) |
| 341 | } |
| 342 | }) |
| 343 | .map(|(_, value)| value.as_os_str()) |
| 344 | } |
| 345 | |
| 346 | #[cfg(unix)] |
| 347 | fn spawnable_command_file(path: &Path) -> bool { |
| 348 | use std::os::unix::fs::PermissionsExt; |
| 349 | |
| 350 | path.is_file() |
| 351 | && fs::metadata(path) |
| 352 | .map(|metadata| metadata.permissions().mode() & 0o111 != 0) |
| 353 | .unwrap_or(false) |
| 354 | } |
| 355 | |
| 356 | #[cfg(windows)] |
| 357 | fn spawnable_command_file(path: &Path) -> bool { |
| 358 | path.is_file() || (path.extension().is_none() && path.with_extension("exe").is_file()) |
| 359 | } |
| 360 | |
| 361 | #[cfg(not(any(unix, windows)))] |
| 362 | fn spawnable_command_file(path: &Path) -> bool { |
| 363 | path.is_file() |
| 364 | } |
| 365 | |
| 366 | fn path_candidate(dir: &Path, name: &str, cwd: Option<&Path>) -> PathBuf { |
| 367 | #[cfg(unix)] |
| 368 | { |
| 369 | // Unix performs PATH lookup after applying Command::current_dir. That |
| 370 | // includes empty PATH entries, which mean the child's current dir. |
| 371 | if dir.is_relative() |
| 372 | && let Some(cwd) = cwd |
| 373 | { |
| 374 | return cwd.join(dir).join(name); |
| 375 | } |
| 376 | } |
| 377 | #[cfg(not(unix))] |
| 378 | let _ = cwd; |
| 379 | dir.join(name) |
| 380 | } |
| 381 | |
| 382 | fn command_availability_on_path( |
| 383 | name: &str, |
| 384 | env: &[(OsString, OsString)], |
| 385 | cwd: Option<&Path>, |
| 386 | ) -> McpCommandAvailability { |
| 387 | let Some(path) = env_value(env, "PATH") else { |
| 388 | // On Unix execvp falls back to an OS-defined path. On Windows Rust's |
| 389 | // resolver still checks system and parent locations. We cannot prove a |
| 390 | // miss without reproducing platform internals, so remain conservative. |
| 391 | return McpCommandAvailability::NotChecked; |
| 392 | }; |
| 393 | for dir in std::env::split_paths(path) { |
| 394 | let candidate = path_candidate(&dir, name, cwd); |
| 395 | if spawnable_command_file(&candidate) { |
| 396 | return McpCommandAvailability::Available; |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | #[cfg(windows)] |
| 401 | { |
| 402 | // Windows Command resolution also checks the running executable's |
| 403 | // directory, system directories, and the parent PATH after an explicit |
| 404 | // child PATH. A static miss in the child PATH is therefore not proof |
| 405 | // that spawn will fail. PATHEXT is intentionally not consulted: Rust |
| 406 | // only supplies an omitted `.exe`; `.cmd`/`.bat` must be explicit. |
| 407 | return McpCommandAvailability::NotChecked; |
| 408 | } |
| 409 | #[cfg(not(windows))] |
| 410 | { |
| 411 | McpCommandAvailability::Missing |
| 412 | } |
| 413 | } |
| 414 | |
| 415 | /// Inspect an MCP stdio command using the same expanded, sanitized environment |
| 416 | /// as the real spawn path, without starting the configured process. |
| 417 | pub fn static_mcp_command_availability(server: &McpServerConfig) -> Result<McpCommandAvailability> { |
| 418 | static_mcp_command_availability_with_auth_context(server, &ProcessAuthContext) |
| 419 | } |
| 420 | |
| 421 | pub fn static_mcp_command_availability_with_auth_context( |
| 422 | server: &McpServerConfig, |
| 423 | auth_context: &dyn AuthContext, |
| 424 | ) -> Result<McpCommandAvailability> { |
| 425 | if server.url.is_some() { |
| 426 | return Ok(McpCommandAvailability::NotApplicable); |
| 427 | } |
| 428 | let Some(cmd) = server.command.as_deref() else { |
| 429 | return Ok(McpCommandAvailability::NotChecked); |
| 430 | }; |
| 431 | if cmd.is_empty() { |
| 432 | return Ok(McpCommandAvailability::Missing); |
| 433 | } |
| 434 | |
| 435 | // StdioTransport expands every configured env value before spawning, even |
| 436 | // when the command itself is absolute. Mirror that failure boundary here. |
| 437 | let child_env = mcp_stdio_child_env_with_auth_context(server, auth_context)?; |
| 438 | let path = Path::new(cmd); |
| 439 | let is_absolute = path.is_absolute() || cmd.starts_with('/'); |
| 440 | if is_absolute { |
| 441 | return Ok(if spawnable_command_file(path) { |
| 442 | McpCommandAvailability::Available |
| 443 | } else { |
| 444 | McpCommandAvailability::Missing |
| 445 | }); |
| 446 | } |
| 447 | |
| 448 | if is_relative_stdio_path_arg(cmd) { |
| 449 | let Some(cwd) = server.cwd.as_deref() else { |
| 450 | return Ok(McpCommandAvailability::NotChecked); |
| 451 | }; |
| 452 | return Ok(if spawnable_command_file(&cwd.join(path)) { |
| 453 | McpCommandAvailability::Available |
| 454 | } else { |
| 455 | McpCommandAvailability::Missing |
| 456 | }); |
| 457 | } |
| 458 | |
| 459 | Ok(command_availability_on_path( |
| 460 | cmd, |
| 461 | &child_env, |
| 462 | server.cwd.as_deref(), |
| 463 | )) |
| 464 | } |
| 465 | |
| 466 | /// Mask a URL so any embedded credentials in the userinfo portion (e.g. |
| 467 | /// `https://user:secret@host`) are replaced with `***`. Failures fall back to |
| 468 | /// the original string so we don't lose context — we never want masking to |
| 469 | /// produce an empty error. |
| 470 | pub fn mask_url_secrets(url: &str) -> String { |
| 471 | if let Ok(parsed) = reqwest::Url::parse(url) { |
| 472 | let mut clone = parsed.clone(); |
| 473 | if !parsed.username().is_empty() || parsed.password().is_some() { |
| 474 | let _ = clone.set_username("***"); |
| 475 | let _ = clone.set_password(Some("***")); |
| 476 | } |
| 477 | if parsed.query().is_some() { |
| 478 | clone.set_query(Some("***")); |
| 479 | } |
| 480 | clone.set_fragment(None); |
| 481 | return clone.to_string(); |
| 482 | } |
| 483 | url.to_string() |
| 484 | } |
| 485 | |
| 486 | fn redact_values_after_ascii_needle( |
| 487 | output: &mut String, |
| 488 | needle: &str, |
| 489 | terminates: impl Fn(char) -> bool, |
| 490 | ) { |
| 491 | let needle = needle.as_bytes(); |
| 492 | let mut search_from = 0_usize; |
| 493 | while search_from.saturating_add(needle.len()) <= output.len() { |
| 494 | let Some(relative) = output.as_bytes()[search_from..] |
| 495 | .windows(needle.len()) |
| 496 | .position(|candidate| candidate.eq_ignore_ascii_case(needle)) |
| 497 | else { |
| 498 | break; |
| 499 | }; |
| 500 | let value_start = search_from + relative + needle.len(); |
| 501 | let value_end = output[value_start..] |
| 502 | .char_indices() |
| 503 | .find(|(_, ch)| terminates(*ch)) |
| 504 | .map_or(output.len(), |(offset, _)| value_start + offset); |
| 505 | if value_end == value_start { |
| 506 | if value_start == output.len() { |
| 507 | break; |
| 508 | } |
| 509 | // The empty value is already safe. Advance over its ASCII |
| 510 | // separator so a second occurrence later in the body is found. |
| 511 | search_from = value_start + 1; |
| 512 | continue; |
| 513 | } |
| 514 | output.replace_range(value_start..value_end, "***"); |
| 515 | search_from = value_start + 3; |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | /// Mask obvious token-like substrings in a body excerpt before surfacing it. |
| 520 | /// Every occurrence is replaced, not only the first one. |
| 521 | fn redact_body_preview(body: &str) -> String { |
| 522 | let mut out = body.to_string(); |
| 523 | redact_values_after_ascii_needle(&mut out, "bearer ", |ch| { |
| 524 | ch.is_whitespace() || ch == '"' || ch == ',' |
| 525 | }); |
| 526 | for needle in ["api_key=", "apikey=", "api-key=", "token="] { |
| 527 | redact_values_after_ascii_needle(&mut out, needle, |ch| { |
| 528 | ch.is_whitespace() || ch == '&' || ch == '"' || ch == ',' |
| 529 | }); |
| 530 | } |
| 531 | out |
| 532 | } |
| 533 | |
| 534 | /// Read at most `max_bytes` of a reqwest response body and produce a |
| 535 | /// single-line excerpt suitable for an error message. The stream is dropped as |
| 536 | /// soon as the cap is reached, so an unbounded or never-ending error response |
| 537 | /// cannot make diagnostics retain the entire body. Best-effort — if the body |
| 538 | /// can't be read, returns the literal string `<no body>`. |
| 539 | pub async fn bounded_body_excerpt(response: reqwest::Response, max_bytes: usize) -> String { |
| 540 | use futures_util::StreamExt; |
| 541 | |
| 542 | let declared_truncated = response |
| 543 | .content_length() |
| 544 | .is_some_and(|length| length > max_bytes as u64); |
| 545 | let mut stream = response.bytes_stream(); |
| 546 | let mut body = Vec::with_capacity(max_bytes.min(8 * 1024)); |
| 547 | let mut truncated = declared_truncated; |
| 548 | |
| 549 | while body.len() < max_bytes { |
| 550 | let Some(chunk) = stream.next().await else { |
| 551 | break; |
| 552 | }; |
| 553 | let Ok(chunk) = chunk else { |
| 554 | break; |
| 555 | }; |
| 556 | let remaining = max_bytes - body.len(); |
| 557 | if chunk.len() > remaining { |
| 558 | body.extend_from_slice(&chunk[..remaining]); |
| 559 | truncated = true; |
| 560 | break; |
| 561 | } |
| 562 | body.extend_from_slice(&chunk); |
| 563 | if body.len() == max_bytes { |
| 564 | // For a chunked response there is no length that proves EOF. Stop |
| 565 | // now rather than polling an attacker-controlled stream again. |
| 566 | truncated = true; |
| 567 | } |
| 568 | } |
| 569 | |
| 570 | if body.is_empty() { |
| 571 | return "<no body>".to_string(); |
| 572 | } |
| 573 | |
| 574 | let one_line = String::from_utf8_lossy(&body).replace(['\n', '\r'], " "); |
| 575 | let suffix = if truncated { "…" } else { "" }; |
| 576 | format!("{}{}", redact_body_preview(&one_line), suffix) |
| 577 | } |
| 578 | |
| 579 | fn invalid_json_preview(bytes: &[u8]) -> String { |
| 580 | let body_text = String::from_utf8_lossy(bytes); |
| 581 | if body_text.is_empty() { |
| 582 | return "<empty>".to_string(); |
| 583 | } |
| 584 | |
| 585 | let trimmed: String = body_text.chars().take(ERROR_BODY_PREVIEW_BYTES).collect(); |
| 586 | let suffix = if body_text.chars().count() > ERROR_BODY_PREVIEW_BYTES { |
| 587 | "…" |
| 588 | } else { |
| 589 | "" |
| 590 | }; |
| 591 | let one_line = trimmed.replace(['\n', '\r'], " "); |
| 592 | format!("{}{}", redact_body_preview(&one_line), suffix) |
| 593 | } |
| 594 | |
| 595 | // === Configuration Types === |
| 596 | |
| 597 | #[derive(Debug, Clone)] |
| 598 | pub struct ReviewedPluginMcpSource { |
| 599 | authority: codewhale_config::PluginAuthority, |
| 600 | approved_remote_endpoint: Option<String>, |
| 601 | approved_remote_origin: Option<String>, |
| 602 | host_environment: Arc<codewhale_plugins::HostEnvironment>, |
| 603 | native_mcp: Option<crate::extension_host::native_mcp::NativeMcpRef>, |
| 604 | } |
| 605 | |
| 606 | impl ReviewedPluginMcpSource { |
| 607 | /// The plugin bundle that contributes this server. The panel names it |
| 608 | /// rather than parsing the synthesized `plugin-<len>-<plugin>-<server>` |
| 609 | /// key, which is an encoding detail and not a contract. |
| 610 | pub fn plugin_name(&self) -> &str { |
| 611 | &self.authority.plugin_name |
| 612 | } |
| 613 | |
| 614 | fn from_authority( |
| 615 | authority: codewhale_config::PluginAuthority, |
| 616 | remote_endpoint: Option<&str>, |
| 617 | host_environment: Arc<codewhale_plugins::HostEnvironment>, |
| 618 | ) -> Result<Self> { |
| 619 | let (approved_remote_endpoint, approved_remote_origin) = match remote_endpoint { |
| 620 | Some(endpoint) => reviewed_remote_endpoint_identity(endpoint) |
| 621 | .map(|(endpoint, origin)| (Some(endpoint), Some(origin)))?, |
| 622 | None => (None, None), |
| 623 | }; |
| 624 | Ok(Self { |
| 625 | authority, |
| 626 | approved_remote_endpoint, |
| 627 | approved_remote_origin, |
| 628 | host_environment, |
| 629 | native_mcp: None, |
| 630 | }) |
| 631 | } |
| 632 | |
| 633 | pub fn validate_before_stdio_spawn(&self, server_name: &str) -> Result<()> { |
| 634 | self.validate_before_use(server_name, "spawn") |
| 635 | } |
| 636 | |
| 637 | pub fn prepare_stdio_launch( |
| 638 | &self, |
| 639 | server_name: &str, |
| 640 | command: &str, |
| 641 | args: &[String], |
| 642 | cwd: Option<&Path>, |
| 643 | ) -> Result<ReviewedStdioLaunch> { |
| 644 | self.validate_before_stdio_spawn(server_name)?; |
| 645 | let staged_root = codewhale_plugins::agent_plugin::plugin_root_for_manifest( |
| 646 | &self.authority.staged_manifest, |
| 647 | ) |
| 648 | .context("reviewed plugin stage manifest has no bundle root")?; |
| 649 | let validated = codewhale_plugins::manifest::PluginManifest::validate_from_path( |
| 650 | &self.authority.staged_manifest, |
| 651 | ) |
| 652 | .map_err(|_| anyhow::anyhow!("reviewed plugin stage could not be opened for launch"))?; |
| 653 | if validated.content_hash != self.authority.content_hash |
| 654 | || validated.capability_hash != self.authority.capability_hash |
| 655 | { |
| 656 | anyhow::bail!("reviewed plugin stage changed before stdio launch"); |
| 657 | } |
| 658 | |
| 659 | let mut launch = ReviewedStdioLaunch { |
| 660 | command: std::ffi::OsString::from(command), |
| 661 | args: args.iter().map(std::ffi::OsString::from).collect(), |
| 662 | cwd: cwd.map(Path::to_path_buf), |
| 663 | opened_files: Vec::new(), |
| 664 | #[cfg(unix)] |
| 665 | cwd_fd: None, |
| 666 | }; |
| 667 | if Path::new(command).is_absolute() { |
| 668 | launch.bind_command(staged_root, Path::new(command), &validated.file_hashes)?; |
| 669 | } |
| 670 | // Darwin descriptor paths lose Node's module filename, package.json |
| 671 | // context and relative-import directory (#5916). Keep the staged path |
| 672 | // for .js/.cjs and multi-file .mjs entries, after bind_file verifies |
| 673 | // their bytes. Node reopens these paths; this is not atomic descriptor |
| 674 | // execution. Sibling modules already use the reviewed staged paths. |
| 675 | #[cfg(target_os = "macos")] |
| 676 | let node_entry_index = is_node_command(command) |
| 677 | .then(|| node_script_entry_index(args)) |
| 678 | .flatten() |
| 679 | .filter(|&index| { |
| 680 | let path = Path::new(&args[index]); |
| 681 | path.is_absolute() |
| 682 | && path.starts_with(staged_root) |
| 683 | && path.extension().is_some_and(|extension| { |
| 684 | matches!(extension.to_str(), Some("mjs" | "js" | "cjs")) |
| 685 | }) |
| 686 | }); |
| 687 | #[cfg(target_os = "macos")] |
| 688 | let node_entry_keeps_path = node_entry_index.is_some_and(|index| { |
| 689 | node_entry_needs_staged_path( |
| 690 | staged_root, |
| 691 | Path::new(&args[index]), |
| 692 | &validated.file_hashes, |
| 693 | ) |
| 694 | }); |
| 695 | for (index, argument) in args.iter().enumerate() { |
| 696 | let path = Path::new(argument); |
| 697 | if path.is_absolute() && path.starts_with(staged_root) && path.is_file() { |
| 698 | let bound = launch.bind_file(staged_root, path, &validated.file_hashes)?; |
| 699 | #[cfg(target_os = "macos")] |
| 700 | if node_entry_keeps_path && node_entry_index == Some(index) { |
| 701 | continue; |
| 702 | } |
| 703 | launch.args[index] = bound; |
| 704 | } |
| 705 | } |
| 706 | #[cfg(target_os = "macos")] |
| 707 | if let Some(entry_index) = node_entry_index |
| 708 | && !node_entry_keeps_path |
| 709 | { |
| 710 | launch.args = node_esm_descriptor_args(&launch.args, entry_index); |
| 711 | } |
| 712 | if let Some(cwd) = cwd { |
| 713 | if !cwd.starts_with(staged_root) { |
| 714 | anyhow::bail!("reviewed plugin stdio cwd escaped its staged root"); |
| 715 | } |
| 716 | launch.bind_cwd(cwd)?; |
| 717 | } |
| 718 | // A final authority pass detects source/stage and capability drift |
| 719 | // while handles were opened. Retained Node entry paths and imports |
| 720 | // are reopened after this check; their owner-only, read-only stage is |
| 721 | // not an atomic handle binding or an OS sandbox. |
| 722 | self.validate_before_stdio_spawn(server_name)?; |
| 723 | Ok(launch) |
| 724 | } |
| 725 | |
| 726 | fn required_capability(&self) -> codewhale_plugins::activation::PluginActivationCapability { |
| 727 | if self.native_mcp.is_some() { |
| 728 | return codewhale_plugins::activation::PluginActivationCapability::Native; |
| 729 | } |
| 730 | if self.approved_remote_endpoint.is_some() { |
| 731 | codewhale_plugins::activation::PluginActivationCapability::McpRemote |
| 732 | } else { |
| 733 | codewhale_plugins::activation::PluginActivationCapability::McpStdio |
| 734 | } |
| 735 | } |
| 736 | |
| 737 | pub fn validate_before_use(&self, server_name: &str, operation: &str) -> Result<()> { |
| 738 | if let Some(native) = self.native_mcp.as_ref() { |
| 739 | native.validate().map_err(anyhow::Error::msg)?; |
| 740 | } |
| 741 | let remediation = format!( |
| 742 | "Run `/plugin reload`, inspect `/plugin show {0}`, then repeat the displayed trust command and `/plugin enable {0}` before retrying", |
| 743 | self.authority.plugin_name |
| 744 | ); |
| 745 | codewhale_plugins::registry::verify_plugin_component_authority( |
| 746 | &self.authority, |
| 747 | self.required_capability(), |
| 748 | ) |
| 749 | .map_err(|reason| { |
| 750 | anyhow::anyhow!( |
| 751 | "Refusing to {operation} MCP server '{server_name}' from plugin bundle `{}`: {reason}. {remediation}", |
| 752 | self.authority.plugin_name |
| 753 | ) |
| 754 | }) |
| 755 | } |
| 756 | |
| 757 | fn validate_remote_endpoint(&self, server_name: &str, endpoint: &str) -> Result<()> { |
| 758 | let (endpoint, origin) = reviewed_remote_endpoint_identity(endpoint)?; |
| 759 | if self.approved_remote_endpoint.as_deref() != Some(endpoint.as_str()) |
| 760 | || self.approved_remote_origin.as_deref() != Some(origin.as_str()) |
| 761 | { |
| 762 | anyhow::bail!( |
| 763 | "Refusing MCP server '{server_name}': its remote endpoint no longer matches the reviewed plugin origin" |
| 764 | ); |
| 765 | } |
| 766 | Ok(()) |
| 767 | } |
| 768 | |
| 769 | fn catalog_is_current(&self) -> bool { |
| 770 | if self |
| 771 | .native_mcp |
| 772 | .as_ref() |
| 773 | .is_some_and(|native| native.validate().is_err()) |
| 774 | { |
| 775 | return false; |
| 776 | } |
| 777 | |
| 778 | // Catalog exposure is an authority boundary too: stale tool, prompt, |
| 779 | // or resource descriptions can steer the model even when the later |
| 780 | // operation would be denied. Revalidate both the mutable reviewed |
| 781 | // source and the Codewhale-owned stage before publishing any entry. |
| 782 | codewhale_plugins::registry::verify_plugin_component_authority( |
| 783 | &self.authority, |
| 784 | self.required_capability(), |
| 785 | ) |
| 786 | .is_ok() |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | /// Preserve .js package type lookup, .cjs module semantics and multi-file |
| 791 | /// .mjs relative imports. A lone .mjs retains the existing descriptor launch. |
| 792 | #[cfg(target_os = "macos")] |
| 793 | fn node_entry_needs_staged_path( |
| 794 | staged_root: &Path, |
| 795 | entry: &Path, |
| 796 | file_hashes: &std::collections::BTreeMap<PathBuf, String>, |
| 797 | ) -> bool { |
| 798 | let Ok(entry) = entry.strip_prefix(staged_root) else { |
| 799 | return false; |
| 800 | }; |
| 801 | if entry |
| 802 | .extension() |
| 803 | .is_some_and(|extension| matches!(extension.to_str(), Some("js" | "cjs"))) |
| 804 | { |
| 805 | return true; |
| 806 | } |
| 807 | file_hashes.keys().any(|path| { |
| 808 | path != entry |
| 809 | && path.extension().is_some_and(|extension| { |
| 810 | matches!( |
| 811 | extension.to_string_lossy().as_ref(), |
| 812 | "mjs" | "js" | "cjs" | "node" | "wasm" |
| 813 | ) |
| 814 | }) |
| 815 | }) |
| 816 | } |
| 817 | |
| 818 | /// Find the script operand, never a preload's value or an argument belonging |
| 819 | /// to an earlier script. Unknown option layouts get no Node-specific rewrite; |
| 820 | /// the generic reviewed-file binder still applies. |
| 821 | #[cfg(target_os = "macos")] |
| 822 | fn node_script_entry_index(args: &[impl AsRef<std::ffi::OsStr>]) -> Option<usize> { |
| 823 | let mut index = 0; |
| 824 | while let Some(argument) = args.get(index) { |
| 825 | let argument = argument.as_ref().to_str()?; |
| 826 | match argument { |
| 827 | "--" => return (index + 1 < args.len()).then_some(index + 1), |
| 828 | "-" | "-e" | "--eval" | "-p" | "--print" | "--run" | "--test" | "-c" | "--check" |
| 829 | | "-i" | "--interactive" | "--input-type" => return None, |
| 830 | "-r" |
| 831 | | "--require" |
| 832 | | "--import" |
| 833 | | "--loader" |
| 834 | | "--experimental-loader" |
| 835 | | "-C" |
| 836 | | "--conditions" |
| 837 | | "--max-old-space-size" |
| 838 | | "--stack-size" => index += 2, |
| 839 | "--no-warnings" |
| 840 | | "--trace-warnings" |
| 841 | | "--trace-deprecation" |
| 842 | | "--no-deprecation" |
| 843 | | "--enable-source-maps" |
| 844 | | "--preserve-symlinks" |
| 845 | | "--preserve-symlinks-main" |
| 846 | | "--abort-on-uncaught-exception" |
| 847 | | "--expose-gc" |
| 848 | | "--jitless" => index += 1, |
| 849 | _ if argument.starts_with("--eval=") |
| 850 | || argument.starts_with("--print=") |
| 851 | || argument.starts_with("--run=") |
| 852 | || argument.starts_with("--input-type=") => |
| 853 | { |
| 854 | return None; |
| 855 | } |
| 856 | _ if argument.starts_with("--") && argument.contains('=') => index += 1, |
| 857 | _ if argument.starts_with('-') => return None, |
| 858 | _ => return Some(index), |
| 859 | } |
| 860 | } |
| 861 | None |
| 862 | } |
| 863 | |
| 864 | fn is_node_command(command: &str) -> bool { |
| 865 | Path::new(command) |
| 866 | .file_name() |
| 867 | .and_then(|name| name.to_str()) |
| 868 | .is_some_and(|name| matches!(name, "node" | "nodejs" | "node.exe" | "nodejs.exe")) |
| 869 | } |
| 870 | |
| 871 | /// Rewrite a Node launch so a reviewed `.mjs` entrypoint keeps ESM semantics |
| 872 | /// after Darwin's reviewed-launch binding replaced its staged path with an |
| 873 | /// inherited `/dev/fd/N` descriptor. |
| 874 | /// |
| 875 | /// Node determines the entrypoint module type from its filename and a |
| 876 | /// descriptor path has no extension, so `node /dev/fd/N` exits without |
| 877 | /// evaluating the module. `--experimental-default-type=module` used to fix |
| 878 | /// that but was removed from current Node releases (Node 25 rejects it as a |
| 879 | /// bad option, which killed the child before the MCP handshake). `--import` |
| 880 | /// has loaded its specifier as an ES module on every supported release, so |
| 881 | /// the reviewed bytes are imported by descriptor once, `-e ""` supplies an |
| 882 | /// empty main, and the descriptor path is echoed after `--` so |
| 883 | /// `process.argv[1]` and the script's own arguments keep the file-mode shape. |
| 884 | /// Node options that preceded the entrypoint stay in front; anything after it |
| 885 | /// is passed through untouched. When the `.mjs` file is not the first |
| 886 | /// positional argument it is not the entrypoint and the launch is left alone. |
| 887 | #[cfg(target_os = "macos")] |
| 888 | fn node_esm_descriptor_args( |
| 889 | args: &[std::ffi::OsString], |
| 890 | entry_index: usize, |
| 891 | ) -> Vec<std::ffi::OsString> { |
| 892 | if node_script_entry_index(args) != Some(entry_index) { |
| 893 | return args.to_vec(); |
| 894 | } |
| 895 | let bound_entry = args[entry_index].clone(); |
| 896 | let prefix_end = entry_index - usize::from(entry_index > 0 && args[entry_index - 1] == "--"); |
| 897 | let mut rewritten: Vec<std::ffi::OsString> = args[..prefix_end].to_vec(); |
| 898 | rewritten.push(std::ffi::OsString::from("--import")); |
| 899 | rewritten.push(bound_entry.clone()); |
| 900 | rewritten.push(std::ffi::OsString::from("-e")); |
| 901 | rewritten.push(std::ffi::OsString::from("")); |
| 902 | rewritten.push(std::ffi::OsString::from("--")); |
| 903 | rewritten.push(bound_entry); |
| 904 | rewritten.extend(args[entry_index + 1..].iter().cloned()); |
| 905 | rewritten |
| 906 | } |
| 907 | |
| 908 | pub struct ReviewedStdioLaunch { |
| 909 | pub command: std::ffi::OsString, |
| 910 | pub args: Vec<std::ffi::OsString>, |
| 911 | pub cwd: Option<PathBuf>, |
| 912 | /// Kept for the child lifetime. Windows opens deny write/delete sharing; |
| 913 | /// Unix normally uses inherited descriptors; macOS Node entries needing |
| 914 | /// module path context are hash-checked here, then reopened by path. |
| 915 | pub opened_files: Vec<fs::File>, |
| 916 | #[cfg(unix)] |
| 917 | pub cwd_fd: Option<fs::File>, |
| 918 | } |
| 919 | |
| 920 | impl ReviewedStdioLaunch { |
| 921 | fn bind_command( |
| 922 | &mut self, |
| 923 | staged_root: &Path, |
| 924 | path: &Path, |
| 925 | expected_hashes: &std::collections::BTreeMap<PathBuf, String>, |
| 926 | ) -> Result<()> { |
| 927 | let bound_path = self.bind_file(staged_root, path, expected_hashes)?; |
| 928 | #[cfg(not(target_os = "macos"))] |
| 929 | { |
| 930 | self.command = bound_path; |
| 931 | Ok(()) |
| 932 | } |
| 933 | #[cfg(target_os = "macos")] |
| 934 | { |
| 935 | use std::os::unix::fs::FileExt as _; |
| 936 | |
| 937 | // Darwin devfs deliberately rejects execve("/dev/fd/N"). Bind |
| 938 | // reviewed scripts by running the interpreter declared in their |
| 939 | // exact hashed shebang and passing the inherited descriptor as |
| 940 | // input. Native Mach-O bundle commands have no fexecve/execveat |
| 941 | // equivalent on Darwin, so fail closed and require the manifest |
| 942 | // to name a bare interpreter with the bundle file as an argument. |
| 943 | let file = self |
| 944 | .opened_files |
| 945 | .last() |
| 946 | .context("reviewed command handle disappeared")?; |
| 947 | let mut prefix = [0_u8; 4_096]; |
| 948 | let read = file |
| 949 | .read_at(&mut prefix, 0) |
| 950 | .context("read reviewed command shebang")?; |
| 951 | let prefix = &prefix[..read]; |
| 952 | let line_end = prefix |
| 953 | .iter() |
| 954 | .position(|byte| *byte == b'\n') |
| 955 | .unwrap_or(prefix.len()); |
| 956 | let line = std::str::from_utf8(&prefix[..line_end]) |
| 957 | .context("reviewed script shebang is not UTF-8")?; |
| 958 | let shebang = line.strip_prefix("#!").map(str::trim).filter(|s| !s.is_empty()) |
| 959 | .context( |
| 960 | "Darwin cannot execute a reviewed native bundle command by descriptor; use a shebang script or declare a bare interpreter command plus the script argument", |
| 961 | )?; |
| 962 | let mut words = shlex::split(shebang) |
| 963 | .context("reviewed script shebang could not be parsed safely")?; |
| 964 | let interpreter = words |
| 965 | .first() |
| 966 | .filter(|word| Path::new(word).is_absolute()) |
| 967 | .context("reviewed script shebang interpreter must be absolute")? |
| 968 | .clone(); |
| 969 | words.remove(0); |
| 970 | let mut args = words |
| 971 | .into_iter() |
| 972 | .map(std::ffi::OsString::from) |
| 973 | .collect::<Vec<_>>(); |
| 974 | args.push(bound_path); |
| 975 | args.append(&mut self.args); |
| 976 | self.command = std::ffi::OsString::from(interpreter); |
| 977 | self.args = args; |
| 978 | Ok(()) |
| 979 | } |
| 980 | } |
| 981 | |
| 982 | fn bind_file( |
| 983 | &mut self, |
| 984 | staged_root: &Path, |
| 985 | path: &Path, |
| 986 | expected_hashes: &std::collections::BTreeMap<PathBuf, String>, |
| 987 | ) -> Result<std::ffi::OsString> { |
| 988 | let relative = path |
| 989 | .strip_prefix(staged_root) |
| 990 | .context("reviewed plugin executable escaped its staged root")?; |
| 991 | let expected = expected_hashes |
| 992 | .get(relative) |
| 993 | .context("reviewed plugin executable is absent from its byte inventory")?; |
| 994 | let mut file = open_reviewed_launch_file(path)?; |
| 995 | let mut hasher = sha2::Sha256::new(); |
| 996 | hasher.update(b"codewhale-plugin-file-bytes-v1\0"); |
| 997 | let mut buffer = [0_u8; 64 * 1024]; |
| 998 | loop { |
| 999 | let read = file |
| 1000 | .read(&mut buffer) |
| 1001 | .context("read reviewed launch file")?; |
| 1002 | if read == 0 { |
| 1003 | break; |
| 1004 | } |
| 1005 | hasher.update(&buffer[..read]); |
| 1006 | } |
| 1007 | let actual = hasher |
| 1008 | .finalize() |
| 1009 | .iter() |
| 1010 | .map(|byte| format!("{byte:02x}")) |
| 1011 | .collect::<String>(); |
| 1012 | if &actual != expected { |
| 1013 | anyhow::bail!("reviewed plugin executable bytes changed before spawn"); |
| 1014 | } |
| 1015 | file.seek(std::io::SeekFrom::Start(0)) |
| 1016 | .context("rewind reviewed launch file after verification")?; |
| 1017 | |
| 1018 | #[cfg(unix)] |
| 1019 | let launch_path = { |
| 1020 | use std::os::fd::AsRawFd as _; |
| 1021 | let fd = file.as_raw_fd(); |
| 1022 | // SAFETY: `fd` is owned by `file`; clearing only FD_CLOEXEC keeps |
| 1023 | // that same descriptor available across the imminent exec. |
| 1024 | let flags = unsafe { libc::fcntl(fd, libc::F_GETFD) }; |
| 1025 | if flags < 0 || unsafe { libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) } < 0 |
| 1026 | { |
| 1027 | anyhow::bail!("failed to inherit reviewed plugin executable descriptor"); |
| 1028 | } |
| 1029 | #[cfg(target_os = "linux")] |
| 1030 | let prefix = "/proc/self/fd"; |
| 1031 | #[cfg(not(target_os = "linux"))] |
| 1032 | let prefix = "/dev/fd"; |
| 1033 | std::ffi::OsString::from(format!("{prefix}/{fd}")) |
| 1034 | }; |
| 1035 | |
| 1036 | #[cfg(not(unix))] |
| 1037 | let launch_path = path.as_os_str().to_os_string(); |
| 1038 | |
| 1039 | self.opened_files.push(file); |
| 1040 | Ok(launch_path) |
| 1041 | } |
| 1042 | |
| 1043 | fn bind_cwd(&mut self, cwd: &Path) -> Result<()> { |
| 1044 | #[cfg(unix)] |
| 1045 | { |
| 1046 | use std::os::unix::fs::OpenOptionsExt as _; |
| 1047 | let file = fs::OpenOptions::new() |
| 1048 | .read(true) |
| 1049 | .custom_flags(libc::O_DIRECTORY | libc::O_NOFOLLOW | libc::O_CLOEXEC) |
| 1050 | .open(cwd) |
| 1051 | .context("open reviewed plugin cwd without following links")?; |
| 1052 | self.cwd_fd = Some(file); |
| 1053 | self.cwd = None; |
| 1054 | } |
| 1055 | #[cfg(windows)] |
| 1056 | { |
| 1057 | use std::os::windows::fs::{MetadataExt as _, OpenOptionsExt as _}; |
| 1058 | let file = fs::OpenOptions::new() |
| 1059 | .read(true) |
| 1060 | .share_mode(0x0000_0001) // FILE_SHARE_READ only |
| 1061 | .custom_flags(0x0220_0000) // BACKUP_SEMANTICS | OPEN_REPARSE_POINT |
| 1062 | .open(cwd) |
| 1063 | .context("open reviewed plugin cwd without write/delete sharing")?; |
| 1064 | let metadata = file |
| 1065 | .metadata() |
| 1066 | .context("inspect reviewed plugin cwd handle")?; |
| 1067 | if !metadata.is_dir() || metadata.file_attributes() & 0x0000_0400 != 0 { |
| 1068 | anyhow::bail!("reviewed plugin cwd is a reparse point or non-directory"); |
| 1069 | } |
| 1070 | self.opened_files.push(file); |
| 1071 | } |
| 1072 | Ok(()) |
| 1073 | } |
| 1074 | } |
| 1075 | |
| 1076 | #[cfg(unix)] |
| 1077 | fn open_reviewed_launch_file(path: &Path) -> Result<fs::File> { |
| 1078 | codewhale_util::bundle_file::open_bundle_file(path) |
| 1079 | .context("open reviewed launch file without following links") |
| 1080 | } |
| 1081 | |
| 1082 | #[cfg(windows)] |
| 1083 | fn open_reviewed_launch_file(path: &Path) -> Result<fs::File> { |
| 1084 | codewhale_util::bundle_file::open_bundle_file(path) |
| 1085 | .context("open reviewed launch file without links, hard links, or write/delete sharing") |
| 1086 | } |
| 1087 | |
| 1088 | #[cfg(all(not(unix), not(windows)))] |
| 1089 | fn open_reviewed_launch_file(path: &Path) -> Result<fs::File> { |
| 1090 | fs::File::open(path).context("open reviewed launch file") |
| 1091 | } |
| 1092 | |
| 1093 | fn reviewed_remote_endpoint_identity(endpoint: &str) -> Result<(String, String)> { |
| 1094 | let endpoint = |
| 1095 | reqwest::Url::parse(endpoint).context("reviewed plugin MCP endpoint is invalid")?; |
| 1096 | if !endpoint.username().is_empty() || endpoint.password().is_some() { |
| 1097 | anyhow::bail!("reviewed plugin MCP endpoint must not contain user information"); |
| 1098 | } |
| 1099 | if endpoint.query().is_some() || endpoint.fragment().is_some() { |
| 1100 | anyhow::bail!("reviewed plugin MCP endpoint must not contain a query or fragment"); |
| 1101 | } |
| 1102 | let origin = reviewed_remote_origin(&endpoint) |
| 1103 | .ok_or_else(|| anyhow::anyhow!("reviewed plugin MCP endpoint has an unsafe origin"))?; |
| 1104 | Ok((endpoint.to_string(), origin)) |
| 1105 | } |
| 1106 | |
| 1107 | fn reviewed_remote_origin(endpoint: &reqwest::Url) -> Option<String> { |
| 1108 | if !endpoint.username().is_empty() || endpoint.password().is_some() { |
| 1109 | return None; |
| 1110 | } |
| 1111 | let host = endpoint.host_str()?; |
| 1112 | let allowed_scheme = endpoint.scheme() == "https" |
| 1113 | || (endpoint.scheme() == "http" |
| 1114 | && (host.eq_ignore_ascii_case("localhost") |
| 1115 | || host |
| 1116 | .trim_matches(['[', ']']) |
| 1117 | .parse::<std::net::IpAddr>() |
| 1118 | .is_ok_and(|address| address.is_loopback()))); |
| 1119 | allowed_scheme.then(|| endpoint.origin().ascii_serialization()) |
| 1120 | } |
| 1121 | |
| 1122 | fn reviewed_redirect_matches_origin(endpoint: &reqwest::Url, approved_origin: &str) -> bool { |
| 1123 | reviewed_remote_origin(endpoint).as_deref() == Some(approved_origin) |
| 1124 | } |
| 1125 | |
| 1126 | // === MCP Tool Definition === |
| 1127 | |
| 1128 | /// Tool discovered from an MCP server |
| 1129 | #[derive(Debug, Clone, PartialEq, Deserialize, Serialize)] |
| 1130 | pub struct McpTool { |
| 1131 | pub name: String, |
| 1132 | #[serde(default)] |
| 1133 | pub description: Option<String>, |
| 1134 | #[serde(rename = "inputSchema", default)] |
| 1135 | pub input_schema: serde_json::Value, |
| 1136 | /// Behaviour hints the server declares (MCP `ToolAnnotations`). They are |
| 1137 | /// claims, not proof: only a reviewed plugin's hints relax approval, and |
| 1138 | /// only toward what the plugin review already covers (CW-11). |
| 1139 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 1140 | pub annotations: Option<McpToolAnnotations>, |
| 1141 | } |
| 1142 | |
| 1143 | pub(crate) fn named_batch_members( |
| 1144 | schema: &serde_json::Value, |
| 1145 | ) -> Option<(&str, &[serde_json::Value])> { |
| 1146 | let required = schema.get("required")?.as_array()?; |
| 1147 | let fields = schema.get("properties")?.as_object()?; |
| 1148 | required |
| 1149 | .iter() |
| 1150 | .filter_map(serde_json::Value::as_str) |
| 1151 | .find_map(|name| { |
| 1152 | let steps = fields.get(name)?; |
| 1153 | if steps.get("type")?.as_str()? != "array" |
| 1154 | || !(1..=50).contains(&steps.get("maxItems")?.as_u64()?) |
| 1155 | { |
| 1156 | return None; |
| 1157 | } |
| 1158 | let step = steps.get("items")?; |
| 1159 | if !step |
| 1160 | .get("required")? |
| 1161 | .as_array()? |
| 1162 | .iter() |
| 1163 | .any(|key| key == "tool") |
| 1164 | || step.pointer("/properties/arguments/type")?.as_str()? != "object" |
| 1165 | || step.pointer("/properties/tool/type")?.as_str()? != "string" |
| 1166 | { |
| 1167 | return None; |
| 1168 | } |
| 1169 | let names = step.pointer("/properties/tool/enum")?.as_array()?; |
| 1170 | (!names.is_empty() && names.len() <= 128 && names.iter().all(|v| v.is_string())) |
| 1171 | .then_some((name, names.as_slice())) |
| 1172 | }) |
| 1173 | } |
| 1174 | |
| 1175 | fn batch_member_signature(tool: &McpTool) -> Option<String> { |
| 1176 | fn identifier(value: &str) -> bool { |
| 1177 | !value.is_empty() |
| 1178 | && value.len() <= 64 |
| 1179 | && value |
| 1180 | .bytes() |
| 1181 | .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-') |
| 1182 | } |
| 1183 | if !identifier(&tool.name) { |
| 1184 | return None; |
| 1185 | } |
| 1186 | let fields = tool.input_schema.get("properties")?.as_object()?; |
| 1187 | if fields.len() > 24 || !fields.keys().all(|key| identifier(key)) { |
| 1188 | return None; |
| 1189 | } |
| 1190 | let required = tool.input_schema.get("required").and_then(|v| v.as_array()); |
| 1191 | let keys = fields |
| 1192 | .iter() |
| 1193 | .map(|(key, value)| { |
| 1194 | let mut field = key.clone(); |
| 1195 | if required.is_none_or(|names| !names.iter().any(|name| name == key)) { |
| 1196 | field.push('?'); |
| 1197 | } |
| 1198 | if let Some(values) = value.get("enum").and_then(|v| v.as_array()) |
| 1199 | && (1..=6).contains(&values.len()) |
| 1200 | && values.iter().all(|v| v.as_str().is_some_and(identifier)) |
| 1201 | { |
| 1202 | field.push('='); |
| 1203 | field.push_str( |
| 1204 | &values |
| 1205 | .iter() |
| 1206 | .filter_map(|v| v.as_str()) |
| 1207 | .collect::<Vec<_>>() |
| 1208 | .join("|"), |
| 1209 | ); |
| 1210 | } |
| 1211 | if let (Some(min), Some(max)) = ( |
| 1212 | value.get("minimum").filter(|v| v.is_number()), |
| 1213 | value.get("maximum").filter(|v| v.is_number()), |
| 1214 | ) { |
| 1215 | field.push_str(&format!("={min}..{max}")); |
| 1216 | } |
| 1217 | field |
| 1218 | }) |
| 1219 | .collect::<Vec<_>>(); |
| 1220 | Some(format!("{}({})", tool.name, keys.join(","))) |
| 1221 | } |
| 1222 | |
| 1223 | /// The subset of MCP `ToolAnnotations` the approval path reads. |
| 1224 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize, Serialize)] |
| 1225 | pub struct McpToolAnnotations { |
| 1226 | #[serde( |
| 1227 | rename = "readOnlyHint", |
| 1228 | default, |
| 1229 | skip_serializing_if = "Option::is_none" |
| 1230 | )] |
| 1231 | pub read_only_hint: Option<bool>, |
| 1232 | #[serde( |
| 1233 | rename = "destructiveHint", |
| 1234 | default, |
| 1235 | skip_serializing_if = "Option::is_none" |
| 1236 | )] |
| 1237 | pub destructive_hint: Option<bool>, |
| 1238 | } |
| 1239 | |
| 1240 | /// How the approval path may treat one model-visible MCP tool, from its |
| 1241 | /// server's declared annotations (CW-11). |
| 1242 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1243 | pub enum McpToolApprovalHint { |
| 1244 | /// A reviewed, enabled plugin declares the tool read-only and not |
| 1245 | /// destructive: it runs without a prompt, like the built-in read tools. |
| 1246 | TrustedReadOnly, |
| 1247 | /// The server declares the tool destructive: session-wide auto-approve |
| 1248 | /// does not cover it, so each call keeps its prompt. |
| 1249 | Destructive, |
| 1250 | } |
| 1251 | |
| 1252 | /// Annotation-derived approval hints for the MCP tools of every live |
| 1253 | /// catalog, keyed by model tool name. Filled where the catalog is built |
| 1254 | /// (`McpPool::to_api_tools`, once per turn) and read by the side-effect-free |
| 1255 | /// call preparation, which has no pool handle. |
| 1256 | /// |
| 1257 | /// Known limitation: the map is process-wide. Two pools in one process that |
| 1258 | /// expose the same model tool name from different servers overwrite each |
| 1259 | /// other's hint; the last catalog built wins. Plugin servers carry |
| 1260 | /// synthesized `plugin-…` names, so this needs a user server deliberately |
| 1261 | /// named like a plugin server. |
| 1262 | static MCP_TOOL_APPROVAL_HINTS: std::sync::LazyLock<RwLock<HashMap<String, McpToolApprovalHint>>> = |
| 1263 | std::sync::LazyLock::new(|| RwLock::new(HashMap::new())); |
| 1264 | |
| 1265 | /// The approval hint recorded for a model-visible MCP tool name, if any. |
| 1266 | #[must_use] |
| 1267 | pub fn mcp_tool_approval_hint(model_tool_name: &str) -> Option<McpToolApprovalHint> { |
| 1268 | MCP_TOOL_APPROVAL_HINTS.read().get(model_tool_name).copied() |
| 1269 | } |
| 1270 | |
| 1271 | #[cfg(any(test, feature = "test-support"))] |
| 1272 | pub fn set_mcp_tool_approval_hint_for_test( |
| 1273 | model_tool_name: &str, |
| 1274 | hint: Option<McpToolApprovalHint>, |
| 1275 | ) { |
| 1276 | let mut hints = MCP_TOOL_APPROVAL_HINTS.write(); |
| 1277 | match hint { |
| 1278 | Some(hint) => hints.insert(model_tool_name.to_string(), hint), |
| 1279 | None => hints.remove(model_tool_name), |
| 1280 | }; |
| 1281 | } |
| 1282 | |
| 1283 | fn approval_hint_for(tool: &McpTool, reviewed_plugin: bool) -> Option<McpToolApprovalHint> { |
| 1284 | let annotations = tool.annotations.unwrap_or_default(); |
| 1285 | // An absent destructiveHint defaults to true in the MCP spec, but only |
| 1286 | // when readOnlyHint is false; a read-only tool is not destructive. |
| 1287 | if annotations.destructive_hint == Some(true) { |
| 1288 | return Some(McpToolApprovalHint::Destructive); |
| 1289 | } |
| 1290 | (reviewed_plugin && annotations.read_only_hint == Some(true)) |
| 1291 | .then_some(McpToolApprovalHint::TrustedReadOnly) |
| 1292 | } |
| 1293 | |
| 1294 | const MCP_TOOL_DESCRIPTION_MAX_CHARS: usize = 80; |
| 1295 | |
| 1296 | /// Format an optional MCP tool description for terminal list surfaces. |
| 1297 | /// |
| 1298 | /// CLI and TUI callers share this helper so both stay single-line and truncate |
| 1299 | /// on Unicode scalar boundaries rather than slicing UTF-8 bytes. |
| 1300 | pub fn format_mcp_tool_description(description: Option<&str>) -> String { |
| 1301 | let Some(first_line) = description |
| 1302 | .and_then(|description| description.split(['\r', '\n']).next()) |
| 1303 | .map(str::trim) |
| 1304 | .filter(|description| !description.is_empty()) |
| 1305 | else { |
| 1306 | return String::new(); |
| 1307 | }; |
| 1308 | |
| 1309 | let mut chars = first_line.chars(); |
| 1310 | let summary: String = chars |
| 1311 | .by_ref() |
| 1312 | .take(MCP_TOOL_DESCRIPTION_MAX_CHARS) |
| 1313 | .collect(); |
| 1314 | if chars.next().is_some() { |
| 1315 | format!(": {summary}...") |
| 1316 | } else { |
| 1317 | format!(": {summary}") |
| 1318 | } |
| 1319 | } |
| 1320 | |
| 1321 | /// Resource discovered from an MCP server |
| 1322 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 1323 | pub struct McpResource { |
| 1324 | pub uri: String, |
| 1325 | pub name: String, |
| 1326 | #[serde(default)] |
| 1327 | pub description: Option<String>, |
| 1328 | #[serde(rename = "mimeType", default)] |
| 1329 | pub mime_type: Option<String>, |
| 1330 | } |
| 1331 | |
| 1332 | /// One `skills/list` entry of the published Skills extension (SEP-2640). |
| 1333 | /// Discovery only records it; nothing here loads or activates the skill. |
| 1334 | #[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] |
| 1335 | pub struct McpSkill { |
| 1336 | pub uri: String, |
| 1337 | pub frontmatter: serde_json::Map<String, serde_json::Value>, |
| 1338 | pub resources: Vec<McpSkillFile>, |
| 1339 | } |
| 1340 | |
| 1341 | #[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)] |
| 1342 | pub struct McpSkillFile { |
| 1343 | pub uri: String, |
| 1344 | pub digest: String, |
| 1345 | pub size: u64, |
| 1346 | } |
| 1347 | |
| 1348 | const MCP_SKILLS_EXTENSION: &str = "io.modelcontextprotocol/skills"; |
| 1349 | const MAX_MCP_SKILL_FILES: usize = 512; |
| 1350 | const MAX_MCP_SKILL_BYTES: u64 = 16 * 1024 * 1024; |
| 1351 | |
| 1352 | impl McpSkill { |
| 1353 | fn frontmatter_text(&self, key: &str) -> Option<&str> { |
| 1354 | self.frontmatter |
| 1355 | .get(key) |
| 1356 | .and_then(serde_json::Value::as_str) |
| 1357 | .filter(|value| !value.trim().is_empty()) |
| 1358 | } |
| 1359 | |
| 1360 | pub fn name(&self) -> &str { |
| 1361 | self.frontmatter_text("name").unwrap_or_default() |
| 1362 | } |
| 1363 | |
| 1364 | pub fn description(&self) -> &str { |
| 1365 | self.frontmatter_text("description").unwrap_or_default() |
| 1366 | } |
| 1367 | |
| 1368 | /// Entry checks a host owes before offering the skill: a `SKILL.md` root |
| 1369 | /// it lists itself, files confined beneath that root with sha256 digests, |
| 1370 | /// and the extension's file and byte limits. |
| 1371 | fn admissible(&self) -> bool { |
| 1372 | let Some(root) = self.uri.strip_suffix("SKILL.md") else { |
| 1373 | return false; |
| 1374 | }; |
| 1375 | let mut seen = HashSet::new(); |
| 1376 | let mut bytes = 0u64; |
| 1377 | !root.is_empty() |
| 1378 | && self.frontmatter_text("name").is_some() |
| 1379 | && self.frontmatter_text("description").is_some() |
| 1380 | && self.resources.len() <= MAX_MCP_SKILL_FILES |
| 1381 | && self.resources.iter().any(|file| file.uri == self.uri) |
| 1382 | && self.resources.iter().all(|file| { |
| 1383 | bytes = bytes.saturating_add(file.size); |
| 1384 | file.uri.strip_prefix(root).is_some_and(|rel| { |
| 1385 | !rel.is_empty() |
| 1386 | && !rel.contains(['\\', '?', '#', '%']) |
| 1387 | && rel.split('/').all(|part| !matches!(part, "" | "." | "..")) |
| 1388 | }) && file.digest.strip_prefix("sha256:").is_some_and(|hex| { |
| 1389 | hex.len() == 64 && hex.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) |
| 1390 | }) && seen.insert(file.uri.as_str()) |
| 1391 | }) |
| 1392 | && bytes <= MAX_MCP_SKILL_BYTES |
| 1393 | } |
| 1394 | } |
| 1395 | |
| 1396 | /// Check one `resources/read` result against its skill entry: exactly the |
| 1397 | /// requested URI, and bytes whose size and sha256 equal the listing's. |
| 1398 | fn verify_mcp_skill_file(file: &McpSkillFile, result: &serde_json::Value) -> Result<()> { |
| 1399 | use base64::Engine as _; |
| 1400 | let contents = result |
| 1401 | .get("contents") |
| 1402 | .and_then(serde_json::Value::as_array) |
| 1403 | .filter(|contents| contents.len() == 1) |
| 1404 | .context("MCP skill file read must return exactly one content entry")?; |
| 1405 | let entry = &contents[0]; |
| 1406 | anyhow::ensure!( |
| 1407 | entry.get("uri").and_then(serde_json::Value::as_str) == Some(file.uri.as_str()), |
| 1408 | "MCP skill file read returned a different URI than '{}'", |
| 1409 | file.uri |
| 1410 | ); |
| 1411 | let bytes = if let Some(text) = entry.get("text").and_then(serde_json::Value::as_str) { |
| 1412 | text.as_bytes().to_vec() |
| 1413 | } else { |
| 1414 | let blob = entry |
| 1415 | .get("blob") |
| 1416 | .and_then(serde_json::Value::as_str) |
| 1417 | .context("MCP skill file read carried neither text nor blob")?; |
| 1418 | base64::engine::general_purpose::STANDARD |
| 1419 | .decode(blob) |
| 1420 | .context("MCP skill file blob is not base64")? |
| 1421 | }; |
| 1422 | let digest = |
| 1423 | sha2::Sha256::digest(&bytes) |
| 1424 | .iter() |
| 1425 | .fold(String::from("sha256:"), |mut out, byte| { |
| 1426 | use std::fmt::Write as _; |
| 1427 | let _ = write!(out, "{byte:02x}"); |
| 1428 | out |
| 1429 | }); |
| 1430 | anyhow::ensure!( |
| 1431 | bytes.len() as u64 == file.size && digest == file.digest, |
| 1432 | "MCP skill file '{}' does not match its listed size and digest; it was not loaded", |
| 1433 | file.uri |
| 1434 | ); |
| 1435 | Ok(()) |
| 1436 | } |
| 1437 | |
| 1438 | /// Resource template discovered from an MCP server |
| 1439 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 1440 | pub struct McpResourceTemplate { |
| 1441 | #[serde(rename = "uriTemplate")] |
| 1442 | pub uri_template: String, |
| 1443 | pub name: String, |
| 1444 | #[serde(default)] |
| 1445 | pub description: Option<String>, |
| 1446 | #[serde(rename = "mimeType", default)] |
| 1447 | pub mime_type: Option<String>, |
| 1448 | } |
| 1449 | |
| 1450 | /// Fail-closed RFC 6570 subset used only as an authorization check. Literal, |
| 1451 | /// simple (`{id}`), and reserved (`{+path}`) expansions cover the common MCP |
| 1452 | /// resource templates. More elaborate operators remain listable but are not |
| 1453 | /// callable until their expansion semantics are implemented exactly. |
| 1454 | /// |
| 1455 | /// `None` is the fail-closed answer: a template this subset cannot express |
| 1456 | /// matches nothing. |
| 1457 | fn resource_template_pattern(template: &str) -> Option<String> { |
| 1458 | let mut pattern = String::from("^"); |
| 1459 | let mut rest = template; |
| 1460 | while let Some(start) = rest.find('{') { |
| 1461 | pattern.push_str(®ex::escape(&rest[..start])); |
| 1462 | let end = rest[start + 1..].find('}')?; |
| 1463 | let expression = &rest[start + 1..start + 1 + end]; |
| 1464 | let (reserved, variables) = match expression.strip_prefix('+') { |
| 1465 | Some(variables) => (true, variables), |
| 1466 | None => (false, expression), |
| 1467 | }; |
| 1468 | if variables.is_empty() |
| 1469 | || variables.split(',').any(|variable| { |
| 1470 | variable.is_empty() |
| 1471 | || !variable |
| 1472 | .chars() |
| 1473 | .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.')) |
| 1474 | }) |
| 1475 | { |
| 1476 | return None; |
| 1477 | } |
| 1478 | let atom = if reserved { ".+" } else { "[^/?#]+" }; |
| 1479 | for (index, _) in variables.split(',').enumerate() { |
| 1480 | if index > 0 { |
| 1481 | pattern.push(','); |
| 1482 | } |
| 1483 | pattern.push_str(atom); |
| 1484 | } |
| 1485 | rest = &rest[start + end + 2..]; |
| 1486 | } |
| 1487 | if rest.contains('}') { |
| 1488 | return None; |
| 1489 | } |
| 1490 | pattern.push_str(®ex::escape(rest)); |
| 1491 | pattern.push('$'); |
| 1492 | Some(pattern) |
| 1493 | } |
| 1494 | |
| 1495 | /// `template`'s anchored pattern, compiled once and reused. |
| 1496 | /// |
| 1497 | /// This runs per URI per advertised template, while the template itself is |
| 1498 | /// fixed by the server's listing, so compiling it on every call was pure |
| 1499 | /// repetition. `None` still means "matches nothing" (#6213 T7). The cache is |
| 1500 | /// bounded because the template list is server-supplied: an unbounded key set |
| 1501 | /// would let one server pin memory for the life of the process. |
| 1502 | fn compiled_resource_template(template: &str) -> Option<Arc<regex::Regex>> { |
| 1503 | const MAX_CACHED_TEMPLATES: usize = 512; |
| 1504 | static CACHE: std::sync::OnceLock< |
| 1505 | std::sync::Mutex<HashMap<String, Option<Arc<regex::Regex>>>>, |
| 1506 | > = std::sync::OnceLock::new(); |
| 1507 | let cache = CACHE.get_or_init(|| std::sync::Mutex::new(HashMap::new())); |
| 1508 | let mut cache = cache |
| 1509 | .lock() |
| 1510 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 1511 | if let Some(cached) = cache.get(template) { |
| 1512 | return cached.clone(); |
| 1513 | } |
| 1514 | let compiled = resource_template_pattern(template) |
| 1515 | .and_then(|pattern| regex::Regex::new(&pattern).ok()) |
| 1516 | .map(Arc::new); |
| 1517 | if cache.len() < MAX_CACHED_TEMPLATES { |
| 1518 | cache.insert(template.to_string(), compiled.clone()); |
| 1519 | } |
| 1520 | compiled |
| 1521 | } |
| 1522 | |
| 1523 | fn resource_uri_matches_template(uri: &str, template: &str) -> bool { |
| 1524 | compiled_resource_template(template).is_some_and(|regex| regex.is_match(uri)) |
| 1525 | } |
| 1526 | |
| 1527 | /// Prompt discovered from an MCP server |
| 1528 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 1529 | pub struct McpPrompt { |
| 1530 | pub name: String, |
| 1531 | #[serde(default)] |
| 1532 | pub description: Option<String>, |
| 1533 | #[serde(default)] |
| 1534 | pub arguments: Vec<McpPromptArgument>, |
| 1535 | } |
| 1536 | |
| 1537 | /// Argument for an MCP prompt |
| 1538 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 1539 | pub struct McpPromptArgument { |
| 1540 | pub name: String, |
| 1541 | #[serde(default)] |
| 1542 | pub description: Option<String>, |
| 1543 | #[serde(default)] |
| 1544 | pub required: bool, |
| 1545 | } |
| 1546 | |
| 1547 | // === Connection State === |
| 1548 | |
| 1549 | /// State of an MCP connection |
| 1550 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 1551 | pub enum ConnectionState { |
| 1552 | Connecting, |
| 1553 | Ready, |
| 1554 | Disconnected, |
| 1555 | } |
| 1556 | |
| 1557 | /// MCP server capabilities advertised in the initialize response. |
| 1558 | /// |
| 1559 | /// Each flag records presence of the corresponding MCP capability object. The |
| 1560 | /// surrounding [`McpServerCapabilityMetadata`] preserves the important |
| 1561 | /// distinction between an advertised empty set and a legacy server that did |
| 1562 | /// not send capability metadata at all. |
| 1563 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 1564 | pub struct McpServerCapabilities { |
| 1565 | pub tools: bool, |
| 1566 | pub resources: bool, |
| 1567 | pub prompts: bool, |
| 1568 | } |
| 1569 | |
| 1570 | impl McpServerCapabilities { |
| 1571 | fn from_initialize_response(response: &serde_json::Value) -> Option<Self> { |
| 1572 | let capabilities = response.get("result")?.get("capabilities")?.as_object()?; |
| 1573 | Some(Self { |
| 1574 | tools: capabilities.contains_key("tools"), |
| 1575 | resources: capabilities.contains_key("resources"), |
| 1576 | prompts: capabilities.contains_key("prompts"), |
| 1577 | }) |
| 1578 | } |
| 1579 | } |
| 1580 | |
| 1581 | /// Provenance-aware capability metadata for a manager snapshot. |
| 1582 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 1583 | pub enum McpServerCapabilityMetadata { |
| 1584 | /// The server supplied a spec-shaped `capabilities` object at initialize. |
| 1585 | Advertised(McpServerCapabilities), |
| 1586 | /// A connected legacy server omitted metadata, so bounded discovery probes |
| 1587 | /// remain enabled for backward compatibility. |
| 1588 | LegacyFallback, |
| 1589 | /// The server has not completed initialization, so no truthful capability |
| 1590 | /// claim can be made yet. |
| 1591 | #[default] |
| 1592 | NotObserved, |
| 1593 | } |
| 1594 | |
| 1595 | fn response_result<'a>( |
| 1596 | response: &'a serde_json::Value, |
| 1597 | method: &str, |
| 1598 | suppress_server_details: bool, |
| 1599 | ) -> Result<Option<&'a serde_json::Value>> { |
| 1600 | if let Some(error) = response.get("error") { |
| 1601 | if suppress_server_details { |
| 1602 | anyhow::bail!( |
| 1603 | "Reviewed plugin MCP server returned an error in '{method}' (server details suppressed to protect environment-backed credentials)" |
| 1604 | ); |
| 1605 | } |
| 1606 | anyhow::bail!("MCP error in '{method}': {error}"); |
| 1607 | } |
| 1608 | if let Some(result_type) = response |
| 1609 | .get("result") |
| 1610 | .and_then(|result| result.get("resultType")) |
| 1611 | && result_type != "complete" |
| 1612 | { |
| 1613 | anyhow::bail!( |
| 1614 | "MCP '{method}' requires an unsupported result flow; the request was not replayed" |
| 1615 | ); |
| 1616 | } |
| 1617 | Ok(response.get("result")) |
| 1618 | } |
| 1619 | |
| 1620 | async fn run_optional_discovery<F, T>( |
| 1621 | server: &str, |
| 1622 | method: &str, |
| 1623 | timeout: Duration, |
| 1624 | discovery: F, |
| 1625 | ) -> Option<T> |
| 1626 | where |
| 1627 | F: Future<Output = Result<T>>, |
| 1628 | { |
| 1629 | match tokio::time::timeout(timeout, discovery).await { |
| 1630 | Ok(Ok(value)) => return Some(value), |
| 1631 | Ok(Err(error)) => { |
| 1632 | tracing::warn!( |
| 1633 | target: "mcp", |
| 1634 | server, |
| 1635 | method, |
| 1636 | error = %error, |
| 1637 | "optional MCP discovery failed; continuing with available capabilities" |
| 1638 | ); |
| 1639 | } |
| 1640 | Err(error) => { |
| 1641 | tracing::warn!( |
| 1642 | target: "mcp", |
| 1643 | server, |
| 1644 | method, |
| 1645 | ?timeout, |
| 1646 | error = %error, |
| 1647 | "optional MCP discovery timed out; continuing with available capabilities" |
| 1648 | ); |
| 1649 | } |
| 1650 | } |
| 1651 | None |
| 1652 | } |
| 1653 | |
| 1654 | // === McpConnection - Async Connection Management === |
| 1655 | |
| 1656 | // === Transport Trait === |
| 1657 | |
| 1658 | #[async_trait::async_trait] |
| 1659 | pub trait McpTransport: Send + Sync { |
| 1660 | async fn send(&mut self, msg: Vec<u8>) -> Result<()>; |
| 1661 | /// The SDK stdio adapter keeps the actual person-decision inside Rust. |
| 1662 | /// Existing transports retain their current byte send and attestation path. |
| 1663 | async fn send_decided( |
| 1664 | &mut self, |
| 1665 | msg: Vec<u8>, |
| 1666 | _decision: Option<&crate::core::engine::HumanDecision>, |
| 1667 | _timeout: Duration, |
| 1668 | ) -> Result<()> { |
| 1669 | self.send(msg).await |
| 1670 | } |
| 1671 | |
| 1672 | async fn recv(&mut self) -> Result<Vec<u8>>; |
| 1673 | |
| 1674 | async fn send_reply(&mut self, msg: Vec<u8>) -> Result<()> { |
| 1675 | self.send(msg).await |
| 1676 | } |
| 1677 | |
| 1678 | /// Record the protocol revision negotiated at `initialize`. Only the |
| 1679 | /// Streamable HTTP transport uses it (the `MCP-Protocol-Version` header on |
| 1680 | /// subsequent requests); stdio and legacy SSE have no header channel, so |
| 1681 | /// the default is a no-op. |
| 1682 | fn set_protocol_version(&mut self, _version: &str) {} |
| 1683 | fn is_modern(&self) -> bool { |
| 1684 | false |
| 1685 | } |
| 1686 | |
| 1687 | /// The last non-empty line the server wrote to stderr, for naming why a |
| 1688 | /// handshake was refused. Only stdio children have a stderr; a reviewed |
| 1689 | /// plugin's is never retained. |
| 1690 | async fn last_stderr_line(&self) -> Option<String> { |
| 1691 | None |
| 1692 | } |
| 1693 | |
| 1694 | /// Synchronous, best-effort liveness probe consulted by |
| 1695 | /// [`McpConnection::is_ready`] so a crashed stdio child stops reading |
| 1696 | /// as "ready" before the next call fails (#6187). Must never block and |
| 1697 | /// never spawn — a contended lock reads as alive; the next call observes |
| 1698 | /// the death. The default is "alive"; Streamable HTTP has no long-lived |
| 1699 | /// channel to observe and reports only a cancelled connection, while |
| 1700 | /// legacy SSE reports its closed event stream. |
| 1701 | fn probe_dead(&self) -> bool { |
| 1702 | false |
| 1703 | } |
| 1704 | |
| 1705 | /// Whether the server announced a `notifications/*/list_changed` since |
| 1706 | /// the last call. Transports that read frames only inside an exchange |
| 1707 | /// leave this to [`McpConnection::recv_reply`]. |
| 1708 | fn take_list_changed(&self) -> bool { |
| 1709 | false |
| 1710 | } |
| 1711 | |
| 1712 | /// Graceful shutdown — stdio transports send SIGTERM to the child and |
| 1713 | /// give it a brief window to exit before tokio's `kill_on_drop` fires |
| 1714 | /// SIGKILL as the backstop. Default is a no-op for non-stdio transports |
| 1715 | /// that have no child process. Whalescale#420. |
| 1716 | async fn shutdown(&mut self) {} |
| 1717 | } |
| 1718 | |
| 1719 | const MAX_MCP_CATALOG_PAGES: usize = 64; |
| 1720 | const MAX_MCP_CATALOG_ITEMS: usize = 4_096; |
| 1721 | const MAX_MCP_CATALOG_BYTES: usize = 32 * 1024 * 1024; |
| 1722 | const MIN_MCP_CATALOG_TTL_MS: u64 = 60_000; |
| 1723 | const MAX_MCP_CATALOG_TTL_MS: u64 = 86_400_000; |
| 1724 | |
| 1725 | pub fn is_mcp_list_changed_method(method: &str) -> bool { |
| 1726 | matches!( |
| 1727 | method, |
| 1728 | "notifications/tools/list_changed" |
| 1729 | | "notifications/resources/list_changed" |
| 1730 | | "notifications/prompts/list_changed" |
| 1731 | ) |
| 1732 | } |
| 1733 | |
| 1734 | /// One retained catalog generation, shared by every advertised family. |
| 1735 | struct McpCatalogBudget { |
| 1736 | pages: usize, |
| 1737 | items: usize, |
| 1738 | bytes: usize, |
| 1739 | // Cursor namespaces are independent across list methods. |
| 1740 | seen_cursors: HashSet<(&'static str, String)>, |
| 1741 | // Optional-method recovery cannot turn a budget refusal into success. |
| 1742 | refused: Option<String>, |
| 1743 | ttl_ms: Option<u64>, |
| 1744 | } |
| 1745 | |
| 1746 | impl McpCatalogBudget { |
| 1747 | fn new() -> Self { |
| 1748 | Self { |
| 1749 | pages: 0, |
| 1750 | items: 0, |
| 1751 | bytes: 0, |
| 1752 | seen_cursors: HashSet::new(), |
| 1753 | refused: None, |
| 1754 | ttl_ms: None, |
| 1755 | } |
| 1756 | } |
| 1757 | |
| 1758 | fn ensure_available(&self) -> Result<()> { |
| 1759 | if let Some(reason) = self.refused.as_ref() { |
| 1760 | anyhow::bail!("{reason}"); |
| 1761 | } |
| 1762 | Ok(()) |
| 1763 | } |
| 1764 | |
| 1765 | fn observe_page( |
| 1766 | &mut self, |
| 1767 | method: &'static str, |
| 1768 | result: &serde_json::Value, |
| 1769 | item_count: usize, |
| 1770 | ) -> Result<Option<String>> { |
| 1771 | self.ensure_available()?; |
| 1772 | self.pages = self.pages.saturating_add(1); |
| 1773 | self.items = self.items.saturating_add(item_count); |
| 1774 | self.bytes = self.bytes.saturating_add(serde_json::to_vec(result)?.len()); |
| 1775 | let refusal = if self.pages > MAX_MCP_CATALOG_PAGES { |
| 1776 | Some(format!( |
| 1777 | "{method} exceeded the {MAX_MCP_CATALOG_PAGES}-page catalogue limit" |
| 1778 | )) |
| 1779 | } else if self.items > MAX_MCP_CATALOG_ITEMS { |
| 1780 | Some(format!( |
| 1781 | "{method} exceeded the {MAX_MCP_CATALOG_ITEMS}-item catalogue limit" |
| 1782 | )) |
| 1783 | } else if self.bytes > MAX_MCP_CATALOG_BYTES { |
| 1784 | Some(format!( |
| 1785 | "{method} exceeded the {MAX_MCP_CATALOG_BYTES}-byte aggregate catalogue limit" |
| 1786 | )) |
| 1787 | } else { |
| 1788 | None |
| 1789 | }; |
| 1790 | if let Some(reason) = refusal { |
| 1791 | self.refused = Some(reason); |
| 1792 | self.ensure_available()?; |
| 1793 | } |
| 1794 | if let Some(ttl) = result.get("ttlMs").and_then(serde_json::Value::as_u64) { |
| 1795 | self.ttl_ms = Some(self.ttl_ms.map_or(ttl, |known| known.min(ttl))); |
| 1796 | } |
| 1797 | let cursor = result |
| 1798 | .get("nextCursor") |
| 1799 | .and_then(|value| value.as_str()) |
| 1800 | .map(str::to_owned); |
| 1801 | if let Some(cursor) = cursor.as_ref() |
| 1802 | && !self.seen_cursors.insert((method, cursor.clone())) |
| 1803 | { |
| 1804 | self.refused = Some(format!("{method} repeated pagination cursor; aborting")); |
| 1805 | self.ensure_available()?; |
| 1806 | } |
| 1807 | Ok(cursor) |
| 1808 | } |
| 1809 | } |
| 1810 | |
| 1811 | pub fn is_legacy_sse_transport(config: &McpServerConfig) -> bool { |
| 1812 | config |
| 1813 | .transport |
| 1814 | .as_deref() |
| 1815 | .map(|transport| transport.trim().eq_ignore_ascii_case("sse")) |
| 1816 | .unwrap_or(false) |
| 1817 | } |
| 1818 | |
| 1819 | pub fn validate_mcp_transport(transport: Option<&str>) -> Result<()> { |
| 1820 | let Some(transport) = transport else { |
| 1821 | return Ok(()); |
| 1822 | }; |
| 1823 | if transport.trim().eq_ignore_ascii_case("sse") { |
| 1824 | return Ok(()); |
| 1825 | } |
| 1826 | anyhow::bail!("Unsupported MCP transport '{transport}'. Supported values: sse"); |
| 1827 | } |
| 1828 | |
| 1829 | fn response_id_matches(id: Option<&serde_json::Value>, expected_id: &str) -> bool { |
| 1830 | let Some(id) = id else { |
| 1831 | return false; |
| 1832 | }; |
| 1833 | if id.as_str() == Some(expected_id) { |
| 1834 | return true; |
| 1835 | } |
| 1836 | id.as_u64() |
| 1837 | .map(|id| id.to_string() == expected_id) |
| 1838 | .unwrap_or(false) |
| 1839 | } |
| 1840 | |
| 1841 | // === McpConnection - Async Connection Management === |
| 1842 | |
| 1843 | /// Manages a single async connection to an MCP server |
| 1844 | pub struct McpConnection { |
| 1845 | auth_context: Arc<dyn AuthContext>, |
| 1846 | name: String, |
| 1847 | transport: Box<dyn McpTransport>, |
| 1848 | tools: Vec<McpTool>, |
| 1849 | resources: Vec<McpResource>, |
| 1850 | resource_templates: Vec<McpResourceTemplate>, |
| 1851 | prompts: Vec<McpPrompt>, |
| 1852 | skills: Vec<McpSkill>, |
| 1853 | skills_extension: bool, |
| 1854 | request_id: AtomicU64, |
| 1855 | state: ConnectionState, |
| 1856 | config: McpServerConfig, |
| 1857 | runtime_registration: Option<SharedRuntimeMcpServers>, |
| 1858 | server_capabilities: Option<McpServerCapabilities>, |
| 1859 | /// Sanitized `instructions` from this connection's `initialize` result. |
| 1860 | /// A reconnect builds a new connection, so guidance never outlives the |
| 1861 | /// handshake that supplied it. |
| 1862 | instructions: Option<String>, |
| 1863 | discovery_timeout: Duration, |
| 1864 | read_timeout_secs: u64, |
| 1865 | cancel_token: tokio_util::sync::CancellationToken, |
| 1866 | authority_revocation_reason: Arc<std::sync::Mutex<Option<String>>>, |
| 1867 | authority_watch: Option<tokio::task::JoinHandle<()>>, |
| 1868 | /// Pool catalog generation that created/last authorized this connection. |
| 1869 | /// Directly constructed test connections use zero until inserted. |
| 1870 | catalog_generation: u64, |
| 1871 | /// Bumped whenever an in-place revalidation changes this catalog, so a |
| 1872 | /// route resolved against the previous catalog cannot execute. |
| 1873 | catalog_revision: u64, |
| 1874 | /// Earliest advertised `ttlMs` across the last discovery's pages. `None` |
| 1875 | /// keeps the catalog until a list-change notice or reconnect. |
| 1876 | catalog_fresh_until: Option<std::time::Instant>, |
| 1877 | catalog_stale: bool, |
| 1878 | /// Key this host shares with the built-in Computer Use plugin over the |
| 1879 | /// connection itself, to attest a person's card decision on a call. |
| 1880 | decision_key: Option<[u8; 32]>, |
| 1881 | call_lane: Option<Arc<McpCallLane>>, |
| 1882 | } |
| 1883 | |
| 1884 | struct PendingAuthorityWatch { |
| 1885 | handle: Option<tokio::task::JoinHandle<()>>, |
| 1886 | cancel: tokio_util::sync::CancellationToken, |
| 1887 | armed: bool, |
| 1888 | } |
| 1889 | |
| 1890 | impl PendingAuthorityWatch { |
| 1891 | fn start( |
| 1892 | source: ReviewedPluginMcpSource, |
| 1893 | cancel: tokio_util::sync::CancellationToken, |
| 1894 | reason_slot: Arc<std::sync::Mutex<Option<String>>>, |
| 1895 | ) -> Self { |
| 1896 | let task_cancel = cancel.clone(); |
| 1897 | // The watch stays per-connection by design (#6211 R7a): it is born |
| 1898 | // with the connect attempt (covering the pre-insertion window) and |
| 1899 | // dies with the connection, so a watched server can neither be |
| 1900 | // missed nor leak. A pool-level task would need the pool lock — |
| 1901 | // held across in-flight calls — and regress the mid-call trip this |
| 1902 | // exists for. What moves is the check itself: synchronous |
| 1903 | // state fs has no place on the executor at 20Hz, so it runs on the |
| 1904 | // blocking pool while the 50ms revocation cadence is unchanged. |
| 1905 | let source = Arc::new(source); |
| 1906 | let handle = tokio::spawn(async move { |
| 1907 | loop { |
| 1908 | let source = Arc::clone(&source); |
| 1909 | let check = tokio::task::spawn_blocking(move || { |
| 1910 | codewhale_plugins::registry::verify_plugin_state_authority(&source.authority) |
| 1911 | }) |
| 1912 | .await; |
| 1913 | let reason = match check { |
| 1914 | Ok(Err(reason)) => Some(reason), |
| 1915 | Ok(Ok(())) => None, |
| 1916 | Err(_) => { |
| 1917 | Some("plugin authority check failed to run; failing closed".to_string()) |
| 1918 | } |
| 1919 | }; |
| 1920 | if let Some(reason) = reason { |
| 1921 | if let Ok(mut slot) = reason_slot.lock() { |
| 1922 | *slot = Some(reason); |
| 1923 | } |
| 1924 | task_cancel.cancel(); |
| 1925 | break; |
| 1926 | } |
| 1927 | tokio::select! { |
| 1928 | _ = task_cancel.cancelled() => break, |
| 1929 | _ = tokio::time::sleep(Duration::from_millis(50)) => {} |
| 1930 | } |
| 1931 | } |
| 1932 | }); |
| 1933 | Self { |
| 1934 | handle: Some(handle), |
| 1935 | cancel, |
| 1936 | armed: true, |
| 1937 | } |
| 1938 | } |
| 1939 | |
| 1940 | fn disarm(mut self) -> tokio::task::JoinHandle<()> { |
| 1941 | self.armed = false; |
| 1942 | self.handle.take().expect("authority watch must exist") |
| 1943 | } |
| 1944 | } |
| 1945 | |
| 1946 | impl Drop for PendingAuthorityWatch { |
| 1947 | fn drop(&mut self) { |
| 1948 | if self.armed { |
| 1949 | self.cancel.cancel(); |
| 1950 | if let Some(handle) = self.handle.take() { |
| 1951 | handle.abort(); |
| 1952 | } |
| 1953 | } |
| 1954 | } |
| 1955 | } |
| 1956 | |
| 1957 | /// Total request ceiling handed to the HTTP client: it must cover the longest |
| 1958 | /// request the connection carries (`tools/call` at the execute budget), so a |
| 1959 | /// raised `execute_timeout` governs HTTP servers too. This is a ceiling for |
| 1960 | /// the transport, not the read knob. |
| 1961 | /// |
| 1962 | /// Streamable HTTP reads the reply inside the POST; `call_method` bounds the |
| 1963 | /// send and the receive with the request's own budget, so this ceiling is |
| 1964 | /// only the transport's outer safety net for requests without one. |
| 1965 | fn http_request_ceiling_secs(config: &McpServerConfig, global: &McpTimeouts) -> u64 { |
| 1966 | config |
| 1967 | .effective_read_timeout(global) |
| 1968 | .max(config.effective_execute_timeout(global)) |
| 1969 | } |
| 1970 | |
| 1971 | async fn prepare_mcp_http_client( |
| 1972 | name: &str, |
| 1973 | config: &McpServerConfig, |
| 1974 | global_timeouts: &McpTimeouts, |
| 1975 | network_policy: Option<&NetworkPolicyDecider>, |
| 1976 | cancel_token: &tokio_util::sync::CancellationToken, |
| 1977 | connect_timeout_secs: u64, |
| 1978 | auth_context: Arc<dyn AuthContext>, |
| 1979 | ) -> Result<http_client::McpHttpClient> { |
| 1980 | let url = config.url.as_deref().context("MCP HTTP URL absent")?; |
| 1981 | // Per-domain network policy gate (#135). Only the HTTP/SSE transport |
| 1982 | // is gated; STDIO MCP servers run as local subprocesses and never |
| 1983 | // touch the network from this code path. |
| 1984 | if let Some(decider) = network_policy |
| 1985 | && let Some(host) = host_from_url(url) |
| 1986 | { |
| 1987 | match decider.evaluate(&host, "mcp") { |
| 1988 | Decision::Allow => {} |
| 1989 | Decision::Deny => { |
| 1990 | anyhow::bail!( |
| 1991 | "MCP server '{name}' connection to '{host}' blocked by network policy" |
| 1992 | ); |
| 1993 | } |
| 1994 | Decision::Prompt => { |
| 1995 | anyhow::bail!( |
| 1996 | "MCP server '{name}' connection to '{host}' requires approval; \ |
| 1997 | re-run after `/network allow {host}` or set network.default = \"allow\" in config" |
| 1998 | ); |
| 1999 | } |
| 2000 | } |
| 2001 | } |
| 2002 | let client = http_client::McpHttpClient::new( |
| 2003 | url, |
| 2004 | config.runtime_added, |
| 2005 | config.reviewed_plugin.is_some(), |
| 2006 | config.allow_private_network, |
| 2007 | network_policy, |
| 2008 | Duration::from_secs(connect_timeout_secs), |
| 2009 | // Transport total-request ceiling, not the read knob: it must |
| 2010 | // cover the longest request this connection carries |
| 2011 | // (`tools/call` at the execute budget), so a raised |
| 2012 | // `execute_timeout` governs HTTP servers too. The read knob |
| 2013 | // itself stays intact for the connection-level waits below. |
| 2014 | Duration::from_secs(http_request_ceiling_secs(config, global_timeouts)), |
| 2015 | )?; |
| 2016 | let oauth_runtime = if config.reviewed_plugin.is_some() { |
| 2017 | None |
| 2018 | } else { |
| 2019 | let default_headers = |
| 2020 | oauth::build_default_headers_with_auth_context(config, auth_context.as_ref()).map_err( |
| 2021 | |error| { |
| 2022 | error.context(McpCredentialConfigurationError( |
| 2023 | "Configured MCP request headers could not be built".to_string(), |
| 2024 | )) |
| 2025 | }, |
| 2026 | )?; |
| 2027 | let prepared = tokio::select! { |
| 2028 | biased; |
| 2029 | _ = cancel_token.cancelled() => { |
| 2030 | anyhow::bail!("MCP OAuth setup cancelled after plugin authority changed") |
| 2031 | } |
| 2032 | prepared = oauth::McpOAuthRuntime::from_server_config_with_client( |
| 2033 | name, config, default_headers, client.clone(), |
| 2034 | ) => prepared, |
| 2035 | }; |
| 2036 | prepared.with_context(|| { |
| 2037 | format!("preparing stored OAuth credentials for MCP server '{name}'") |
| 2038 | })? |
| 2039 | }; |
| 2040 | let client = client.with_mcp_auth(McpHttpAuth::from_config_with_auth_context( |
| 2041 | name, |
| 2042 | config, |
| 2043 | oauth_runtime, |
| 2044 | auth_context, |
| 2045 | )); |
| 2046 | Ok(client) |
| 2047 | } |
| 2048 | |
| 2049 | impl McpConnection { |
| 2050 | /// Connect to an MCP server and initialize it. |
| 2051 | /// |
| 2052 | /// `network_policy` (added in v0.7.0 for #135) is consulted for HTTP/SSE |
| 2053 | /// transports only — STDIO transports are unaffected. Pass `None` to |
| 2054 | /// match pre-v0.7.0 permissive behavior. |
| 2055 | #[cfg(any(test, feature = "test-support"))] |
| 2056 | pub async fn connect_with_policy( |
| 2057 | name: String, |
| 2058 | config: McpServerConfig, |
| 2059 | global_timeouts: &McpTimeouts, |
| 2060 | network_policy: Option<&NetworkPolicyDecider>, |
| 2061 | ) -> Result<Self> { |
| 2062 | Self::connect_with_backend( |
| 2063 | name, |
| 2064 | config, |
| 2065 | global_timeouts, |
| 2066 | network_policy, |
| 2067 | McpBackend::Rust, |
| 2068 | ) |
| 2069 | .await |
| 2070 | } |
| 2071 | pub async fn connect_with_backend( |
| 2072 | name: String, |
| 2073 | config: McpServerConfig, |
| 2074 | global_timeouts: &McpTimeouts, |
| 2075 | network_policy: Option<&NetworkPolicyDecider>, |
| 2076 | backend: McpBackend, |
| 2077 | ) -> Result<Self> { |
| 2078 | Self::connect_with_backend_and_auth_context( |
| 2079 | name, |
| 2080 | config, |
| 2081 | global_timeouts, |
| 2082 | network_policy, |
| 2083 | backend, |
| 2084 | process_mcp_auth_context(), |
| 2085 | ) |
| 2086 | .await |
| 2087 | } |
| 2088 | |
| 2089 | pub async fn connect_with_backend_and_auth_context( |
| 2090 | name: String, |
| 2091 | config: McpServerConfig, |
| 2092 | global_timeouts: &McpTimeouts, |
| 2093 | network_policy: Option<&NetworkPolicyDecider>, |
| 2094 | backend: McpBackend, |
| 2095 | auth_context: Arc<dyn AuthContext>, |
| 2096 | ) -> Result<Self> { |
| 2097 | Self::connect_with_backend_auth_and_cancel( |
| 2098 | name, |
| 2099 | config, |
| 2100 | global_timeouts, |
| 2101 | network_policy, |
| 2102 | backend, |
| 2103 | auth_context, |
| 2104 | tokio_util::sync::CancellationToken::new(), |
| 2105 | ) |
| 2106 | .await |
| 2107 | } |
| 2108 | |
| 2109 | pub async fn connect_with_backend_auth_and_cancel( |
| 2110 | name: String, |
| 2111 | config: McpServerConfig, |
| 2112 | global_timeouts: &McpTimeouts, |
| 2113 | network_policy: Option<&NetworkPolicyDecider>, |
| 2114 | backend: McpBackend, |
| 2115 | auth_context: Arc<dyn AuthContext>, |
| 2116 | cancel: tokio_util::sync::CancellationToken, |
| 2117 | ) -> Result<Self> { |
| 2118 | let connect_timeout_secs = config.effective_connect_timeout(global_timeouts); |
| 2119 | let read_timeout_secs = config.effective_read_timeout(global_timeouts); |
| 2120 | let cancel_token = cancel.child_token(); |
| 2121 | if cancel_token.is_cancelled() { |
| 2122 | anyhow::bail!("MCP connection '{name}' was cancelled"); |
| 2123 | } |
| 2124 | let authority_revocation_reason = Arc::new(std::sync::Mutex::new(None)); |
| 2125 | if let Some(source) = config.reviewed_plugin_source() { |
| 2126 | source.validate_before_use(&name, "connect")?; |
| 2127 | if let Some(url) = config.url.as_deref() { |
| 2128 | source.validate_remote_endpoint(&name, url)?; |
| 2129 | } |
| 2130 | } |
| 2131 | // Start the cross-process generation watch before any network request |
| 2132 | // or child spawn. The guard cancels and aborts itself on every early |
| 2133 | // return; a successful connection transfers the task into `Self`. |
| 2134 | let authority_watch = config.reviewed_plugin_source().cloned().map(|source| { |
| 2135 | PendingAuthorityWatch::start( |
| 2136 | source, |
| 2137 | cancel_token.clone(), |
| 2138 | Arc::clone(&authority_revocation_reason), |
| 2139 | ) |
| 2140 | }); |
| 2141 | let http_client = if config.url.is_some() { |
| 2142 | let client_res = tokio::select! { |
| 2143 | biased; |
| 2144 | () = cancel_token.cancelled() => { |
| 2145 | anyhow::bail!("MCP connection '{name}' was cancelled"); |
| 2146 | } |
| 2147 | res = prepare_mcp_http_client( |
| 2148 | &name, |
| 2149 | &config, |
| 2150 | global_timeouts, |
| 2151 | network_policy, |
| 2152 | &cancel_token, |
| 2153 | connect_timeout_secs, |
| 2154 | Arc::clone(&auth_context), |
| 2155 | ) => res?, |
| 2156 | }; |
| 2157 | Some(client_res) |
| 2158 | } else { |
| 2159 | None |
| 2160 | }; |
| 2161 | let transport: Box<dyn McpTransport> = if backend == McpBackend::Host { |
| 2162 | let sdk_transport = tokio::select! { |
| 2163 | biased; |
| 2164 | () = cancel_token.cancelled() => { |
| 2165 | anyhow::bail!("MCP connection '{name}' was cancelled"); |
| 2166 | } |
| 2167 | res = crate::extension_host::mcp::SdkTransport::connect_with_http_and_auth_context( |
| 2168 | &name, |
| 2169 | &config, |
| 2170 | cancel_token.clone(), |
| 2171 | Duration::from_secs(connect_timeout_secs), |
| 2172 | http_client, |
| 2173 | Arc::clone(&auth_context), |
| 2174 | ) => res?, |
| 2175 | }; |
| 2176 | Box::new(sdk_transport) |
| 2177 | } else if let Some(url) = &config.url { |
| 2178 | let client = http_client.expect("prepared HTTP authority"); |
| 2179 | if is_legacy_sse_transport(&config) { |
| 2180 | let sse_transport = tokio::select! { |
| 2181 | biased; |
| 2182 | () = cancel_token.cancelled() => { |
| 2183 | anyhow::bail!("MCP connection '{name}' was cancelled"); |
| 2184 | } |
| 2185 | res = SseTransport::connect( |
| 2186 | client, |
| 2187 | url.clone(), |
| 2188 | cancel_token.clone(), |
| 2189 | Duration::from_secs(connect_timeout_secs), |
| 2190 | ) => res?, |
| 2191 | }; |
| 2192 | Box::new(sse_transport) |
| 2193 | } else { |
| 2194 | let mut http = HttpTransport::new( |
| 2195 | client, |
| 2196 | url.clone(), |
| 2197 | cancel_token.clone(), |
| 2198 | Duration::from_secs(connect_timeout_secs), |
| 2199 | ); |
| 2200 | // Best-effort session preflight for servers that require |
| 2201 | // a session ID on every POST including `initialize` |
| 2202 | // (e.g. Hindsight, #1629). Failures are non-fatal — the |
| 2203 | // `initialize` POST will proceed and may capture a session |
| 2204 | // ID from the response instead. |
| 2205 | tokio::select! { |
| 2206 | biased; |
| 2207 | () = cancel_token.cancelled() => { |
| 2208 | anyhow::bail!("MCP connection '{name}' was cancelled"); |
| 2209 | } |
| 2210 | res = http.try_establish_session() => { |
| 2211 | if let Err(e) = res { |
| 2212 | tracing::debug!( |
| 2213 | target: "mcp", |
| 2214 | server = %name, |
| 2215 | error = %e, |
| 2216 | "session-establishment GET skipped; proceeding with POST initialize" |
| 2217 | ); |
| 2218 | } |
| 2219 | } |
| 2220 | } |
| 2221 | Box::new(http) |
| 2222 | } |
| 2223 | } else if let Some(command) = &config.command { |
| 2224 | Box::new(StdioTransport::spawn_with_auth_context( |
| 2225 | &name, |
| 2226 | command, |
| 2227 | &config, |
| 2228 | cancel_token.clone(), |
| 2229 | Arc::clone(&auth_context), |
| 2230 | )?) |
| 2231 | } else { |
| 2232 | anyhow::bail!("MCP server '{name}' config must have either 'command' or 'url'"); |
| 2233 | }; |
| 2234 | let authority_watch = authority_watch.map(PendingAuthorityWatch::disarm); |
| 2235 | |
| 2236 | let mut conn = Self { |
| 2237 | auth_context, |
| 2238 | name: name.clone(), |
| 2239 | transport, |
| 2240 | tools: Vec::new(), |
| 2241 | resources: Vec::new(), |
| 2242 | resource_templates: Vec::new(), |
| 2243 | prompts: Vec::new(), |
| 2244 | skills: Vec::new(), |
| 2245 | skills_extension: false, |
| 2246 | request_id: AtomicU64::new(1), |
| 2247 | state: ConnectionState::Connecting, |
| 2248 | config, |
| 2249 | runtime_registration: None, |
| 2250 | server_capabilities: None, |
| 2251 | instructions: None, |
| 2252 | discovery_timeout: Duration::from_secs(connect_timeout_secs), |
| 2253 | read_timeout_secs, |
| 2254 | cancel_token: cancel_token.clone(), |
| 2255 | authority_revocation_reason, |
| 2256 | authority_watch, |
| 2257 | catalog_generation: 0, |
| 2258 | catalog_revision: 0, |
| 2259 | catalog_fresh_until: None, |
| 2260 | catalog_stale: false, |
| 2261 | decision_key: None, |
| 2262 | call_lane: None, |
| 2263 | }; |
| 2264 | |
| 2265 | let setup_result: Result<()> = tokio::select! { |
| 2266 | biased; |
| 2267 | () = cancel_token.cancelled() => { |
| 2268 | Err(anyhow::anyhow!("MCP connection '{name}' was cancelled")) |
| 2269 | } |
| 2270 | res = conn.finish_connect(backend, connect_timeout_secs) => res, |
| 2271 | }; |
| 2272 | if let Err(error) = setup_result { |
| 2273 | conn.transport.shutdown().await; |
| 2274 | return Err(error); |
| 2275 | } |
| 2276 | if cancel_token.is_cancelled() { |
| 2277 | conn.transport.shutdown().await; |
| 2278 | anyhow::bail!("MCP connection '{name}' was cancelled"); |
| 2279 | } |
| 2280 | conn.state = ConnectionState::Ready; |
| 2281 | Ok(conn) |
| 2282 | } |
| 2283 | |
| 2284 | async fn finish_connect( |
| 2285 | &mut self, |
| 2286 | backend: McpBackend, |
| 2287 | connect_timeout_secs: u64, |
| 2288 | ) -> Result<()> { |
| 2289 | if let Some(source) = self.config.reviewed_plugin_source() { |
| 2290 | source.validate_before_use(&self.name, "initialize")?; |
| 2291 | } |
| 2292 | |
| 2293 | // The reviewed Computer Use plugin accepts consent and script calls |
| 2294 | // only with a decision attested by its host. Its keys travel as the |
| 2295 | // first message on the plugin's own stdin, never in its environment. |
| 2296 | if backend == McpBackend::Rust |
| 2297 | && self.config.url.is_none() |
| 2298 | && self.config.command.is_some() |
| 2299 | && self |
| 2300 | .config |
| 2301 | .reviewed_plugin_source() |
| 2302 | .is_some_and(|source| source.plugin_name() == COMPUTER_USE_PLUGIN_NAME) |
| 2303 | { |
| 2304 | let decision_key = random_key()?; |
| 2305 | let ledger_key = computer_use_ledger_key().await; |
| 2306 | self.send(serde_json::json!({ |
| 2307 | "jsonrpc": "2.0", |
| 2308 | "method": COMPUTER_USE_HOST_KEYS_METHOD, |
| 2309 | "params": { |
| 2310 | "decision_key": hex_encode(&decision_key), |
| 2311 | "ledger_key": ledger_key, |
| 2312 | } |
| 2313 | })) |
| 2314 | .await?; |
| 2315 | self.decision_key = Some(decision_key); |
| 2316 | } |
| 2317 | |
| 2318 | // Initialize with timeout |
| 2319 | let connect_deadline = Duration::from_secs(connect_timeout_secs); |
| 2320 | let initialize_started = std::time::Instant::now(); |
| 2321 | let initialized = tokio::time::timeout(connect_deadline, self.initialize()) |
| 2322 | .await |
| 2323 | .map_err(anyhow::Error::from) |
| 2324 | .and_then(|result| result); |
| 2325 | if let Err(error) = initialized { |
| 2326 | if initialize_started.elapsed() >= connect_deadline { |
| 2327 | return Err(error.context(format!( |
| 2328 | "MCP server '{}' didn't start within {connect_timeout_secs}s; retry with /mcp restart, or raise its connect_timeout", |
| 2329 | self.name |
| 2330 | ))); |
| 2331 | } |
| 2332 | return Err(error); |
| 2333 | } |
| 2334 | |
| 2335 | self.discover_all() |
| 2336 | .await |
| 2337 | .with_context(|| format!("MCP server '{}' discovery failed", self.name))?; |
| 2338 | |
| 2339 | self.ensure_not_disconnected()?; |
| 2340 | Ok(()) |
| 2341 | } |
| 2342 | |
| 2343 | /// Send initialize request and wait for response |
| 2344 | async fn initialize(&mut self) -> Result<()> { |
| 2345 | let init_id = self.next_id(); |
| 2346 | self.send(serde_json::json!({ |
| 2347 | "jsonrpc": "2.0", |
| 2348 | "id": &init_id, |
| 2349 | "method": "initialize", |
| 2350 | "params": { |
| 2351 | "protocolVersion": MCP_PROTOCOL_VERSION, |
| 2352 | "clientInfo": { |
| 2353 | "name": "codewhale-tui", |
| 2354 | "version": env!("CARGO_PKG_VERSION") |
| 2355 | }, |
| 2356 | // Client capabilities name what the *client* offers the server |
| 2357 | // (roots, sampling, elicitation). `tools`/`resources`/`prompts` |
| 2358 | // are server capabilities; declaring them here is off-spec and |
| 2359 | // strict servers reject the handshake with -32602. We offer |
| 2360 | // none of the client features yet, so the object is empty. |
| 2361 | "capabilities": {} |
| 2362 | } |
| 2363 | })) |
| 2364 | .await?; |
| 2365 | |
| 2366 | let response = self.recv(init_id).await?; |
| 2367 | if let Some(error) = response.get("error") { |
| 2368 | // A JSON-RPC error on `initialize` is the server refusing the |
| 2369 | // handshake, not a transport fault: name the server and what was |
| 2370 | // launched, and carry the child's last stderr line, which is |
| 2371 | // usually the real reason (an MCP proxy that cannot reach its |
| 2372 | // upstream answers -32602 and explains itself only on stderr). |
| 2373 | let stderr = self |
| 2374 | .transport |
| 2375 | .last_stderr_line() |
| 2376 | .await |
| 2377 | .map(|line| format!("; server stderr: {line}")) |
| 2378 | .unwrap_or_default(); |
| 2379 | // Classified from the raw error and stderr *before* any |
| 2380 | // suppression, so a reviewed plugin's AWS server (the aws-core |
| 2381 | // plugin ships one) still learns its login expired. Only our own |
| 2382 | // fixed hint text leaves this branch, never the server's words. |
| 2383 | let raw = format!("{error}{stderr}"); |
| 2384 | let hint = if mcp_error_is_aws_login(&raw, mcp_server_oauth_capable(&self.config)) { |
| 2385 | format!("; {}", aws_login_hint(&self.config, &self.name, &raw)) |
| 2386 | } else { |
| 2387 | String::new() |
| 2388 | }; |
| 2389 | if self.config.reviewed_plugin.is_some() { |
| 2390 | anyhow::bail!( |
| 2391 | "Reviewed plugin MCP server returned an error in 'initialize' (server details suppressed to protect environment-backed credentials){hint}" |
| 2392 | ); |
| 2393 | } |
| 2394 | let launched = match (&self.config.command, &self.config.url) { |
| 2395 | (Some(command), _) => format!("command `{}`", mcp_display_target("stdio", command)), |
| 2396 | (None, Some(_)) => "HTTP endpoint".to_string(), |
| 2397 | (None, None) => "server".to_string(), |
| 2398 | }; |
| 2399 | anyhow::bail!( |
| 2400 | "MCP server '{}' rejected initialize ({launched}): {error}{stderr}{hint}", |
| 2401 | self.name |
| 2402 | ); |
| 2403 | } |
| 2404 | let result = response_result( |
| 2405 | &response, |
| 2406 | "initialize", |
| 2407 | self.config.reviewed_plugin.is_some(), |
| 2408 | )?; |
| 2409 | // Per spec, a server that cannot speak the advertised revision answers |
| 2410 | // with one it does support. Accept any dated revision we still |
| 2411 | // implement; anything else ends the handshake. |
| 2412 | let negotiated = result |
| 2413 | .and_then(|result| result.get("protocolVersion")) |
| 2414 | .and_then(|version| version.as_str()) |
| 2415 | .ok_or_else(|| { |
| 2416 | anyhow::anyhow!( |
| 2417 | "MCP server '{}' initialize result omitted protocolVersion", |
| 2418 | self.name |
| 2419 | ) |
| 2420 | })?; |
| 2421 | anyhow::ensure!( |
| 2422 | MCP_CLIENT_ACCEPTED_PROTOCOL_VERSIONS.contains(&negotiated) |
| 2423 | || (negotiated == MCP_MODERN_PROTOCOL_VERSION && self.transport.is_modern()), |
| 2424 | "MCP server '{}' negotiated unsupported protocol version '{negotiated}' (supported: {})", |
| 2425 | self.name, |
| 2426 | MCP_CLIENT_ACCEPTED_PROTOCOL_VERSIONS.join(", ") |
| 2427 | ); |
| 2428 | self.transport.set_protocol_version(negotiated); |
| 2429 | self.server_capabilities = McpServerCapabilities::from_initialize_response(&response); |
| 2430 | self.skills_extension = result |
| 2431 | .and_then(|result| result.pointer("/capabilities/extensions")) |
| 2432 | .and_then(|extensions| extensions.get(MCP_SKILLS_EXTENSION)) |
| 2433 | .is_some_and(serde_json::Value::is_object); |
| 2434 | self.instructions = codewhale_mcp::sanitize_server_instructions( |
| 2435 | &self.name, |
| 2436 | result.and_then(|result| result.get("instructions")), |
| 2437 | ); |
| 2438 | |
| 2439 | // Send initialized notification (no id, no response expected) |
| 2440 | self.send(serde_json::json!({ |
| 2441 | "jsonrpc": "2.0", |
| 2442 | "method": "notifications/initialized" |
| 2443 | })) |
| 2444 | .await?; |
| 2445 | |
| 2446 | Ok(()) |
| 2447 | } |
| 2448 | |
| 2449 | fn ensure_not_disconnected(&mut self) -> Result<()> { |
| 2450 | if self.cancel_token.is_cancelled() { |
| 2451 | self.state = ConnectionState::Disconnected; |
| 2452 | anyhow::bail!("MCP connection '{}' was cancelled", self.name); |
| 2453 | } |
| 2454 | if self.state == ConnectionState::Disconnected { |
| 2455 | anyhow::bail!("MCP connection '{}' is disconnected", self.name); |
| 2456 | } |
| 2457 | Ok(()) |
| 2458 | } |
| 2459 | |
| 2460 | /// Discover and admit one complete tools/resources/prompts generation. |
| 2461 | async fn discover_all(&mut self) -> Result<()> { |
| 2462 | settle_call_lane(self.call_lane.clone()).await; |
| 2463 | self.ensure_not_disconnected()?; |
| 2464 | let capabilities = self.server_capabilities; |
| 2465 | let server = self.name.clone(); |
| 2466 | let discovery_timeout = self.discovery_timeout; |
| 2467 | let mut budget = McpCatalogBudget::new(); |
| 2468 | let mut tools = None; |
| 2469 | let mut resources = None; |
| 2470 | let mut resource_templates = None; |
| 2471 | let mut prompts = None; |
| 2472 | let mut skills = None; |
| 2473 | |
| 2474 | // Missing initialize metadata is treated as a legacy/unknown server: |
| 2475 | // retain tool discovery and bounded best-effort probes for compatibility. |
| 2476 | // When capabilities are advertised, do not call methods the server says |
| 2477 | // it does not implement (notably JetBrains tools-only MCP servers). |
| 2478 | if capabilities.is_none_or(|capabilities| capabilities.tools) { |
| 2479 | tools = Some( |
| 2480 | tokio::time::timeout(discovery_timeout, self.discover_tools(&mut budget)) |
| 2481 | .await |
| 2482 | .with_context(|| { |
| 2483 | format!( |
| 2484 | "MCP server '{}' tool discovery timed out after {:?}", |
| 2485 | server, discovery_timeout |
| 2486 | ) |
| 2487 | })??, |
| 2488 | ); |
| 2489 | } |
| 2490 | |
| 2491 | // Keep all three optional calls within one discovery-timeout budget in |
| 2492 | // the worst case while also respecting a tighter transport read timeout. |
| 2493 | let optional_timeout = |
| 2494 | (discovery_timeout / 3).min(Duration::from_secs(self.read_timeout_secs)); |
| 2495 | if capabilities.is_none_or(|capabilities| capabilities.resources) { |
| 2496 | resources = run_optional_discovery( |
| 2497 | &server, |
| 2498 | "resources/list", |
| 2499 | optional_timeout, |
| 2500 | self.discover_resources(&mut budget), |
| 2501 | ) |
| 2502 | .await; |
| 2503 | self.ensure_not_disconnected()?; |
| 2504 | resource_templates = run_optional_discovery( |
| 2505 | &server, |
| 2506 | "resources/templates/list", |
| 2507 | optional_timeout, |
| 2508 | self.discover_resource_templates(&mut budget), |
| 2509 | ) |
| 2510 | .await; |
| 2511 | self.ensure_not_disconnected()?; |
| 2512 | } |
| 2513 | if capabilities.is_none_or(|capabilities| capabilities.prompts) { |
| 2514 | prompts = run_optional_discovery( |
| 2515 | &server, |
| 2516 | "prompts/list", |
| 2517 | optional_timeout, |
| 2518 | self.discover_prompts(&mut budget), |
| 2519 | ) |
| 2520 | .await; |
| 2521 | self.ensure_not_disconnected()?; |
| 2522 | } |
| 2523 | if self.skills_extension { |
| 2524 | skills = run_optional_discovery( |
| 2525 | &server, |
| 2526 | "skills/list", |
| 2527 | optional_timeout, |
| 2528 | self.discover_skills(&mut budget), |
| 2529 | ) |
| 2530 | .await; |
| 2531 | self.ensure_not_disconnected()?; |
| 2532 | } |
| 2533 | // Ordinary optional-method errors remain best effort. Admit only the |
| 2534 | // freshly staged families; do not mix them with an old generation. |
| 2535 | // A budget/cursor refusal preserves the entire previous catalog. |
| 2536 | budget.ensure_available()?; |
| 2537 | self.tools = tools.unwrap_or_default(); |
| 2538 | self.resources = resources.unwrap_or_default(); |
| 2539 | self.resource_templates = resource_templates.unwrap_or_default(); |
| 2540 | self.prompts = prompts.unwrap_or_default(); |
| 2541 | self.skills = skills.unwrap_or_default(); |
| 2542 | self.catalog_fresh_until = budget.ttl_ms.map(|ttl| { |
| 2543 | std::time::Instant::now() |
| 2544 | + Duration::from_millis(ttl.clamp(MIN_MCP_CATALOG_TTL_MS, MAX_MCP_CATALOG_TTL_MS)) |
| 2545 | }); |
| 2546 | self.catalog_stale = false; |
| 2547 | Ok(()) |
| 2548 | } |
| 2549 | |
| 2550 | fn catalog_needs_revalidation(&mut self) -> bool { |
| 2551 | if self.transport.take_list_changed() { |
| 2552 | self.catalog_stale = true; |
| 2553 | } |
| 2554 | self.catalog_stale |
| 2555 | || self |
| 2556 | .catalog_fresh_until |
| 2557 | .is_some_and(|until| std::time::Instant::now() >= until) |
| 2558 | } |
| 2559 | |
| 2560 | /// Rediscover a stale catalog on its own connection. Returns whether the |
| 2561 | /// admitted catalog changed; a failure leaves the previous catalog in |
| 2562 | /// place and the caller retires the connection. |
| 2563 | async fn revalidate_catalog(&mut self) -> Result<bool> { |
| 2564 | let before = ( |
| 2565 | serde_json::to_value(&self.tools)?, |
| 2566 | serde_json::to_value(&self.resources)?, |
| 2567 | serde_json::to_value(&self.resource_templates)?, |
| 2568 | serde_json::to_value(&self.prompts)?, |
| 2569 | serde_json::to_value(&self.skills)?, |
| 2570 | ); |
| 2571 | self.discover_all().await?; |
| 2572 | let changed = before |
| 2573 | != ( |
| 2574 | serde_json::to_value(&self.tools)?, |
| 2575 | serde_json::to_value(&self.resources)?, |
| 2576 | serde_json::to_value(&self.resource_templates)?, |
| 2577 | serde_json::to_value(&self.prompts)?, |
| 2578 | serde_json::to_value(&self.skills)?, |
| 2579 | ); |
| 2580 | if changed { |
| 2581 | self.catalog_revision = self.catalog_revision.wrapping_add(1); |
| 2582 | } |
| 2583 | Ok(changed) |
| 2584 | } |
| 2585 | |
| 2586 | /// Discover available tools from the MCP server |
| 2587 | async fn discover_tools(&mut self, budget: &mut McpCatalogBudget) -> Result<Vec<McpTool>> { |
| 2588 | let mut cursor: Option<String> = None; |
| 2589 | let mut discovered = Vec::new(); |
| 2590 | loop { |
| 2591 | budget.ensure_available()?; |
| 2592 | let list_id = self.next_id(); |
| 2593 | let params = match &cursor { |
| 2594 | Some(c) => serde_json::json!({ "cursor": c }), |
| 2595 | None => serde_json::json!({}), |
| 2596 | }; |
| 2597 | self.send(serde_json::json!({ |
| 2598 | "jsonrpc": "2.0", |
| 2599 | "id": &list_id, |
| 2600 | "method": "tools/list", |
| 2601 | "params": params |
| 2602 | })) |
| 2603 | .await?; |
| 2604 | |
| 2605 | let response = self.recv(list_id).await?; |
| 2606 | let Some(result) = response_result( |
| 2607 | &response, |
| 2608 | "tools/list", |
| 2609 | self.config.reviewed_plugin.is_some(), |
| 2610 | )? |
| 2611 | else { |
| 2612 | break; |
| 2613 | }; |
| 2614 | |
| 2615 | let items = result |
| 2616 | .get("tools") |
| 2617 | .and_then(|tools| tools.as_array()) |
| 2618 | .map_or(0, Vec::len); |
| 2619 | cursor = budget.observe_page("tools/list", result, items)?; |
| 2620 | if let Some(arr) = result.get("tools").and_then(|t| t.as_array()) { |
| 2621 | for item in arr { |
| 2622 | match serde_json::from_value::<McpTool>(item.clone()) { |
| 2623 | Ok(tool) => discovered.push(tool), |
| 2624 | Err(err) => { |
| 2625 | // Skip individual malformed entries instead of |
| 2626 | // dropping the whole page (#1410). The old |
| 2627 | // `unwrap_or_default()` would silently throw |
| 2628 | // away every tool when one was misshapen. |
| 2629 | tracing::debug!(target: "mcp", ?err, "skipping malformed tool item"); |
| 2630 | } |
| 2631 | } |
| 2632 | } |
| 2633 | } |
| 2634 | |
| 2635 | if cursor.is_none() { |
| 2636 | break; |
| 2637 | } |
| 2638 | } |
| 2639 | // Sort by tool name so the order the model sees doesn't depend on |
| 2640 | // server-side pagination ordering — keeps the prompt prefix stable |
| 2641 | // for cache-hit purposes (#1319). |
| 2642 | discovered.sort_by(|a, b| a.name.cmp(&b.name)); |
| 2643 | Ok(discovered) |
| 2644 | } |
| 2645 | |
| 2646 | /// Discover available resources from the MCP server |
| 2647 | async fn discover_resources( |
| 2648 | &mut self, |
| 2649 | budget: &mut McpCatalogBudget, |
| 2650 | ) -> Result<Vec<McpResource>> { |
| 2651 | let mut cursor: Option<String> = None; |
| 2652 | let mut discovered = Vec::new(); |
| 2653 | loop { |
| 2654 | budget.ensure_available()?; |
| 2655 | let list_id = self.next_id(); |
| 2656 | let params = match &cursor { |
| 2657 | Some(c) => serde_json::json!({ "cursor": c }), |
| 2658 | None => serde_json::json!({}), |
| 2659 | }; |
| 2660 | self.send(serde_json::json!({ |
| 2661 | "jsonrpc": "2.0", |
| 2662 | "id": &list_id, |
| 2663 | "method": "resources/list", |
| 2664 | "params": params |
| 2665 | })) |
| 2666 | .await?; |
| 2667 | |
| 2668 | let response = self.recv(list_id).await?; |
| 2669 | let Some(result) = response_result( |
| 2670 | &response, |
| 2671 | "resources/list", |
| 2672 | self.config.reviewed_plugin.is_some(), |
| 2673 | )? |
| 2674 | else { |
| 2675 | break; |
| 2676 | }; |
| 2677 | |
| 2678 | let items = result |
| 2679 | .get("resources") |
| 2680 | .and_then(|resources| resources.as_array()) |
| 2681 | .map_or(0, Vec::len); |
| 2682 | cursor = budget.observe_page("resources/list", result, items)?; |
| 2683 | if let Some(arr) = result.get("resources").and_then(|r| r.as_array()) { |
| 2684 | for item in arr { |
| 2685 | match serde_json::from_value::<McpResource>(item.clone()) { |
| 2686 | Ok(resource) => discovered.push(resource), |
| 2687 | Err(err) => { |
| 2688 | tracing::debug!(target: "mcp", ?err, "skipping malformed resource item"); |
| 2689 | } |
| 2690 | } |
| 2691 | } |
| 2692 | } |
| 2693 | |
| 2694 | if cursor.is_none() { |
| 2695 | break; |
| 2696 | } |
| 2697 | } |
| 2698 | Ok(discovered) |
| 2699 | } |
| 2700 | |
| 2701 | /// Discover available resource templates from the MCP server |
| 2702 | async fn discover_resource_templates( |
| 2703 | &mut self, |
| 2704 | budget: &mut McpCatalogBudget, |
| 2705 | ) -> Result<Vec<McpResourceTemplate>> { |
| 2706 | let mut cursor: Option<String> = None; |
| 2707 | let mut discovered = Vec::new(); |
| 2708 | loop { |
| 2709 | budget.ensure_available()?; |
| 2710 | let list_id = self.next_id(); |
| 2711 | let params = match &cursor { |
| 2712 | Some(c) => serde_json::json!({ "cursor": c }), |
| 2713 | None => serde_json::json!({}), |
| 2714 | }; |
| 2715 | self.send(serde_json::json!({ |
| 2716 | "jsonrpc": "2.0", |
| 2717 | "id": &list_id, |
| 2718 | "method": "resources/templates/list", |
| 2719 | "params": params |
| 2720 | })) |
| 2721 | .await?; |
| 2722 | |
| 2723 | let response = self.recv(list_id).await?; |
| 2724 | let Some(result) = response_result( |
| 2725 | &response, |
| 2726 | "resources/templates/list", |
| 2727 | self.config.reviewed_plugin.is_some(), |
| 2728 | )? |
| 2729 | else { |
| 2730 | break; |
| 2731 | }; |
| 2732 | |
| 2733 | let templates = result |
| 2734 | .get("resourceTemplates") |
| 2735 | .or_else(|| result.get("templates")) |
| 2736 | .or_else(|| result.get("resource_templates")); |
| 2737 | let items = templates |
| 2738 | .and_then(|templates| templates.as_array()) |
| 2739 | .map_or(0, Vec::len); |
| 2740 | cursor = budget.observe_page("resources/templates/list", result, items)?; |
| 2741 | if let Some(arr) = templates.and_then(|t| t.as_array()) { |
| 2742 | for item in arr { |
| 2743 | match serde_json::from_value::<McpResourceTemplate>(item.clone()) { |
| 2744 | Ok(tmpl) => discovered.push(tmpl), |
| 2745 | Err(err) => { |
| 2746 | tracing::debug!(target: "mcp", ?err, "skipping malformed resource_template item"); |
| 2747 | } |
| 2748 | } |
| 2749 | } |
| 2750 | } |
| 2751 | |
| 2752 | if cursor.is_none() { |
| 2753 | break; |
| 2754 | } |
| 2755 | } |
| 2756 | Ok(discovered) |
| 2757 | } |
| 2758 | |
| 2759 | /// Discover available prompts from the MCP server |
| 2760 | async fn discover_prompts(&mut self, budget: &mut McpCatalogBudget) -> Result<Vec<McpPrompt>> { |
| 2761 | let mut cursor: Option<String> = None; |
| 2762 | let mut discovered = Vec::new(); |
| 2763 | loop { |
| 2764 | budget.ensure_available()?; |
| 2765 | let list_id = self.next_id(); |
| 2766 | let params = match &cursor { |
| 2767 | Some(c) => serde_json::json!({ "cursor": c }), |
| 2768 | None => serde_json::json!({}), |
| 2769 | }; |
| 2770 | self.send(serde_json::json!({ |
| 2771 | "jsonrpc": "2.0", |
| 2772 | "id": &list_id, |
| 2773 | "method": "prompts/list", |
| 2774 | "params": params |
| 2775 | })) |
| 2776 | .await?; |
| 2777 | |
| 2778 | let response = self.recv(list_id).await?; |
| 2779 | let Some(result) = response_result( |
| 2780 | &response, |
| 2781 | "prompts/list", |
| 2782 | self.config.reviewed_plugin.is_some(), |
| 2783 | )? |
| 2784 | else { |
| 2785 | break; |
| 2786 | }; |
| 2787 | |
| 2788 | let items = result |
| 2789 | .get("prompts") |
| 2790 | .and_then(|prompts| prompts.as_array()) |
| 2791 | .map_or(0, Vec::len); |
| 2792 | cursor = budget.observe_page("prompts/list", result, items)?; |
| 2793 | if let Some(arr) = result.get("prompts").and_then(|p| p.as_array()) { |
| 2794 | for item in arr { |
| 2795 | match serde_json::from_value::<McpPrompt>(item.clone()) { |
| 2796 | Ok(prompt) => discovered.push(prompt), |
| 2797 | Err(err) => { |
| 2798 | tracing::debug!(target: "mcp", ?err, "skipping malformed prompt item"); |
| 2799 | } |
| 2800 | } |
| 2801 | } |
| 2802 | } |
| 2803 | |
| 2804 | if cursor.is_none() { |
| 2805 | break; |
| 2806 | } |
| 2807 | } |
| 2808 | Ok(discovered) |
| 2809 | } |
| 2810 | |
| 2811 | async fn discover_skills(&mut self, budget: &mut McpCatalogBudget) -> Result<Vec<McpSkill>> { |
| 2812 | let mut cursor: Option<String> = None; |
| 2813 | let mut discovered: Vec<McpSkill> = Vec::new(); |
| 2814 | loop { |
| 2815 | budget.ensure_available()?; |
| 2816 | let list_id = self.next_id(); |
| 2817 | let params = match &cursor { |
| 2818 | Some(c) => serde_json::json!({ "cursor": c }), |
| 2819 | None => serde_json::json!({}), |
| 2820 | }; |
| 2821 | self.send(serde_json::json!({ |
| 2822 | "jsonrpc": "2.0", |
| 2823 | "id": &list_id, |
| 2824 | "method": "skills/list", |
| 2825 | "params": params |
| 2826 | })) |
| 2827 | .await?; |
| 2828 | let response = self.recv(list_id).await?; |
| 2829 | let Some(result) = response_result( |
| 2830 | &response, |
| 2831 | "skills/list", |
| 2832 | self.config.reviewed_plugin.is_some(), |
| 2833 | )? |
| 2834 | else { |
| 2835 | break; |
| 2836 | }; |
| 2837 | let items = result |
| 2838 | .get("skills") |
| 2839 | .and_then(serde_json::Value::as_array) |
| 2840 | .map_or(0, Vec::len); |
| 2841 | cursor = budget.observe_page("skills/list", result, items)?; |
| 2842 | for item in result |
| 2843 | .get("skills") |
| 2844 | .and_then(serde_json::Value::as_array) |
| 2845 | .into_iter() |
| 2846 | .flatten() |
| 2847 | { |
| 2848 | match serde_json::from_value::<McpSkill>(item.clone()) { |
| 2849 | Ok(skill) |
| 2850 | if skill.admissible() |
| 2851 | && !discovered.iter().any(|known| known.uri == skill.uri) => |
| 2852 | { |
| 2853 | discovered.push(skill); |
| 2854 | } |
| 2855 | _ => tracing::debug!(target: "mcp", "skipping inadmissible skill entry"), |
| 2856 | } |
| 2857 | } |
| 2858 | if cursor.is_none() { |
| 2859 | break; |
| 2860 | } |
| 2861 | } |
| 2862 | discovered.sort_by(|a, b| a.uri.cmp(&b.uri)); |
| 2863 | Ok(discovered) |
| 2864 | } |
| 2865 | |
| 2866 | /// Call a tool on this MCP server |
| 2867 | #[cfg(any(test, feature = "test-support"))] |
| 2868 | pub async fn call_tool( |
| 2869 | &mut self, |
| 2870 | tool_name: &str, |
| 2871 | arguments: serde_json::Value, |
| 2872 | timeout_secs: u64, |
| 2873 | ) -> Result<serde_json::Value> { |
| 2874 | self.call_tool_decided(tool_name, arguments, timeout_secs, None) |
| 2875 | .await |
| 2876 | } |
| 2877 | |
| 2878 | /// Call a tool, attaching an attested person's decision when there is |
| 2879 | /// one and this server shares a decision key with the host. |
| 2880 | async fn call_tool_decided( |
| 2881 | &mut self, |
| 2882 | tool_name: &str, |
| 2883 | arguments: serde_json::Value, |
| 2884 | timeout_secs: u64, |
| 2885 | decision: Option<&crate::core::engine::HumanDecision>, |
| 2886 | ) -> Result<serde_json::Value> { |
| 2887 | let mut params = serde_json::json!({ |
| 2888 | "name": tool_name, |
| 2889 | "arguments": arguments |
| 2890 | }); |
| 2891 | if decision.is_some() |
| 2892 | && let Some(key) = self.decision_key.as_ref() |
| 2893 | { |
| 2894 | params["_meta"] = serde_json::json!({ |
| 2895 | COMPUTER_USE_DECISION_META: attest_decision(key, tool_name, ¶ms["arguments"])?, |
| 2896 | }); |
| 2897 | } |
| 2898 | self.call_method_decided("tools/call", params, timeout_secs, decision) |
| 2899 | .await |
| 2900 | } |
| 2901 | |
| 2902 | /// Read a resource from this MCP server |
| 2903 | pub async fn read_resource( |
| 2904 | &mut self, |
| 2905 | uri: &str, |
| 2906 | timeout_secs: u64, |
| 2907 | ) -> Result<serde_json::Value> { |
| 2908 | self.call_method( |
| 2909 | "resources/read", |
| 2910 | serde_json::json!({ |
| 2911 | "uri": uri |
| 2912 | }), |
| 2913 | timeout_secs, |
| 2914 | ) |
| 2915 | .await |
| 2916 | } |
| 2917 | |
| 2918 | /// Get a prompt from this MCP server |
| 2919 | pub async fn get_prompt( |
| 2920 | &mut self, |
| 2921 | prompt_name: &str, |
| 2922 | arguments: serde_json::Value, |
| 2923 | timeout_secs: u64, |
| 2924 | ) -> Result<serde_json::Value> { |
| 2925 | self.call_method( |
| 2926 | "prompts/get", |
| 2927 | serde_json::json!({ |
| 2928 | "name": prompt_name, |
| 2929 | "arguments": arguments |
| 2930 | }), |
| 2931 | timeout_secs, |
| 2932 | ) |
| 2933 | .await |
| 2934 | } |
| 2935 | |
| 2936 | /// Generic method to call an MCP method |
| 2937 | async fn call_method( |
| 2938 | &mut self, |
| 2939 | method: &str, |
| 2940 | params: serde_json::Value, |
| 2941 | timeout_secs: u64, |
| 2942 | ) -> Result<serde_json::Value> { |
| 2943 | self.call_method_decided(method, params, timeout_secs, None) |
| 2944 | .await |
| 2945 | } |
| 2946 | async fn call_method_decided( |
| 2947 | &mut self, |
| 2948 | method: &str, |
| 2949 | params: serde_json::Value, |
| 2950 | timeout_secs: u64, |
| 2951 | decision: Option<&crate::core::engine::HumanDecision>, |
| 2952 | ) -> Result<serde_json::Value> { |
| 2953 | settle_call_lane(self.call_lane.clone()).await; |
| 2954 | let cancellation = self |
| 2955 | .config |
| 2956 | .reviewed_plugin_source() |
| 2957 | .and_then(|source| source.native_mcp.as_ref()) |
| 2958 | .cloned(); |
| 2959 | let Some(cancellation) = cancellation else { |
| 2960 | return self |
| 2961 | .call_method_decided_inner(method, params, timeout_secs, decision) |
| 2962 | .await; |
| 2963 | }; |
| 2964 | let outcome = tokio::select! { |
| 2965 | biased; |
| 2966 | _=cancellation.withdrawn()=>None, |
| 2967 | result=self.call_method_decided_inner(method,params,timeout_secs,decision)=>Some(result), |
| 2968 | }; |
| 2969 | match outcome { |
| 2970 | Some(result)=>result, |
| 2971 | None=>self.finish_guarded_error(anyhow::anyhow!("Native MCP operation cancelled because its definition was withdrawn; the operation is not replayed")).await, |
| 2972 | } |
| 2973 | } |
| 2974 | async fn call_method_decided_inner( |
| 2975 | &mut self, |
| 2976 | method: &str, |
| 2977 | params: serde_json::Value, |
| 2978 | timeout_secs: u64, |
| 2979 | decision: Option<&crate::core::engine::HumanDecision>, |
| 2980 | ) -> Result<serde_json::Value> { |
| 2981 | if self.state != ConnectionState::Ready { |
| 2982 | anyhow::bail!( |
| 2983 | "Failed to call MCP method '{}': connection '{}' is not ready", |
| 2984 | method, |
| 2985 | self.name |
| 2986 | ); |
| 2987 | } |
| 2988 | if let Some(source) = self.config.reviewed_plugin_source() { |
| 2989 | source.validate_before_use(&self.name, method)?; |
| 2990 | } |
| 2991 | |
| 2992 | let call_id = self.next_id(); |
| 2993 | // One deadline bounds the whole request. Streamable HTTP reads the |
| 2994 | // reply inside the POST, so a budget on the receive alone would leave |
| 2995 | // that transport to its client-wide ceiling (the larger of the read |
| 2996 | // and execute knobs) instead of this request's own budget. |
| 2997 | let deadline = tokio::time::Instant::now() + Duration::from_secs(timeout_secs); |
| 2998 | let expired_error = anyhow::anyhow!( |
| 2999 | "MCP method '{}' on server '{}' timed out after {}s", |
| 3000 | method, |
| 3001 | self.name, |
| 3002 | timeout_secs |
| 3003 | ); |
| 3004 | match tokio::time::timeout_at( |
| 3005 | deadline, |
| 3006 | self.send_decided( |
| 3007 | serde_json::json!({ |
| 3008 | "jsonrpc": "2.0", |
| 3009 | "id": &call_id, |
| 3010 | "method": method, |
| 3011 | "params": params |
| 3012 | }), |
| 3013 | decision, |
| 3014 | Duration::from_secs(timeout_secs), |
| 3015 | ), |
| 3016 | ) |
| 3017 | .await |
| 3018 | { |
| 3019 | Ok(Ok(())) => {} |
| 3020 | Ok(Err(error)) => return self.finish_guarded_error(error).await, |
| 3021 | Err(_) => { |
| 3022 | // A send abandoned mid-write can leave a partial frame on a |
| 3023 | // stream transport, so the frame boundary is unknown: rebuild |
| 3024 | // the connection rather than reuse it. |
| 3025 | self.state = ConnectionState::Disconnected; |
| 3026 | return self.finish_guarded_error(expired_error).await; |
| 3027 | } |
| 3028 | } |
| 3029 | |
| 3030 | // The request's own budget is its only receive deadline. A per-frame |
| 3031 | // read-knob wait here either undercut it — a server is silent for the |
| 3032 | // whole execution of a tool call, so the knob fired first, marked the |
| 3033 | // connection Disconnected, and capped a raised `execute_timeout` — or |
| 3034 | // tied with it, leaving the connection's fate to timer order. On |
| 3035 | // expiry the request is abandoned and the connection kept: a late |
| 3036 | // reply carries the abandoned id and the next receive skips it. |
| 3037 | // |
| 3038 | // On receive timeout, send a best-effort bounded `notifications/cancelled` |
| 3039 | // so servers that honor MCP cancellation can stop work early instead of |
| 3040 | // blocking the next call. Caller-dropped turn cancellations still rely on |
| 3041 | // cancelling `cancel_token`, which marks the connection dead so the pool |
| 3042 | // rebuilds it (a new child for stdio) before the next call. |
| 3043 | let response = |
| 3044 | match tokio::time::timeout_at(deadline, self.recv_reply(call_id.clone(), None)) |
| 3045 | .await |
| 3046 | .with_context(|| { |
| 3047 | format!( |
| 3048 | "MCP method '{}' on server '{}' timed out after {}s", |
| 3049 | method, self.name, timeout_secs |
| 3050 | ) |
| 3051 | }) { |
| 3052 | Ok(Ok(response)) => response, |
| 3053 | Ok(Err(error)) => return self.finish_guarded_error(error).await, |
| 3054 | Err(error) => { |
| 3055 | if self.state == ConnectionState::Ready { |
| 3056 | let cancel_timeout = Duration::from_secs(2); |
| 3057 | let cancel_msg = serde_json::json!({ |
| 3058 | "jsonrpc": "2.0", |
| 3059 | "method": "notifications/cancelled", |
| 3060 | "params": { |
| 3061 | "requestId": call_id, |
| 3062 | "reason": format!( |
| 3063 | "MCP method '{}' timed out after {}s", |
| 3064 | method, timeout_secs |
| 3065 | ), |
| 3066 | } |
| 3067 | }); |
| 3068 | if !matches!( |
| 3069 | tokio::time::timeout( |
| 3070 | cancel_timeout, |
| 3071 | self.send_decided(cancel_msg, None, cancel_timeout), |
| 3072 | ) |
| 3073 | .await, |
| 3074 | Ok(Ok(())) |
| 3075 | ) { |
| 3076 | self.state = ConnectionState::Disconnected; |
| 3077 | } |
| 3078 | } |
| 3079 | return self.finish_guarded_error(error).await; |
| 3080 | } |
| 3081 | }; |
| 3082 | |
| 3083 | if let Some(source) = self.config.reviewed_plugin_source() { |
| 3084 | source.validate_before_use(&self.name, method)?; |
| 3085 | } |
| 3086 | if let Some(error) = response.get("error") { |
| 3087 | if self.config.reviewed_plugin.is_some() { |
| 3088 | // Preserve only the fixed recovery class, just as initialize |
| 3089 | // does; raw server details may contain plugin credentials. |
| 3090 | let raw = error.to_string(); |
| 3091 | let hint = if mcp_error_is_aws_login(&raw, mcp_server_oauth_capable(&self.config)) { |
| 3092 | format!("; {}", aws_login_hint(&self.config, &self.name, &raw)) |
| 3093 | } else { |
| 3094 | String::new() |
| 3095 | }; |
| 3096 | anyhow::bail!( |
| 3097 | "Reviewed plugin MCP server returned an error in '{method}' (server details suppressed to protect environment-backed credentials){hint}" |
| 3098 | ); |
| 3099 | } |
| 3100 | return Err(anyhow::anyhow!( |
| 3101 | "MCP error in '{}': {}", |
| 3102 | method, |
| 3103 | serde_json::to_string_pretty(error)? |
| 3104 | )); |
| 3105 | } |
| 3106 | |
| 3107 | // JSON-RPC requires exactly one of `result` / `error`. Treating a |
| 3108 | // response carrying neither as an empty success handed the model a |
| 3109 | // `null` tool result that is indistinguishable from a tool that |
| 3110 | // genuinely returned nothing. An explicit `"result": null` is still a |
| 3111 | // valid empty success and passes through unchanged. |
| 3112 | response_result(&response, method, self.config.reviewed_plugin.is_some())?.cloned().with_context(|| { |
| 3113 | format!( |
| 3114 | "MCP response from server '{}' for '{method}' contained neither a result nor an error", |
| 3115 | self.name |
| 3116 | ) |
| 3117 | }) |
| 3118 | } |
| 3119 | |
| 3120 | /// Get discovered tools |
| 3121 | pub fn tools(&self) -> &[McpTool] { |
| 3122 | &self.tools |
| 3123 | } |
| 3124 | |
| 3125 | fn skill_file(&self, uri: &str) -> Option<McpSkillFile> { |
| 3126 | self.skills |
| 3127 | .iter() |
| 3128 | .flat_map(|skill| &skill.resources) |
| 3129 | .find(|file| file.uri == uri) |
| 3130 | .cloned() |
| 3131 | } |
| 3132 | |
| 3133 | fn skill_items(&self, server: &str) -> impl Iterator<Item = serde_json::Value> + '_ { |
| 3134 | let server = server.to_string(); |
| 3135 | self.skills.iter().map(move |skill| { |
| 3136 | serde_json::json!({ |
| 3137 | "server": server, |
| 3138 | "uri": skill.uri, |
| 3139 | "name": skill.name(), |
| 3140 | "description": skill.description(), |
| 3141 | "mime_type": "text/markdown", |
| 3142 | "skill": { |
| 3143 | "files": skill.resources.iter().map(|file| &file.uri).collect::<Vec<_>>(), |
| 3144 | "activation": "explicit read only", |
| 3145 | }, |
| 3146 | }) |
| 3147 | }) |
| 3148 | } |
| 3149 | |
| 3150 | /// Get discovered resources |
| 3151 | pub fn resources(&self) -> &[McpResource] { |
| 3152 | &self.resources |
| 3153 | } |
| 3154 | |
| 3155 | /// Get discovered resource templates |
| 3156 | pub fn resource_templates(&self) -> &[McpResourceTemplate] { |
| 3157 | &self.resource_templates |
| 3158 | } |
| 3159 | |
| 3160 | /// Get discovered prompts |
| 3161 | pub fn prompts(&self) -> &[McpPrompt] { |
| 3162 | &self.prompts |
| 3163 | } |
| 3164 | |
| 3165 | /// Get server name |
| 3166 | pub fn name(&self) -> &str { |
| 3167 | &self.name |
| 3168 | } |
| 3169 | |
| 3170 | /// Ready to dispatch: the transport is live **and** the plugin bundle |
| 3171 | /// backing it still carries the authority it was reviewed with. |
| 3172 | pub fn is_ready(&self) -> bool { |
| 3173 | self.is_transport_ready() && self.catalog_authorized() |
| 3174 | } |
| 3175 | |
| 3176 | /// The Ready flag alone can't see a stdio child that exited between |
| 3177 | /// calls; the probe closes that gap so the pool rebuilds the connection |
| 3178 | /// instead of handing a dead transport back (#6187). |
| 3179 | /// |
| 3180 | /// Only for callers that have just run `validate_before_use` on this same |
| 3181 | /// source, where `is_ready`'s authority half would re-walk and re-hash the |
| 3182 | /// plugin bundle it already verified one statement earlier (#6209). Every |
| 3183 | /// other caller must use `is_ready`: dropping the authority half without |
| 3184 | /// a preceding check silently dispatches to a revoked or altered bundle. |
| 3185 | pub fn is_transport_ready(&self) -> bool { |
| 3186 | self.state == ConnectionState::Ready |
| 3187 | && self.runtime_registration_is_current() |
| 3188 | && !self.transport.probe_dead() |
| 3189 | } |
| 3190 | |
| 3191 | /// Usage guidance the server supplied at `initialize`, sanitized and |
| 3192 | /// capped (see [`codewhale_mcp::sanitize_server_instructions`]). |
| 3193 | pub fn instructions(&self) -> Option<&str> { |
| 3194 | self.instructions.as_deref() |
| 3195 | } |
| 3196 | |
| 3197 | /// Get server config |
| 3198 | pub fn config(&self) -> &McpServerConfig { |
| 3199 | &self.config |
| 3200 | } |
| 3201 | |
| 3202 | /// Get connection state |
| 3203 | pub fn state(&self) -> ConnectionState { |
| 3204 | if self |
| 3205 | .call_lane |
| 3206 | .as_ref() |
| 3207 | .is_some_and(|lane| lane.broken.load(Ordering::SeqCst)) |
| 3208 | { |
| 3209 | return ConnectionState::Disconnected; |
| 3210 | } |
| 3211 | self.state |
| 3212 | } |
| 3213 | |
| 3214 | fn call_lane(&mut self) -> Arc<McpCallLane> { |
| 3215 | if let Some(lane) = &self.call_lane { |
| 3216 | return Arc::clone(lane); |
| 3217 | } |
| 3218 | let transport = std::mem::replace(&mut self.transport, Box::new(DetachedTransport)); |
| 3219 | let lane = Arc::new(McpCallLane { |
| 3220 | modern: transport.is_modern(), |
| 3221 | transport: Arc::new(tokio::sync::Mutex::new(transport)), |
| 3222 | turn: Arc::new(tokio::sync::Mutex::new(())), |
| 3223 | interrupt: self.cancel_token.child_token(), |
| 3224 | broken: std::sync::atomic::AtomicBool::new(false), |
| 3225 | list_changed: std::sync::atomic::AtomicBool::new(false), |
| 3226 | }); |
| 3227 | self.transport = Box::new(LaneTransport(Arc::clone(&lane))); |
| 3228 | self.call_lane = Some(Arc::clone(&lane)); |
| 3229 | lane |
| 3230 | } |
| 3231 | |
| 3232 | fn holds_call_lane(&self, lane: &Arc<McpCallLane>) -> bool { |
| 3233 | self.call_lane |
| 3234 | .as_ref() |
| 3235 | .is_some_and(|held| Arc::ptr_eq(held, lane)) |
| 3236 | } |
| 3237 | |
| 3238 | fn call_lane_busy(&self) -> bool { |
| 3239 | self.call_lane |
| 3240 | .as_ref() |
| 3241 | .is_some_and(|lane| lane.transport.try_lock().is_err()) |
| 3242 | } |
| 3243 | |
| 3244 | async fn lease_for_call( |
| 3245 | &mut self, |
| 3246 | turn: Option<McpCallTurn>, |
| 3247 | ) -> std::result::Result<LeasedConnection, Arc<McpCallLane>> { |
| 3248 | let lane = self.call_lane(); |
| 3249 | let held = turn |
| 3250 | .filter(|turn| Arc::ptr_eq(&turn.lane, &lane)) |
| 3251 | .map(|turn| turn.guard); |
| 3252 | let turn = match held { |
| 3253 | Some(turn) => turn, |
| 3254 | None => match Arc::clone(&lane.turn).try_lock_owned() { |
| 3255 | Ok(turn) => turn, |
| 3256 | Err(_) => return Err(lane), |
| 3257 | }, |
| 3258 | }; |
| 3259 | let transport = Arc::clone(&lane.transport).lock_owned().await; |
| 3260 | let connection = McpConnection { |
| 3261 | auth_context: Arc::clone(&self.auth_context), |
| 3262 | name: self.name.clone(), |
| 3263 | transport: Box::new(LeasedTransport { |
| 3264 | transport, |
| 3265 | _turn: turn, |
| 3266 | }), |
| 3267 | tools: Vec::new(), |
| 3268 | resources: Vec::new(), |
| 3269 | resource_templates: Vec::new(), |
| 3270 | prompts: Vec::new(), |
| 3271 | skills: Vec::new(), |
| 3272 | skills_extension: self.skills_extension, |
| 3273 | request_id: AtomicU64::new(self.request_id.fetch_add(1, Ordering::SeqCst)), |
| 3274 | state: self.state, |
| 3275 | config: self.config.clone(), |
| 3276 | runtime_registration: self.runtime_registration.clone(), |
| 3277 | server_capabilities: self.server_capabilities, |
| 3278 | instructions: None, |
| 3279 | discovery_timeout: self.discovery_timeout, |
| 3280 | read_timeout_secs: self.read_timeout_secs, |
| 3281 | cancel_token: lane.interrupt.child_token(), |
| 3282 | authority_revocation_reason: Arc::clone(&self.authority_revocation_reason), |
| 3283 | authority_watch: None, |
| 3284 | catalog_generation: self.catalog_generation, |
| 3285 | catalog_revision: self.catalog_revision, |
| 3286 | catalog_fresh_until: None, |
| 3287 | catalog_stale: false, |
| 3288 | decision_key: self.decision_key, |
| 3289 | call_lane: None, |
| 3290 | }; |
| 3291 | Ok(LeasedConnection { connection, lane }) |
| 3292 | } |
| 3293 | |
| 3294 | fn next_id(&self) -> String { |
| 3295 | self.request_id.fetch_add(1, Ordering::SeqCst).to_string() |
| 3296 | } |
| 3297 | |
| 3298 | async fn send(&mut self, msg: serde_json::Value) -> Result<()> { |
| 3299 | self.send_decided(msg, None, self.discovery_timeout).await |
| 3300 | } |
| 3301 | async fn send_decided( |
| 3302 | &mut self, |
| 3303 | msg: serde_json::Value, |
| 3304 | decision: Option<&crate::core::engine::HumanDecision>, |
| 3305 | timeout: Duration, |
| 3306 | ) -> Result<()> { |
| 3307 | self.ensure_not_disconnected()?; |
| 3308 | anyhow::ensure!( |
| 3309 | self.runtime_registration_is_current(), |
| 3310 | "MCP runtime registration changed before dispatch; retry against the current config" |
| 3311 | ); |
| 3312 | let bytes = serde_json::to_vec(&msg).context("Failed to serialize MCP JSON-RPC message")?; |
| 3313 | let cancel_token = self.cancel_token.clone(); |
| 3314 | let name = self.name.clone(); |
| 3315 | let prev_state = std::mem::replace(&mut self.state, ConnectionState::Disconnected); |
| 3316 | let result = tokio::select! { |
| 3317 | biased; |
| 3318 | _ = cancel_token.cancelled() => { |
| 3319 | Err(anyhow::anyhow!("MCP connection '{name}' was cancelled")) |
| 3320 | } |
| 3321 | result = self.transport.send_decided(bytes, decision, timeout) => result, |
| 3322 | }; |
| 3323 | if result.is_ok() { |
| 3324 | // A dead write side is as fatal as a dead read side: the pool |
| 3325 | // reuses any connection whose `is_ready()` is true, so leaving |
| 3326 | // this one in `Ready` would hand the same broken transport back |
| 3327 | // on every later call instead of rebuilding it. |
| 3328 | self.state = prev_state; |
| 3329 | } |
| 3330 | result |
| 3331 | } |
| 3332 | |
| 3333 | async fn answer_server_request(&mut self, reply: &serde_json::Value) -> Result<()> { |
| 3334 | self.ensure_not_disconnected()?; |
| 3335 | let bytes = match serde_json::to_vec(reply) { |
| 3336 | Ok(bytes) => bytes, |
| 3337 | Err(err) => { |
| 3338 | tracing::debug!( |
| 3339 | target: "mcp", |
| 3340 | server = %self.name, |
| 3341 | error = %err, |
| 3342 | "could not serialize an MCP server request reply" |
| 3343 | ); |
| 3344 | return Ok(()); |
| 3345 | } |
| 3346 | }; |
| 3347 | let prev_state = std::mem::replace(&mut self.state, ConnectionState::Disconnected); |
| 3348 | let cancel_token = self.cancel_token.clone(); |
| 3349 | let name = self.name.clone(); |
| 3350 | let (result, cancelled) = tokio::select! { |
| 3351 | biased; |
| 3352 | _ = cancel_token.cancelled() => { |
| 3353 | (Err(anyhow::anyhow!("MCP connection '{name}' was cancelled")), true) |
| 3354 | } |
| 3355 | result = self.transport.send_reply(bytes) => (result, false), |
| 3356 | }; |
| 3357 | match result { |
| 3358 | Ok(()) if !cancelled => { |
| 3359 | self.state = prev_state; |
| 3360 | Ok(()) |
| 3361 | } |
| 3362 | Err(err) if !cancelled && is_mcp_server_reply_unsupported_error(&err) => { |
| 3363 | self.state = prev_state; |
| 3364 | tracing::debug!( |
| 3365 | target: "mcp", |
| 3366 | server = %self.name, |
| 3367 | error = %err, |
| 3368 | "could not answer an MCP server request" |
| 3369 | ); |
| 3370 | Ok(()) |
| 3371 | } |
| 3372 | other => { |
| 3373 | let err = match other { |
| 3374 | Ok(()) => anyhow::anyhow!("MCP connection '{}' was cancelled", self.name), |
| 3375 | Err(err) => err, |
| 3376 | }; |
| 3377 | tracing::debug!( |
| 3378 | target: "mcp", |
| 3379 | server = %self.name, |
| 3380 | error = %err, |
| 3381 | "could not answer an MCP server request" |
| 3382 | ); |
| 3383 | anyhow::bail!( |
| 3384 | "MCP connection '{}' failed while answering server request: {err:#}", |
| 3385 | self.name |
| 3386 | ); |
| 3387 | } |
| 3388 | } |
| 3389 | } |
| 3390 | |
| 3391 | /// Handshake and discovery receive: each frame wait is bounded by the read |
| 3392 | /// knob, and a server that stays silent past it is treated as dead. |
| 3393 | async fn recv(&mut self, expected_id: String) -> Result<serde_json::Value> { |
| 3394 | self.recv_reply(expected_id, Some(self.read_timeout_secs)) |
| 3395 | .await |
| 3396 | } |
| 3397 | |
| 3398 | /// The next transport frame, unless the connection is cancelled first. |
| 3399 | async fn next_frame(&mut self) -> Result<Vec<u8>> { |
| 3400 | tokio::select! { |
| 3401 | biased; |
| 3402 | _ = self.cancel_token.cancelled() => { |
| 3403 | anyhow::bail!("MCP connection '{}' was cancelled", self.name) |
| 3404 | } |
| 3405 | result = self.transport.recv() => result, |
| 3406 | } |
| 3407 | } |
| 3408 | |
| 3409 | /// Receive the reply to `expected_id`, skipping notifications and replies |
| 3410 | /// to other (abandoned) requests. `frame_timeout_secs` bounds each frame |
| 3411 | /// wait and treats its expiry as a dead connection; `None` leaves the |
| 3412 | /// whole wait to the caller's own request budget. |
| 3413 | async fn recv_reply( |
| 3414 | &mut self, |
| 3415 | expected_id: String, |
| 3416 | frame_timeout_secs: Option<u64>, |
| 3417 | ) -> Result<serde_json::Value> { |
| 3418 | loop { |
| 3419 | let frame = match frame_timeout_secs { |
| 3420 | Some(secs) => { |
| 3421 | match tokio::time::timeout(Duration::from_secs(secs), self.next_frame()).await { |
| 3422 | Ok(frame) => frame, |
| 3423 | Err(_) => { |
| 3424 | self.state = ConnectionState::Disconnected; |
| 3425 | anyhow::bail!( |
| 3426 | "Timed out waiting for MCP JSON-RPC response from server '{}' after {}s", |
| 3427 | self.name, |
| 3428 | secs |
| 3429 | ); |
| 3430 | } |
| 3431 | } |
| 3432 | } |
| 3433 | None => self.next_frame().await, |
| 3434 | }; |
| 3435 | let bytes = frame.inspect_err(|_e| { |
| 3436 | self.state = ConnectionState::Disconnected; |
| 3437 | })?; |
| 3438 | let value: serde_json::Value = match serde_json::from_slice(&bytes) { |
| 3439 | Ok(value) => value, |
| 3440 | Err(err) => { |
| 3441 | self.state = ConnectionState::Disconnected; |
| 3442 | let preview = if self.config.reviewed_plugin.is_some() { |
| 3443 | "<server details suppressed for reviewed plugin>".to_string() |
| 3444 | } else { |
| 3445 | invalid_json_preview(&bytes) |
| 3446 | }; |
| 3447 | return Err(err).with_context(|| { |
| 3448 | format!( |
| 3449 | "Invalid MCP JSON-RPC message from server '{}': {}", |
| 3450 | self.name, preview |
| 3451 | ) |
| 3452 | }); |
| 3453 | } |
| 3454 | }; |
| 3455 | |
| 3456 | // Check if this is a response with the expected id. We emit |
| 3457 | // string IDs because some MCP gateways reject numeric JSON-RPC |
| 3458 | // IDs, but accept numeric echoes for compatibility with older |
| 3459 | // servers and tests. |
| 3460 | if value.get("id").is_none() |
| 3461 | && value |
| 3462 | .get("method") |
| 3463 | .and_then(serde_json::Value::as_str) |
| 3464 | .is_some_and(is_mcp_list_changed_method) |
| 3465 | { |
| 3466 | self.catalog_stale = true; |
| 3467 | } |
| 3468 | if let Some(method) = value.get("method") { |
| 3469 | if let Some(id) = value.get("id") { |
| 3470 | let method = method.as_str().unwrap_or_default(); |
| 3471 | let reply = if method == "ping" { |
| 3472 | serde_json::json!({"jsonrpc": "2.0", "id": id, "result": {}}) |
| 3473 | } else { |
| 3474 | serde_json::json!({ |
| 3475 | "jsonrpc": "2.0", |
| 3476 | "id": id, |
| 3477 | "error": {"code": -32601, "message": format!("Method not found: {method}")} |
| 3478 | }) |
| 3479 | }; |
| 3480 | self.answer_server_request(&reply).await?; |
| 3481 | } |
| 3482 | continue; |
| 3483 | } |
| 3484 | if response_id_matches(value.get("id"), &expected_id) { |
| 3485 | // Marks the connection stale so it is rebuilt, but this is a |
| 3486 | // reply to the request, so it never qualifies for a replay. |
| 3487 | // An expired AWS *SSO session* is the server's upstream |
| 3488 | // credential, not our MCP session: rebuilding the connection |
| 3489 | // cannot renew it, and the stale-session wording would hide |
| 3490 | // the one fact the user can act on. |
| 3491 | if let Some(error) = value.get("error") |
| 3492 | && is_mcp_stale_session_body(&error.to_string()) |
| 3493 | && !error_text_looks_aws_credentials_expired(&error.to_string()) |
| 3494 | { |
| 3495 | anyhow::bail!("MCP session expired: {error}"); |
| 3496 | } |
| 3497 | return Ok(value); |
| 3498 | } |
| 3499 | // Skip notifications (no id) and responses with different ids |
| 3500 | } |
| 3501 | } |
| 3502 | |
| 3503 | /// Gracefully close the connection |
| 3504 | pub fn close(&mut self) { |
| 3505 | self.cancel_token.cancel(); |
| 3506 | self.state = ConnectionState::Disconnected; |
| 3507 | } |
| 3508 | |
| 3509 | fn runtime_registration_is_current(&self) -> bool { |
| 3510 | self.runtime_registration |
| 3511 | .as_ref() |
| 3512 | .is_none_or(|registration| { |
| 3513 | registration.read().get(&self.name).is_some_and(|current| { |
| 3514 | current.runtime_added == self.config.runtime_added |
| 3515 | && mcp_configured_server_identity( |
| 3516 | McpTimeouts::default(), |
| 3517 | &self.name, |
| 3518 | current, |
| 3519 | ) == mcp_configured_server_identity( |
| 3520 | McpTimeouts::default(), |
| 3521 | &self.name, |
| 3522 | &self.config, |
| 3523 | ) |
| 3524 | }) |
| 3525 | }) |
| 3526 | } |
| 3527 | |
| 3528 | fn catalog_authorized(&self) -> bool { |
| 3529 | self.runtime_registration_is_current() |
| 3530 | && self |
| 3531 | .config |
| 3532 | .reviewed_plugin_source() |
| 3533 | .is_none_or(ReviewedPluginMcpSource::catalog_is_current) |
| 3534 | } |
| 3535 | |
| 3536 | async fn finish_guarded_error<T>(&mut self, error: anyhow::Error) -> Result<T> { |
| 3537 | let reason = self |
| 3538 | .authority_revocation_reason |
| 3539 | .lock() |
| 3540 | .ok() |
| 3541 | .and_then(|reason| reason.clone()); |
| 3542 | if let Some(reason) = reason { |
| 3543 | self.transport.shutdown().await; |
| 3544 | self.state = ConnectionState::Disconnected; |
| 3545 | anyhow::bail!( |
| 3546 | "MCP operation on plugin server '{}' was cancelled after authority changed: {reason}", |
| 3547 | self.name |
| 3548 | ); |
| 3549 | } |
| 3550 | Err(error) |
| 3551 | } |
| 3552 | } |
| 3553 | |
| 3554 | impl Drop for McpConnection { |
| 3555 | fn drop(&mut self) { |
| 3556 | self.cancel_token.cancel(); |
| 3557 | if let Some(watch) = self.authority_watch.take() { |
| 3558 | watch.abort(); |
| 3559 | } |
| 3560 | } |
| 3561 | } |
| 3562 | |
| 3563 | struct McpCallLane { |
| 3564 | transport: Arc<tokio::sync::Mutex<Box<dyn McpTransport>>>, |
| 3565 | turn: Arc<tokio::sync::Mutex<()>>, |
| 3566 | interrupt: tokio_util::sync::CancellationToken, |
| 3567 | broken: std::sync::atomic::AtomicBool, |
| 3568 | list_changed: std::sync::atomic::AtomicBool, |
| 3569 | modern: bool, |
| 3570 | } |
| 3571 | |
| 3572 | impl McpCallLane { |
| 3573 | fn ensure_usable(&self) -> Result<()> { |
| 3574 | anyhow::ensure!( |
| 3575 | !self.broken.load(Ordering::SeqCst), |
| 3576 | "MCP connection is disconnected" |
| 3577 | ); |
| 3578 | Ok(()) |
| 3579 | } |
| 3580 | } |
| 3581 | |
| 3582 | async fn settle_call_lane(lane: Option<Arc<McpCallLane>>) { |
| 3583 | if let Some(lane) = lane { |
| 3584 | drop(lane.transport.lock().await); |
| 3585 | } |
| 3586 | } |
| 3587 | |
| 3588 | struct DetachedTransport; |
| 3589 | |
| 3590 | #[async_trait::async_trait] |
| 3591 | impl McpTransport for DetachedTransport { |
| 3592 | async fn send(&mut self, _msg: Vec<u8>) -> Result<()> { |
| 3593 | anyhow::bail!("MCP transport is detached") |
| 3594 | } |
| 3595 | |
| 3596 | async fn recv(&mut self) -> Result<Vec<u8>> { |
| 3597 | anyhow::bail!("MCP transport is detached") |
| 3598 | } |
| 3599 | } |
| 3600 | |
| 3601 | struct LaneTransport(Arc<McpCallLane>); |
| 3602 | |
| 3603 | #[async_trait::async_trait] |
| 3604 | impl McpTransport for LaneTransport { |
| 3605 | async fn send(&mut self, msg: Vec<u8>) -> Result<()> { |
| 3606 | let mut transport = self.0.transport.lock().await; |
| 3607 | self.0.ensure_usable()?; |
| 3608 | transport.send(msg).await |
| 3609 | } |
| 3610 | |
| 3611 | async fn send_decided( |
| 3612 | &mut self, |
| 3613 | msg: Vec<u8>, |
| 3614 | decision: Option<&crate::core::engine::HumanDecision>, |
| 3615 | timeout: Duration, |
| 3616 | ) -> Result<()> { |
| 3617 | let mut transport = self.0.transport.lock().await; |
| 3618 | self.0.ensure_usable()?; |
| 3619 | transport.send_decided(msg, decision, timeout).await |
| 3620 | } |
| 3621 | |
| 3622 | async fn recv(&mut self) -> Result<Vec<u8>> { |
| 3623 | let mut transport = self.0.transport.lock().await; |
| 3624 | self.0.ensure_usable()?; |
| 3625 | transport.recv().await |
| 3626 | } |
| 3627 | |
| 3628 | async fn send_reply(&mut self, msg: Vec<u8>) -> Result<()> { |
| 3629 | let mut transport = self.0.transport.lock().await; |
| 3630 | self.0.ensure_usable()?; |
| 3631 | transport.send_reply(msg).await |
| 3632 | } |
| 3633 | |
| 3634 | fn set_protocol_version(&mut self, version: &str) { |
| 3635 | if let Ok(mut transport) = self.0.transport.try_lock() { |
| 3636 | transport.set_protocol_version(version); |
| 3637 | } |
| 3638 | } |
| 3639 | |
| 3640 | fn is_modern(&self) -> bool { |
| 3641 | self.0.modern |
| 3642 | } |
| 3643 | |
| 3644 | async fn last_stderr_line(&self) -> Option<String> { |
| 3645 | let transport = self.0.transport.try_lock().ok()?; |
| 3646 | transport.last_stderr_line().await |
| 3647 | } |
| 3648 | |
| 3649 | fn probe_dead(&self) -> bool { |
| 3650 | self.0.broken.load(Ordering::SeqCst) |
| 3651 | || self |
| 3652 | .0 |
| 3653 | .transport |
| 3654 | .try_lock() |
| 3655 | .is_ok_and(|transport| transport.probe_dead()) |
| 3656 | } |
| 3657 | |
| 3658 | fn take_list_changed(&self) -> bool { |
| 3659 | let flagged = self.0.list_changed.swap(false, Ordering::SeqCst); |
| 3660 | let live = self |
| 3661 | .0 |
| 3662 | .transport |
| 3663 | .try_lock() |
| 3664 | .is_ok_and(|transport| transport.take_list_changed()); |
| 3665 | flagged || live |
| 3666 | } |
| 3667 | |
| 3668 | async fn shutdown(&mut self) { |
| 3669 | self.0.interrupt.cancel(); |
| 3670 | self.0.transport.lock().await.shutdown().await; |
| 3671 | } |
| 3672 | } |
| 3673 | |
| 3674 | struct LeasedTransport { |
| 3675 | transport: tokio::sync::OwnedMutexGuard<Box<dyn McpTransport>>, |
| 3676 | _turn: tokio::sync::OwnedMutexGuard<()>, |
| 3677 | } |
| 3678 | |
| 3679 | #[async_trait::async_trait] |
| 3680 | impl McpTransport for LeasedTransport { |
| 3681 | async fn send(&mut self, msg: Vec<u8>) -> Result<()> { |
| 3682 | self.transport.send(msg).await |
| 3683 | } |
| 3684 | |
| 3685 | async fn send_decided( |
| 3686 | &mut self, |
| 3687 | msg: Vec<u8>, |
| 3688 | decision: Option<&crate::core::engine::HumanDecision>, |
| 3689 | timeout: Duration, |
| 3690 | ) -> Result<()> { |
| 3691 | self.transport.send_decided(msg, decision, timeout).await |
| 3692 | } |
| 3693 | |
| 3694 | async fn recv(&mut self) -> Result<Vec<u8>> { |
| 3695 | self.transport.recv().await |
| 3696 | } |
| 3697 | |
| 3698 | async fn send_reply(&mut self, msg: Vec<u8>) -> Result<()> { |
| 3699 | self.transport.send_reply(msg).await |
| 3700 | } |
| 3701 | |
| 3702 | fn set_protocol_version(&mut self, version: &str) { |
| 3703 | self.transport.set_protocol_version(version); |
| 3704 | } |
| 3705 | |
| 3706 | fn is_modern(&self) -> bool { |
| 3707 | self.transport.is_modern() |
| 3708 | } |
| 3709 | |
| 3710 | async fn last_stderr_line(&self) -> Option<String> { |
| 3711 | self.transport.last_stderr_line().await |
| 3712 | } |
| 3713 | |
| 3714 | fn probe_dead(&self) -> bool { |
| 3715 | self.transport.probe_dead() |
| 3716 | } |
| 3717 | |
| 3718 | fn take_list_changed(&self) -> bool { |
| 3719 | self.transport.take_list_changed() |
| 3720 | } |
| 3721 | |
| 3722 | async fn shutdown(&mut self) { |
| 3723 | self.transport.shutdown().await; |
| 3724 | } |
| 3725 | } |
| 3726 | |
| 3727 | struct LeasedConnection { |
| 3728 | connection: McpConnection, |
| 3729 | lane: Arc<McpCallLane>, |
| 3730 | } |
| 3731 | |
| 3732 | impl Drop for LeasedConnection { |
| 3733 | fn drop(&mut self) { |
| 3734 | if self.connection.state != ConnectionState::Ready { |
| 3735 | self.lane.broken.store(true, Ordering::SeqCst); |
| 3736 | } |
| 3737 | if self.connection.catalog_stale { |
| 3738 | self.lane.list_changed.store(true, Ordering::SeqCst); |
| 3739 | } |
| 3740 | } |
| 3741 | } |
| 3742 | |
| 3743 | struct McpCallTurn { |
| 3744 | lane: Arc<McpCallLane>, |
| 3745 | guard: tokio::sync::OwnedMutexGuard<()>, |
| 3746 | } |
| 3747 | |
| 3748 | struct McpCallQueue { |
| 3749 | lane: Arc<McpCallLane>, |
| 3750 | retry: Option<Box<McpToolRoute>>, |
| 3751 | } |
| 3752 | |
| 3753 | impl McpCallQueue { |
| 3754 | async fn wait(self) -> (McpCallTurn, Option<Box<McpToolRoute>>) { |
| 3755 | let guard = Arc::clone(&self.lane.turn).lock_owned().await; |
| 3756 | ( |
| 3757 | McpCallTurn { |
| 3758 | lane: self.lane, |
| 3759 | guard, |
| 3760 | }, |
| 3761 | self.retry, |
| 3762 | ) |
| 3763 | } |
| 3764 | } |
| 3765 | |
| 3766 | enum McpLeasedAction { |
| 3767 | Tool { |
| 3768 | route: Box<McpToolRoute>, |
| 3769 | arguments: serde_json::Value, |
| 3770 | }, |
| 3771 | ReadResource { |
| 3772 | server_name: String, |
| 3773 | uri: String, |
| 3774 | skill_file: Option<McpSkillFile>, |
| 3775 | }, |
| 3776 | GetPrompt { |
| 3777 | server_name: String, |
| 3778 | prompt_name: String, |
| 3779 | arguments: serde_json::Value, |
| 3780 | }, |
| 3781 | } |
| 3782 | |
| 3783 | enum McpCallTarget { |
| 3784 | Tool(Box<McpToolRoute>), |
| 3785 | Helper { |
| 3786 | server_name: String, |
| 3787 | skill_file: Option<McpSkillFile>, |
| 3788 | }, |
| 3789 | } |
| 3790 | |
| 3791 | struct McpLeasedCall { |
| 3792 | leased: LeasedConnection, |
| 3793 | action: McpLeasedAction, |
| 3794 | timeout: u64, |
| 3795 | final_attempt: bool, |
| 3796 | } |
| 3797 | |
| 3798 | struct McpToolCallOutcome { |
| 3799 | result: Result<serde_json::Value>, |
| 3800 | lane: Arc<McpCallLane>, |
| 3801 | target: McpCallTarget, |
| 3802 | final_attempt: bool, |
| 3803 | } |
| 3804 | |
| 3805 | enum McpToolCallStep { |
| 3806 | Done(serde_json::Value), |
| 3807 | Call(Box<McpLeasedCall>), |
| 3808 | Wait(McpCallQueue), |
| 3809 | } |
| 3810 | |
| 3811 | fn mcp_call_error_retires_connection(error: &anyhow::Error) -> bool { |
| 3812 | (is_mcp_session_rejected_error(error) || is_mcp_connection_lost_error(error)) |
| 3813 | && !oauth::error_looks_auth_required(error) |
| 3814 | } |
| 3815 | |
| 3816 | impl McpLeasedCall { |
| 3817 | async fn run( |
| 3818 | self, |
| 3819 | decision: Option<&crate::core::engine::HumanDecision>, |
| 3820 | ) -> McpToolCallOutcome { |
| 3821 | let Self { |
| 3822 | mut leased, |
| 3823 | action, |
| 3824 | timeout, |
| 3825 | final_attempt, |
| 3826 | } = self; |
| 3827 | let (result, target) = match action { |
| 3828 | McpLeasedAction::Tool { route, arguments } => { |
| 3829 | let result = leased |
| 3830 | .connection |
| 3831 | .call_tool_decided(&route.tool.name, arguments, timeout, decision) |
| 3832 | .await; |
| 3833 | if !final_attempt |
| 3834 | && let Err(error) = &result |
| 3835 | && mcp_call_error_retires_connection(error) |
| 3836 | { |
| 3837 | leased.lane.broken.store(true, Ordering::SeqCst); |
| 3838 | } |
| 3839 | (result, McpCallTarget::Tool(route)) |
| 3840 | } |
| 3841 | McpLeasedAction::ReadResource { |
| 3842 | server_name, |
| 3843 | uri, |
| 3844 | skill_file, |
| 3845 | } => { |
| 3846 | let result = leased.connection.read_resource(&uri, timeout).await; |
| 3847 | ( |
| 3848 | result, |
| 3849 | McpCallTarget::Helper { |
| 3850 | server_name, |
| 3851 | skill_file, |
| 3852 | }, |
| 3853 | ) |
| 3854 | } |
| 3855 | McpLeasedAction::GetPrompt { |
| 3856 | server_name, |
| 3857 | prompt_name, |
| 3858 | arguments, |
| 3859 | } => { |
| 3860 | let result = leased |
| 3861 | .connection |
| 3862 | .get_prompt(&prompt_name, arguments, timeout) |
| 3863 | .await; |
| 3864 | ( |
| 3865 | result, |
| 3866 | McpCallTarget::Helper { |
| 3867 | server_name, |
| 3868 | skill_file: None, |
| 3869 | }, |
| 3870 | ) |
| 3871 | } |
| 3872 | }; |
| 3873 | let lane = Arc::clone(&leased.lane); |
| 3874 | drop(leased); |
| 3875 | McpToolCallOutcome { |
| 3876 | result, |
| 3877 | lane, |
| 3878 | target, |
| 3879 | final_attempt, |
| 3880 | } |
| 3881 | } |
| 3882 | } |
| 3883 | |
| 3884 | pub async fn call_tool_unlocked<A>( |
| 3885 | pool: &tokio::sync::Mutex<McpPool>, |
| 3886 | name: &str, |
| 3887 | input: serde_json::Value, |
| 3888 | rules: &[String], |
| 3889 | decision: Option<&crate::core::engine::HumanDecision>, |
| 3890 | mut admit: A, |
| 3891 | ) -> Result<serde_json::Value> |
| 3892 | where |
| 3893 | A: FnMut(&mut McpPool) -> Result<()> + Send, |
| 3894 | { |
| 3895 | let mut turn: Option<McpCallTurn> = None; |
| 3896 | let mut retry: Option<Box<McpToolRoute>> = None; |
| 3897 | let mut next: Option<McpToolCallStep> = None; |
| 3898 | loop { |
| 3899 | let step = match next.take() { |
| 3900 | Some(step) => step, |
| 3901 | None => { |
| 3902 | let mut guard = pool.lock().await; |
| 3903 | admit(&mut guard)?; |
| 3904 | if turn.is_none() && retry.is_none() { |
| 3905 | McpPool::authorize_call(&guard.disallowed_tools, name, &input)?; |
| 3906 | McpPool::authorize_call(rules, name, &input)?; |
| 3907 | if decision.is_some_and(|decision| !decision.authorizes(name, &input)) { |
| 3908 | anyhow::bail!("Human approval does not authorize this exact MCP call"); |
| 3909 | } |
| 3910 | if let Some(server) = guard.authenticate_tool_target(name) { |
| 3911 | drop(guard); |
| 3912 | let mut result = authenticate_tool_via_pool(pool, &server, |_| {}).await?; |
| 3913 | McpPool::filter_authenticate_result(&mut result, rules); |
| 3914 | return Ok(result); |
| 3915 | } |
| 3916 | } |
| 3917 | let step = guard |
| 3918 | .begin_tool_call(name, &input, rules, decision, turn.take(), retry.take()) |
| 3919 | .await?; |
| 3920 | drop(guard); |
| 3921 | step |
| 3922 | } |
| 3923 | }; |
| 3924 | let call = match step { |
| 3925 | McpToolCallStep::Done(result) => return Ok(result), |
| 3926 | McpToolCallStep::Wait(queue) => { |
| 3927 | let (held, route) = queue.wait().await; |
| 3928 | turn = Some(held); |
| 3929 | retry = route; |
| 3930 | continue; |
| 3931 | } |
| 3932 | McpToolCallStep::Call(call) => call, |
| 3933 | }; |
| 3934 | let outcome = call.run(decision).await; |
| 3935 | if let Ok(result) = outcome.result { |
| 3936 | if let McpCallTarget::Helper { |
| 3937 | skill_file: Some(file), |
| 3938 | .. |
| 3939 | } = outcome.target |
| 3940 | { |
| 3941 | verify_mcp_skill_file(&file, &result)?; |
| 3942 | } |
| 3943 | return Ok(result); |
| 3944 | } |
| 3945 | let mut guard = pool.lock().await; |
| 3946 | next = Some(guard.finish_tool_call(outcome, &input, decision).await?); |
| 3947 | } |
| 3948 | } |
| 3949 | |
| 3950 | pub(crate) async fn call_delegated_read_unlocked<A>( |
| 3951 | pool: &tokio::sync::Mutex<McpPool>, |
| 3952 | expected: &DelegatedMcpRead, |
| 3953 | name: &str, |
| 3954 | input: serde_json::Value, |
| 3955 | rules: &[String], |
| 3956 | mut admit: A, |
| 3957 | ) -> Result<serde_json::Value> |
| 3958 | where |
| 3959 | A: FnMut(&mut McpPool) -> Result<()> + Send, |
| 3960 | { |
| 3961 | let mut turn: Option<McpCallTurn> = None; |
| 3962 | loop { |
| 3963 | let mut guard = pool.lock().await; |
| 3964 | admit(&mut guard)?; |
| 3965 | let step = guard |
| 3966 | .begin_delegated_read(expected, name, &input, rules, turn.take()) |
| 3967 | .await?; |
| 3968 | drop(guard); |
| 3969 | match step { |
| 3970 | McpToolCallStep::Done(result) => return Ok(result), |
| 3971 | McpToolCallStep::Call(call) => return call.run(None).await.result, |
| 3972 | McpToolCallStep::Wait(queue) => turn = Some(queue.wait().await.0), |
| 3973 | } |
| 3974 | } |
| 3975 | } |
| 3976 | |
| 3977 | // === McpPool - Connection Pool Management === |
| 3978 | |
| 3979 | #[derive(Clone, Copy, PartialEq, Eq)] |
| 3980 | enum ConfigRefresh { |
| 3981 | IfChanged, |
| 3982 | VerifyContents, |
| 3983 | Reconnect, |
| 3984 | } |
| 3985 | |
| 3986 | #[derive(Debug, Clone)] |
| 3987 | struct McpToolRoute { |
| 3988 | server_name: String, |
| 3989 | tool: McpTool, |
| 3990 | catalog_generation: u64, |
| 3991 | catalog_revision: u64, |
| 3992 | server_identity: McpServerIdentity, |
| 3993 | runtime_added: bool, |
| 3994 | } |
| 3995 | |
| 3996 | impl McpToolRoute { |
| 3997 | fn permits(&self, conn: &McpConnection, timeouts: McpTimeouts) -> bool { |
| 3998 | conn.name == self.server_name |
| 3999 | && conn.catalog_authorized() |
| 4000 | && conn.config().runtime_added == self.runtime_added |
| 4001 | && conn.catalog_generation == self.catalog_generation |
| 4002 | && conn.config().is_tool_enabled(&self.tool.name) |
| 4003 | && conn.tools().contains(&self.tool) |
| 4004 | && mcp_configured_server_identity(timeouts, &conn.name, conn.config()) |
| 4005 | == self.server_identity |
| 4006 | } |
| 4007 | } |
| 4008 | |
| 4009 | #[derive(Clone)] |
| 4010 | pub struct DelegatedMcpRead { |
| 4011 | route: McpToolRoute, |
| 4012 | lifetime: tokio_util::sync::CancellationToken, |
| 4013 | instance: Arc<std::sync::Mutex<Option<String>>>, |
| 4014 | grant: codewhale_mcp::config::DelegatedOperation, |
| 4015 | } |
| 4016 | |
| 4017 | impl DelegatedMcpRead { |
| 4018 | pub(crate) fn current(&self) -> bool { |
| 4019 | !self.lifetime.is_cancelled() |
| 4020 | } |
| 4021 | |
| 4022 | pub(crate) fn permits_arguments(&self, input: &serde_json::Value) -> bool { |
| 4023 | self.current() && self.grant.allowed_arguments.contains(input) |
| 4024 | } |
| 4025 | } |
| 4026 | |
| 4027 | fn static_mcp_binding(server: &McpServerConfig) -> Option<String> { |
| 4028 | if server.runtime_added |
| 4029 | || server.reviewed_plugin.is_some() |
| 4030 | || server.command.is_some() |
| 4031 | || !server.env_headers.is_empty() |
| 4032 | || server.bearer_token_env_var.is_some() |
| 4033 | || server |
| 4034 | .headers |
| 4035 | .iter() |
| 4036 | .filter(|(key, _)| key.eq_ignore_ascii_case("authorization")) |
| 4037 | .count() |
| 4038 | != 1 |
| 4039 | || !server.headers.iter().any(|(key, value)| { |
| 4040 | key.eq_ignore_ascii_case("authorization") && !value.trim().is_empty() |
| 4041 | }) |
| 4042 | || server.headers.values().any(|value| value.contains("${")) |
| 4043 | { |
| 4044 | return None; |
| 4045 | } |
| 4046 | let endpoint = server.url.as_deref()?; |
| 4047 | if endpoint.contains("${") { |
| 4048 | return None; |
| 4049 | } |
| 4050 | let headers = server |
| 4051 | .headers |
| 4052 | .iter() |
| 4053 | .collect::<std::collections::BTreeMap<_, _>>(); |
| 4054 | let bytes = serde_json::to_vec(&(endpoint, headers)).ok()?; |
| 4055 | Some(codewhale_runtime::hashing::sha256_hex(bytes)) |
| 4056 | } |
| 4057 | |
| 4058 | /// Model-facing name suffix of the synthetic self-serve OAuth login tool |
| 4059 | /// (`mcp_<server>_authenticate`). Registered by [`McpPool::to_api_tools`] for |
| 4060 | /// servers whose last connect failed auth-required; executed by |
| 4061 | /// `McpPool::call_tool` through the same flow `/mcp login` uses. |
| 4062 | pub const AUTHENTICATE_TOOL_NAME: &str = "authenticate"; |
| 4063 | |
| 4064 | /// Result of [`McpPool::begin_authenticate_tool`]: either the shared token |
| 4065 | /// store already holds a usable credential (a login completed elsewhere since |
| 4066 | /// the catalog was built) or a browser login has been started and must be |
| 4067 | /// finished outside the pool lock. |
| 4068 | pub enum AuthenticateToolStart { |
| 4069 | AlreadyAuthorized, |
| 4070 | Login(Box<oauth::McpOAuthToolLogin>), |
| 4071 | } |
| 4072 | |
| 4073 | /// How the login phase of the synthetic authenticate tool concluded, fed to |
| 4074 | /// [`McpPool::finish_authenticate_tool`]. |
| 4075 | pub enum AuthenticateToolOutcome { |
| 4076 | AlreadyAuthorized, |
| 4077 | Authenticated { authorization_url: String }, |
| 4078 | } |
| 4079 | |
| 4080 | /// Execute the synthetic `mcp_<server>_authenticate` tool against a shared |
| 4081 | /// pool without holding the pool lock during the browser wait: lock to start |
| 4082 | /// the flow, release, wait for the loopback callback, then lock again to |
| 4083 | /// reconnect. `on_authorization_url` fires as soon as the URL exists — before |
| 4084 | /// the wait — so the runtime can show it to the user while the call blocks; |
| 4085 | /// the model only sees the URL in the result, after the flow has already |
| 4086 | /// finished, so this hook is the user's real path to the sign-in page when |
| 4087 | /// the browser did not open. |
| 4088 | pub async fn authenticate_tool_via_pool( |
| 4089 | pool: &tokio::sync::Mutex<McpPool>, |
| 4090 | server_name: &str, |
| 4091 | on_authorization_url: impl FnOnce(&str), |
| 4092 | ) -> Result<serde_json::Value> { |
| 4093 | let start = pool |
| 4094 | .lock() |
| 4095 | .await |
| 4096 | .begin_authenticate_tool(server_name) |
| 4097 | .await?; |
| 4098 | let outcome = match start { |
| 4099 | AuthenticateToolStart::AlreadyAuthorized => AuthenticateToolOutcome::AlreadyAuthorized, |
| 4100 | AuthenticateToolStart::Login(login) => { |
| 4101 | let authorization_url = login.authorization_url().to_string(); |
| 4102 | on_authorization_url(&authorization_url); |
| 4103 | login.finish().await?; |
| 4104 | AuthenticateToolOutcome::Authenticated { authorization_url } |
| 4105 | } |
| 4106 | }; |
| 4107 | pool.lock() |
| 4108 | .await |
| 4109 | .finish_authenticate_tool(server_name, outcome) |
| 4110 | .await |
| 4111 | } |
| 4112 | |
| 4113 | /// Pool of MCP connections for reuse |
| 4114 | pub struct McpPool { |
| 4115 | auth_context: Arc<dyn AuthContext>, |
| 4116 | backend: McpBackend, |
| 4117 | /// Immutable operator ceiling; source reloads and shared child pools cannot relax it. |
| 4118 | disallowed_tools: Vec<String>, |
| 4119 | connections: HashMap<String, McpConnection>, |
| 4120 | config: McpConfig, |
| 4121 | network_policy: Option<NetworkPolicyDecider>, |
| 4122 | /// Source paths the config was loaded from. Empty for pools constructed |
| 4123 | /// directly via `new` (tests, ad-hoc snapshots). Workspace-aware pools |
| 4124 | /// track both global and project-level MCP config paths so lazy reload sees |
| 4125 | /// either file appear or change. |
| 4126 | config_sources: Vec<PathBuf>, |
| 4127 | workspace: Option<PathBuf>, |
| 4128 | plugin_registry: Option<Arc<codewhale_plugins::PluginRegistry>>, |
| 4129 | /// 64-bit content hash of the active config (`hash_mcp_config`). Compared |
| 4130 | /// against the freshly-loaded config after an mtime change to skip |
| 4131 | /// reloading when the file was merely touched. |
| 4132 | config_hash: u64, |
| 4133 | runtime_config_hash: u64, |
| 4134 | /// Monotonic identity for the exact config/plugin catalog generation that |
| 4135 | /// advertised a callable MCP item. Resolution captures this value and the |
| 4136 | /// call boundary rejects any intervening lazy reload or dynamic mutation. |
| 4137 | catalog_generation: AtomicU64, |
| 4138 | /// Most recently observed mtime for `config_sources`. |
| 4139 | last_mtimes: Vec<Option<std::time::SystemTime>>, |
| 4140 | native_mcp_epoch: u64, |
| 4141 | /// Dynamically added MCP servers (from tool calls at runtime). |
| 4142 | /// These are not persisted to disk and live for the process lifetime. |
| 4143 | pub dynamic_servers: SharedRuntimeMcpServers, |
| 4144 | /// Servers whose most recent connect attempt failed auth-required (401 / |
| 4145 | /// OAuth not logged in). Each gets a synthetic `mcp_<server>_authenticate` |
| 4146 | /// tool in the model catalog so the model can self-serve the OAuth login |
| 4147 | /// instead of dead-ending on the error item. BTreeSet keeps catalog |
| 4148 | /// construction deterministic. |
| 4149 | needs_auth_servers: BTreeSet<String>, |
| 4150 | /// Configured OAuth callback overrides, so the synthetic self-serve |
| 4151 | /// login tool honors the same pre-registered redirect URI `/mcp login` |
| 4152 | /// uses (`mcp_oauth_callback_port` / `mcp_oauth_callback_url`). |
| 4153 | oauth_callback_port: Option<u16>, |
| 4154 | oauth_callback_url: Option<String>, |
| 4155 | /// Bumped on every `needs_auth_servers` mutation. The engine reads it |
| 4156 | /// around a tool call so a live 401 that flips the auth surface can |
| 4157 | /// flag `mcp_catalog_changed` on the failed result and the turn loop |
| 4158 | /// replaces the pool's catalog slice before the next model request. |
| 4159 | needs_auth_generation: u64, |
| 4160 | /// Per-server cooldown after a failed connect, keyed by server name. |
| 4161 | /// |
| 4162 | /// The turn loop rebuilds the tool catalog on every user message, and |
| 4163 | /// that used to re-attempt every server that was not ready — so twenty |
| 4164 | /// configured servers with four dead ones paid four connect timeouts |
| 4165 | /// before the first token, every single turn, forever. A failure now |
| 4166 | /// buys a growing cooldown; the recorded diagnosis is replayed while it |
| 4167 | /// holds, so a skipped server still reads as failing and never as |
| 4168 | /// healthy. Explicit intent (`retry_connection`, `get_or_connect`, an |
| 4169 | /// explicit reload, an edit to that server's config) ignores the cooldown. |
| 4170 | connect_backoff: HashMap<String, ConnectBackoff>, |
| 4171 | /// Servers the supervisor last saw dead. Death is reported once, on the |
| 4172 | /// transition, so status surfaces flip exactly when liveness does instead |
| 4173 | /// of re-emitting every sweep (#6187). |
| 4174 | supervised_dead: HashSet<String>, |
| 4175 | /// Servers the supervisor stopped auto-reconnecting after |
| 4176 | /// [`SUPERVISOR_PARK_AFTER_CONSECUTIVE_FAILURES`] consecutive failures. |
| 4177 | /// A stored-ready connection or an explicit `/mcp retry` clears the park. |
| 4178 | supervised_parked: HashSet<String>, |
| 4179 | /// Servers with a spawned connect in flight right now. `connect_all`, |
| 4180 | /// the session boot pass, explicit tool-selection connects, engine |
| 4181 | /// `/mcp` retries, and supervisor redials all mark names here and clear |
| 4182 | /// them on resolution, so status surfaces never have to infer |
| 4183 | /// "connecting" from "enabled but not connected yet" (#6033): an |
| 4184 | /// unconnected on-demand server (`lazy = true`) is one nobody has asked |
| 4185 | /// for, not one mid-handshake. |
| 4186 | connecting: HashSet<String>, |
| 4187 | retired: bool, |
| 4188 | } |
| 4189 | |
| 4190 | pub struct McpHandoff { |
| 4191 | auth_context: Arc<dyn AuthContext>, |
| 4192 | workspace: Option<PathBuf>, |
| 4193 | backend: McpBackend, |
| 4194 | connections: Vec<(String, McpServerIdentity, McpConnection)>, |
| 4195 | } |
| 4196 | |
| 4197 | type McpServerIdentity = (u64, Option<codewhale_config::PluginAuthority>); |
| 4198 | |
| 4199 | fn mcp_server_identity(config: &McpConfig, name: &str) -> Option<McpServerIdentity> { |
| 4200 | config |
| 4201 | .servers |
| 4202 | .get(name) |
| 4203 | .map(|server| mcp_configured_server_identity(config.timeouts, name, server)) |
| 4204 | } |
| 4205 | |
| 4206 | fn mcp_configured_server_identity( |
| 4207 | timeouts: McpTimeouts, |
| 4208 | name: &str, |
| 4209 | server: &McpServerConfig, |
| 4210 | ) -> McpServerIdentity { |
| 4211 | ( |
| 4212 | hash_mcp_config(&McpConfig { |
| 4213 | delegated_operations: Default::default(), |
| 4214 | timeouts, |
| 4215 | servers: HashMap::from([(name.to_string(), server.clone())]), |
| 4216 | }), |
| 4217 | server |
| 4218 | .reviewed_plugin_source() |
| 4219 | .map(|source| source.authority.clone()), |
| 4220 | ) |
| 4221 | } |
| 4222 | |
| 4223 | fn runtime_servers_hash(servers: &HashMap<String, McpServerConfig>) -> u64 { |
| 4224 | use std::hash::{Hash, Hasher}; |
| 4225 | let mut hasher = std::collections::hash_map::DefaultHasher::new(); |
| 4226 | hash_mcp_config(&McpConfig { |
| 4227 | delegated_operations: Default::default(), |
| 4228 | timeouts: McpTimeouts::default(), |
| 4229 | servers: servers.clone(), |
| 4230 | }) |
| 4231 | .hash(&mut hasher); |
| 4232 | let mut provenance = servers |
| 4233 | .iter() |
| 4234 | .map(|(name, config)| (name, config.runtime_added)) |
| 4235 | .collect::<Vec<_>>(); |
| 4236 | provenance.sort_by_key(|(name, _)| *name); |
| 4237 | provenance.hash(&mut hasher); |
| 4238 | hasher.finish() |
| 4239 | } |
| 4240 | |
| 4241 | /// One server's cooldown: when to try again, and what to say until then. |
| 4242 | struct ConnectBackoff { |
| 4243 | consecutive_failures: u32, |
| 4244 | retry_after: std::time::Instant, |
| 4245 | last_error: String, |
| 4246 | } |
| 4247 | |
| 4248 | /// One supervised reconnect candidate: the name, the config to redial, and |
| 4249 | /// whether this sweep newly observed the death. |
| 4250 | pub struct SupervisionDue { |
| 4251 | pub name: String, |
| 4252 | pub config: McpServerConfig, |
| 4253 | pub fresh_death: bool, |
| 4254 | } |
| 4255 | |
| 4256 | /// One supervisor sweep's plan: candidates to redial plus the transitions |
| 4257 | /// the plan phase already knows (recoveries and newly parked servers). |
| 4258 | pub struct SupervisionPlan { |
| 4259 | pub auth_context: Arc<dyn AuthContext>, |
| 4260 | pub backend: McpBackend, |
| 4261 | pub due: Vec<SupervisionDue>, |
| 4262 | pub recovered: Vec<String>, |
| 4263 | pub parked: Vec<String>, |
| 4264 | pub timeouts: McpTimeouts, |
| 4265 | pub network_policy: Option<NetworkPolicyDecider>, |
| 4266 | pub catalog_generation: u64, |
| 4267 | } |
| 4268 | |
| 4269 | /// One supervisor sweep's transitions. Death, recovery, failed attempts, and |
| 4270 | /// parking are reported on transition only, so the engine emits a snapshot |
| 4271 | /// update exactly when something changed (#6187). |
| 4272 | #[derive(Debug, Default)] |
| 4273 | pub struct McpSupervisorUpdate { |
| 4274 | /// Newly observed dead, with the reconnect failure that confirmed it. |
| 4275 | pub died: Vec<(String, String)>, |
| 4276 | /// Reconnect attempt failed for an already-dead server, with last error. |
| 4277 | pub failed: Vec<(String, String)>, |
| 4278 | /// Dead last sweep, alive now. |
| 4279 | pub recovered: Vec<String>, |
| 4280 | /// Newly parked after repeated failures; explicit `/mcp retry` resumes. |
| 4281 | pub parked: Vec<String>, |
| 4282 | /// Live catalogs an expired TTL or list-change notice rediscovered with |
| 4283 | /// a different result. |
| 4284 | pub refreshed: Vec<String>, |
| 4285 | } |
| 4286 | |
| 4287 | impl McpSupervisorUpdate { |
| 4288 | pub fn is_empty(&self) -> bool { |
| 4289 | self.died.is_empty() |
| 4290 | && self.failed.is_empty() |
| 4291 | && self.recovered.is_empty() |
| 4292 | && self.parked.is_empty() |
| 4293 | && self.refreshed.is_empty() |
| 4294 | } |
| 4295 | |
| 4296 | fn merge(&mut self, other: McpSupervisorUpdate) { |
| 4297 | self.died.extend(other.died); |
| 4298 | self.failed.extend(other.failed); |
| 4299 | self.recovered.extend(other.recovered); |
| 4300 | self.parked.extend(other.parked); |
| 4301 | self.refreshed.extend(other.refreshed); |
| 4302 | } |
| 4303 | } |
| 4304 | |
| 4305 | /// Cooldown after `failures` consecutive failed connects. |
| 4306 | /// |
| 4307 | /// Doubling from 30s to a 10-minute ceiling: long enough that a wall of dead |
| 4308 | /// servers costs nothing per turn, short enough that a server coming back |
| 4309 | /// (a laptop rejoining a network, a local server restarted) is picked up |
| 4310 | /// within one coffee break without the user touching anything. |
| 4311 | fn connect_backoff_delay(failures: u32) -> std::time::Duration { |
| 4312 | const BASE: std::time::Duration = std::time::Duration::from_secs(30); |
| 4313 | const CAP: std::time::Duration = std::time::Duration::from_secs(600); |
| 4314 | BASE.saturating_mul(1u32 << failures.saturating_sub(1).min(5)) |
| 4315 | .min(CAP) |
| 4316 | } |
| 4317 | |
| 4318 | type McpPendingConnect = (String, McpServerConfig); |
| 4319 | type McpConnectError = (String, anyhow::Error); |
| 4320 | |
| 4321 | /// The connected-app server named by an `mcp_<server>_<tool>` tool name. |
| 4322 | /// Presentation only: server names may themselves hold `_`, so this is never |
| 4323 | /// a policy input. |
| 4324 | #[must_use] |
| 4325 | pub fn connected_app_server(tool_name: &str) -> Option<&str> { |
| 4326 | let rest = tool_name.strip_prefix("mcp_")?; |
| 4327 | match rest.split_once('_') { |
| 4328 | Some((server, _)) if !server.is_empty() => Some(server), |
| 4329 | _ if !rest.is_empty() => Some(rest), |
| 4330 | _ => None, |
| 4331 | } |
| 4332 | } |
| 4333 | |
| 4334 | /// Whether an explicit tool selection (`tools_always_load`, a turn's |
| 4335 | /// `allowed_tools`) covers `server`: either an exact `mcp_<server>_<tool>` |
| 4336 | /// name or an `mcp_<prefix>*` glob whose prefix reaches the server name. |
| 4337 | /// One definition shared by the lazy boot pass and the per-turn |
| 4338 | /// explicit-connect wait so both agree on what a selection starts (#6033). |
| 4339 | pub fn tool_selection_covers_server(requested: &[String], server: &str) -> bool { |
| 4340 | let prefix = format!("mcp_{}_", server.to_ascii_lowercase()); |
| 4341 | requested.iter().any(|name| { |
| 4342 | name.starts_with(&prefix) |
| 4343 | || name |
| 4344 | .strip_suffix('*') |
| 4345 | .is_some_and(|rule| prefix.starts_with(rule)) |
| 4346 | }) |
| 4347 | } |
| 4348 | |
| 4349 | impl McpPool { |
| 4350 | /// Create a new pool with the given configuration |
| 4351 | pub fn new(config: McpConfig) -> Self { |
| 4352 | Self::new_with_auth_context(config, process_mcp_auth_context()) |
| 4353 | } |
| 4354 | |
| 4355 | pub fn new_with_auth_context(config: McpConfig, auth_context: Arc<dyn AuthContext>) -> Self { |
| 4356 | let config_hash = hash_mcp_config(&config); |
| 4357 | Self { |
| 4358 | auth_context, |
| 4359 | backend: McpBackend::default(), |
| 4360 | connections: HashMap::new(), |
| 4361 | disallowed_tools: Vec::new(), |
| 4362 | config, |
| 4363 | network_policy: None, |
| 4364 | oauth_callback_port: None, |
| 4365 | oauth_callback_url: None, |
| 4366 | config_sources: Vec::new(), |
| 4367 | workspace: None, |
| 4368 | plugin_registry: None, |
| 4369 | config_hash, |
| 4370 | runtime_config_hash: runtime_servers_hash(&HashMap::new()), |
| 4371 | catalog_generation: AtomicU64::new(1), |
| 4372 | connect_backoff: HashMap::new(), |
| 4373 | supervised_dead: HashSet::new(), |
| 4374 | supervised_parked: HashSet::new(), |
| 4375 | connecting: HashSet::new(), |
| 4376 | last_mtimes: Vec::new(), |
| 4377 | native_mcp_epoch: crate::extension_host::native_mcp::epoch(), |
| 4378 | dynamic_servers: Arc::new(RwLock::new(HashMap::new())), |
| 4379 | needs_auth_servers: BTreeSet::new(), |
| 4380 | needs_auth_generation: 0, |
| 4381 | retired: false, |
| 4382 | } |
| 4383 | } |
| 4384 | |
| 4385 | pub fn with_backend(mut self, backend: McpBackend) -> Self { |
| 4386 | self.backend = backend; |
| 4387 | self |
| 4388 | } |
| 4389 | pub fn auth_context(&self) -> Arc<dyn AuthContext> { |
| 4390 | Arc::clone(&self.auth_context) |
| 4391 | } |
| 4392 | |
| 4393 | pub fn backend(&self) -> McpBackend { |
| 4394 | self.backend |
| 4395 | } |
| 4396 | |
| 4397 | /// Create a pool from a configuration file path. |
| 4398 | #[cfg(any(test, feature = "test-support"))] |
| 4399 | pub fn from_config_path(path: &std::path::Path) -> Result<Self> { |
| 4400 | let config = load_config(path)?; |
| 4401 | let mut pool = Self::new(config); |
| 4402 | pool.config_sources = vec![path.to_path_buf()]; |
| 4403 | pool.last_mtimes = vec![mcp_config_mtime(path)]; |
| 4404 | Ok(pool) |
| 4405 | } |
| 4406 | |
| 4407 | /// Create a pool from global MCP config plus workspace-local |
| 4408 | /// `.codewhale/mcp.json`. Project servers override same-name global |
| 4409 | /// servers and default stdio `cwd` to the workspace root. |
| 4410 | #[cfg(any(test, feature = "test-support"))] |
| 4411 | pub fn from_config_path_with_workspace( |
| 4412 | path: &std::path::Path, |
| 4413 | workspace: &Path, |
| 4414 | ) -> Result<Self> { |
| 4415 | let plugins = Arc::new(codewhale_plugins::PluginRegistry::empty(workspace)); |
| 4416 | Self::from_config_path_with_workspace_and_plugins(path, workspace, plugins) |
| 4417 | } |
| 4418 | |
| 4419 | pub fn from_config_path_with_workspace_and_plugins( |
| 4420 | path: &std::path::Path, |
| 4421 | workspace: &Path, |
| 4422 | plugins: Arc<codewhale_plugins::PluginRegistry>, |
| 4423 | ) -> Result<Self> { |
| 4424 | Self::from_config_path_with_workspace_and_plugins_and_auth_context( |
| 4425 | path, |
| 4426 | workspace, |
| 4427 | plugins, |
| 4428 | process_mcp_auth_context(), |
| 4429 | ) |
| 4430 | } |
| 4431 | |
| 4432 | pub fn from_config_path_with_workspace_and_plugins_and_auth_context( |
| 4433 | path: &std::path::Path, |
| 4434 | workspace: &Path, |
| 4435 | plugins: Arc<codewhale_plugins::PluginRegistry>, |
| 4436 | auth_context: Arc<dyn AuthContext>, |
| 4437 | ) -> Result<Self> { |
| 4438 | if plugins.workspace() != workspace { |
| 4439 | anyhow::bail!("plugin registry workspace does not match MCP pool workspace"); |
| 4440 | } |
| 4441 | let config = load_config_with_workspace_and_plugins(path, workspace, plugins.as_ref())?; |
| 4442 | let workspace = checked_workspace_path(workspace)?; |
| 4443 | let mut pool = Self::new_with_auth_context(config, auth_context); |
| 4444 | pool.config_sources = vec![ |
| 4445 | path.to_path_buf(), |
| 4446 | checked_workspace_mcp_config_path(&workspace)?, |
| 4447 | ]; |
| 4448 | pool.config_sources |
| 4449 | .extend(codewhale_runtime::config::workspace_trust_config_candidate_paths()); |
| 4450 | pool.last_mtimes = pool |
| 4451 | .config_sources |
| 4452 | .iter() |
| 4453 | .map(|source| mcp_config_mtime(source)) |
| 4454 | .collect(); |
| 4455 | pool.workspace = Some(workspace); |
| 4456 | pool.plugin_registry = Some(plugins); |
| 4457 | Ok(pool) |
| 4458 | } |
| 4459 | |
| 4460 | pub fn empty_with_workspace_config_sources_and_auth_context( |
| 4461 | path: &std::path::Path, |
| 4462 | workspace: &Path, |
| 4463 | plugins: Arc<codewhale_plugins::PluginRegistry>, |
| 4464 | auth_context: Arc<dyn AuthContext>, |
| 4465 | ) -> Result<Self> { |
| 4466 | validate_mcp_config_path(path)?; |
| 4467 | if plugins.workspace() != workspace { |
| 4468 | anyhow::bail!("plugin registry workspace does not match MCP pool workspace"); |
| 4469 | } |
| 4470 | let workspace = checked_workspace_path(workspace)?; |
| 4471 | let mut pool = Self::new_with_auth_context(McpConfig::default(), auth_context); |
| 4472 | pool.config_sources = vec![ |
| 4473 | path.to_path_buf(), |
| 4474 | checked_workspace_mcp_config_path(&workspace)?, |
| 4475 | ]; |
| 4476 | pool.config_sources |
| 4477 | .extend(codewhale_runtime::config::workspace_trust_config_candidate_paths()); |
| 4478 | pool.last_mtimes = pool |
| 4479 | .config_sources |
| 4480 | .iter() |
| 4481 | .map(|source| mcp_config_mtime(source)) |
| 4482 | .collect(); |
| 4483 | pool.workspace = Some(workspace); |
| 4484 | pool.plugin_registry = Some(plugins); |
| 4485 | Ok(pool) |
| 4486 | } |
| 4487 | |
| 4488 | /// Install the session ceiling before any connection or model catalog is exposed. |
| 4489 | pub fn with_disallowed_tools(mut self, rules: Vec<String>) -> Self { |
| 4490 | self.disallowed_tools.extend(rules); |
| 4491 | self |
| 4492 | } |
| 4493 | |
| 4494 | /// Only a prefix covering the entire namespace suppresses a server. An |
| 4495 | /// individual tool denial must preserve its siblings and resource access. |
| 4496 | pub fn server_denied_by(rules: &[String], server: &str) -> bool { |
| 4497 | let namespace = format!("mcp_{server}_").to_ascii_lowercase(); |
| 4498 | rules.iter().any(|rule| { |
| 4499 | rule.to_ascii_lowercase() |
| 4500 | .strip_suffix('*') |
| 4501 | .is_some_and(|prefix| namespace.starts_with(prefix)) |
| 4502 | }) |
| 4503 | } |
| 4504 | |
| 4505 | fn server_allowed(&self, server: &str) -> bool { |
| 4506 | !self.retired && !Self::server_denied_by(&self.disallowed_tools, server) |
| 4507 | } |
| 4508 | |
| 4509 | pub fn tool_allowed(&self, name: &str) -> bool { |
| 4510 | !codewhale_execpolicy::tool_rules::tool_matches_any_rule(&self.disallowed_tools, name) |
| 4511 | } |
| 4512 | |
| 4513 | fn require_server(&self, server: &str) -> Result<()> { |
| 4514 | anyhow::ensure!( |
| 4515 | !self.retired, |
| 4516 | "MCP server {server} belongs to a newer conversation; this conversation's MCP connections are closed" |
| 4517 | ); |
| 4518 | anyhow::ensure!( |
| 4519 | self.server_allowed(server), |
| 4520 | "Failed to find MCP server: {server}" |
| 4521 | ); |
| 4522 | Ok(()) |
| 4523 | } |
| 4524 | |
| 4525 | pub fn authorize_call(rules: &[String], name: &str, input: &serde_json::Value) -> Result<()> { |
| 4526 | anyhow::ensure!( |
| 4527 | !codewhale_execpolicy::tool_rules::tool_matches_any_rule(rules, name), |
| 4528 | "Unknown MCP tool name: {name}" |
| 4529 | ); |
| 4530 | if matches!( |
| 4531 | name, |
| 4532 | "list_mcp_resources" |
| 4533 | | "list_mcp_resource_templates" |
| 4534 | | "mcp_read_resource" |
| 4535 | | "read_mcp_resource" |
| 4536 | | "mcp_get_prompt" |
| 4537 | ) && let Some(server) = input.get("server").and_then(serde_json::Value::as_str) |
| 4538 | { |
| 4539 | anyhow::ensure!( |
| 4540 | !Self::server_denied_by(rules, server), |
| 4541 | "Failed to find MCP server: {server}" |
| 4542 | ); |
| 4543 | } |
| 4544 | Ok(()) |
| 4545 | } |
| 4546 | |
| 4547 | /// Attach a per-domain network policy (#135). When set, HTTP/SSE |
| 4548 | /// transports are gated through it; STDIO transports are unaffected. |
| 4549 | pub fn with_network_policy(mut self, policy: NetworkPolicyDecider) -> Self { |
| 4550 | self.network_policy = Some(policy); |
| 4551 | self |
| 4552 | } |
| 4553 | |
| 4554 | pub fn set_network_policy(&mut self, policy: Option<NetworkPolicyDecider>) { |
| 4555 | self.network_policy = policy; |
| 4556 | } |
| 4557 | |
| 4558 | /// Configure the OAuth callback overrides (`mcp_oauth_callback_port` / |
| 4559 | /// `mcp_oauth_callback_url`) for installations whose OAuth client has a |
| 4560 | /// pre-registered redirect URI. The synthetic self-serve login tool must |
| 4561 | /// use the same overrides as `/mcp login`, or the provider rejects its |
| 4562 | /// ephemeral loopback redirect. |
| 4563 | pub fn with_oauth_callback(mut self, port: Option<u16>, url: Option<String>) -> Self { |
| 4564 | self.oauth_callback_port = port; |
| 4565 | self.oauth_callback_url = url; |
| 4566 | self |
| 4567 | } |
| 4568 | |
| 4569 | pub fn connect_timeouts(&self) -> McpTimeouts { |
| 4570 | self.config.timeouts |
| 4571 | } |
| 4572 | |
| 4573 | pub fn cloned_network_policy(&self) -> Option<NetworkPolicyDecider> { |
| 4574 | self.network_policy.clone() |
| 4575 | } |
| 4576 | |
| 4577 | pub fn runtime_server_scope(&self) -> Option<(PathBuf, SharedRuntimeMcpServers)> { |
| 4578 | self.workspace |
| 4579 | .clone() |
| 4580 | .map(|workspace| (workspace, Arc::clone(&self.dynamic_servers))) |
| 4581 | } |
| 4582 | |
| 4583 | pub fn current_catalog_generation(&self) -> u64 { |
| 4584 | self.catalog_generation |
| 4585 | .load(Ordering::SeqCst) |
| 4586 | .wrapping_add(u64::from( |
| 4587 | runtime_servers_hash(&self.dynamic_servers.read()) != self.runtime_config_hash, |
| 4588 | )) |
| 4589 | } |
| 4590 | |
| 4591 | fn sync_runtime_servers(&mut self) -> bool { |
| 4592 | let identity = runtime_servers_hash(&self.dynamic_servers.read()); |
| 4593 | if identity == self.runtime_config_hash { |
| 4594 | return false; |
| 4595 | } |
| 4596 | self.runtime_config_hash = identity; |
| 4597 | self.connections |
| 4598 | .retain(|_, connection| connection.runtime_registration_is_current()); |
| 4599 | let configured = &self.config.servers; |
| 4600 | self.connecting.clear(); |
| 4601 | self.connect_backoff |
| 4602 | .retain(|name, _| configured.contains_key(name)); |
| 4603 | self.supervised_dead |
| 4604 | .retain(|name| configured.contains_key(name)); |
| 4605 | self.supervised_parked |
| 4606 | .retain(|name| configured.contains_key(name)); |
| 4607 | let before = self.needs_auth_servers.len(); |
| 4608 | self.needs_auth_servers |
| 4609 | .retain(|name| configured.contains_key(name)); |
| 4610 | if self.needs_auth_servers.len() != before { |
| 4611 | self.needs_auth_generation = self.needs_auth_generation.wrapping_add(1); |
| 4612 | } |
| 4613 | let generation = self |
| 4614 | .catalog_generation |
| 4615 | .fetch_add(1, Ordering::SeqCst) |
| 4616 | .wrapping_add(1); |
| 4617 | for connection in self.connections.values_mut() { |
| 4618 | connection.catalog_generation = generation; |
| 4619 | } |
| 4620 | true |
| 4621 | } |
| 4622 | |
| 4623 | fn drop_connection(&mut self, server_name: &str, reason: &str) { |
| 4624 | if self.connections.remove(server_name).is_some() { |
| 4625 | tracing::debug!( |
| 4626 | target: "mcp", |
| 4627 | server = %server_name, |
| 4628 | reason = %reason, |
| 4629 | "dropped MCP connection" |
| 4630 | ); |
| 4631 | } |
| 4632 | } |
| 4633 | |
| 4634 | fn drop_all_connections(&mut self, reason: &str) { |
| 4635 | // Auth state is only known from a live connect attempt; once every |
| 4636 | // connection is dropped (explicit reload, source switch, shutdown) the |
| 4637 | // next attempt re-derives it. A reload is explicit intent, so every |
| 4638 | // cooldown lifts with it. |
| 4639 | self.connect_backoff.clear(); |
| 4640 | self.connecting.clear(); |
| 4641 | self.needs_auth_servers.clear(); |
| 4642 | self.needs_auth_generation = self.needs_auth_generation.wrapping_add(1); |
| 4643 | if self.connections.is_empty() { |
| 4644 | return; |
| 4645 | } |
| 4646 | let count = self.connections.len(); |
| 4647 | tracing::debug!( |
| 4648 | target: "mcp", |
| 4649 | count, |
| 4650 | reason = %reason, |
| 4651 | "dropping MCP connections" |
| 4652 | ); |
| 4653 | self.connections.clear(); |
| 4654 | } |
| 4655 | |
| 4656 | /// If the source config file's mtime has changed since the last check, |
| 4657 | /// re-read it and (only when the content hash also changed) drop the |
| 4658 | /// connections of servers whose own config changed or was removed, so the |
| 4659 | /// next `get_or_connect` reattaches them under the new config; unchanged |
| 4660 | /// servers keep their transports. A forced reload drops every connection. |
| 4661 | /// |
| 4662 | /// This is the lazy half of the auto-reload story for #1267: instead of a |
| 4663 | /// long-lived file watcher, the next tool invocation pays a single `stat` |
| 4664 | /// call (and only re-reads the file when the mtime moved). On networked |
| 4665 | /// or remote filesystems where mtime granularity is poor, the hash |
| 4666 | /// compare keeps us from churning connections on every check. |
| 4667 | fn reload_from_config_sources(&mut self, mode: ConfigRefresh) -> Result<bool> { |
| 4668 | let force = mode == ConfigRefresh::Reconnect; |
| 4669 | let runtime_changed = self.sync_runtime_servers(); |
| 4670 | if self.config_sources.is_empty() { |
| 4671 | if force { |
| 4672 | anyhow::bail!("MCP pool has no configuration source to reload"); |
| 4673 | } |
| 4674 | return Ok(runtime_changed); |
| 4675 | } |
| 4676 | let current_mtimes: Vec<_> = self |
| 4677 | .config_sources |
| 4678 | .iter() |
| 4679 | .map(|path| mcp_config_mtime(path)) |
| 4680 | .collect(); |
| 4681 | let native_epoch = crate::extension_host::native_mcp::epoch(); |
| 4682 | let native_changed = |
| 4683 | self.plugin_registry.is_some() && native_epoch != self.native_mcp_epoch; |
| 4684 | if mode == ConfigRefresh::IfChanged && !native_changed && current_mtimes == self.last_mtimes |
| 4685 | { |
| 4686 | return Ok(runtime_changed); |
| 4687 | } |
| 4688 | // An mtime moved, or the user explicitly requested a reload: re-read |
| 4689 | // the complete global + workspace + plugin-backed config. |
| 4690 | let primary = self |
| 4691 | .config_sources |
| 4692 | .first() |
| 4693 | .context("MCP config source list unexpectedly empty")?; |
| 4694 | let new_config = if let Some(workspace) = self.workspace.as_deref() { |
| 4695 | match self.plugin_registry.as_deref() { |
| 4696 | Some(plugins) => { |
| 4697 | load_config_with_workspace_and_plugins(primary, workspace, plugins)? |
| 4698 | } |
| 4699 | None => load_config_with_workspace(primary, workspace)?, |
| 4700 | } |
| 4701 | } else { |
| 4702 | load_config(primary)? |
| 4703 | }; |
| 4704 | let new_hash = hash_mcp_config(&new_config); |
| 4705 | // Always advance mtimes so a touched-but-unchanged file doesn't |
| 4706 | // make us re-read on every subsequent call. |
| 4707 | self.last_mtimes = current_mtimes; |
| 4708 | self.native_mcp_epoch = native_epoch; |
| 4709 | if !force && new_hash == self.config_hash { |
| 4710 | return Ok(runtime_changed); |
| 4711 | } |
| 4712 | // Every reload invalidates every advertised route. An explicit reload |
| 4713 | // also drops every live transport, because OAuth credentials may have |
| 4714 | // changed without changing the config bytes; a content change drops |
| 4715 | // only the transports of servers whose own config changed. |
| 4716 | if force { |
| 4717 | self.drop_all_connections("explicit config reload"); |
| 4718 | } else { |
| 4719 | let changed: HashSet<String> = self |
| 4720 | .config |
| 4721 | .servers |
| 4722 | .keys() |
| 4723 | .chain(new_config.servers.keys()) |
| 4724 | .filter(|name| { |
| 4725 | mcp_server_identity(&self.config, name.as_str()) |
| 4726 | != mcp_server_identity(&new_config, name.as_str()) |
| 4727 | }) |
| 4728 | .cloned() |
| 4729 | .collect(); |
| 4730 | self.connect_backoff |
| 4731 | .retain(|name, _| !changed.contains(name)); |
| 4732 | self.connecting.retain(|name| !changed.contains(name)); |
| 4733 | self.needs_auth_servers |
| 4734 | .retain(|name| !changed.contains(name)); |
| 4735 | self.needs_auth_generation = self.needs_auth_generation.wrapping_add(1); |
| 4736 | for name in &changed { |
| 4737 | self.drop_connection(name, "config reload"); |
| 4738 | } |
| 4739 | } |
| 4740 | self.config = new_config; |
| 4741 | self.config_hash = new_hash; |
| 4742 | let generation = self.catalog_generation.fetch_add(1, Ordering::SeqCst) + 1; |
| 4743 | for connection in self.connections.values_mut() { |
| 4744 | connection.catalog_generation = generation; |
| 4745 | } |
| 4746 | Ok(true) |
| 4747 | } |
| 4748 | |
| 4749 | pub async fn reload_if_config_changed(&mut self) -> Result<bool> { |
| 4750 | self.refresh_config_if_changed() |
| 4751 | } |
| 4752 | |
| 4753 | pub(crate) fn refresh_config_if_changed(&mut self) -> Result<bool> { |
| 4754 | self.reload_from_config_sources(ConfigRefresh::IfChanged) |
| 4755 | } |
| 4756 | |
| 4757 | /// Force a source re-read and drop every live connection so the next |
| 4758 | /// connect pass reattaches under the current configuration and |
| 4759 | /// credentials — without waiting for any handshake. An explicit reload is |
| 4760 | /// intent, so cooldowns lift and even a byte-identical config re-dials. |
| 4761 | /// |
| 4762 | /// An unreadable or malformed source returns `Err` **before** anything is |
| 4763 | /// dropped: a failed reload leaves the live tool pool intact. Dynamic |
| 4764 | /// in-memory servers remain registered because this mutates the existing |
| 4765 | /// pool rather than replacing it. |
| 4766 | pub fn force_reload_config_sources(&mut self) -> Result<()> { |
| 4767 | self.reload_from_config_sources(ConfigRefresh::Reconnect) |
| 4768 | .map(|_| ()) |
| 4769 | } |
| 4770 | |
| 4771 | /// Install a replacement global config source transactionally, preserving |
| 4772 | /// this shared pool (and its dynamic runtime servers) for parent and |
| 4773 | /// sub-agent holders. A malformed replacement leaves the current config, |
| 4774 | /// connections, and source paths unchanged. On success every live |
| 4775 | /// connection is dropped; the caller reattaches through its own connect |
| 4776 | /// pass so no pool lock is held across a handshake. |
| 4777 | pub fn switch_workspace_config_source( |
| 4778 | &mut self, |
| 4779 | path: &Path, |
| 4780 | workspace: &Path, |
| 4781 | plugins: Arc<codewhale_plugins::PluginRegistry>, |
| 4782 | ) -> Result<()> { |
| 4783 | validate_mcp_config_path(path)?; |
| 4784 | if plugins.workspace() != workspace { |
| 4785 | anyhow::bail!("plugin registry workspace does not match MCP pool workspace"); |
| 4786 | } |
| 4787 | let workspace = checked_workspace_path(workspace)?; |
| 4788 | let new_config = |
| 4789 | load_config_with_workspace_and_plugins(path, &workspace, plugins.as_ref())?; |
| 4790 | let mut new_sources = vec![ |
| 4791 | path.to_path_buf(), |
| 4792 | checked_workspace_mcp_config_path(&workspace)?, |
| 4793 | ]; |
| 4794 | new_sources.extend(codewhale_runtime::config::workspace_trust_config_candidate_paths()); |
| 4795 | let new_mtimes = new_sources |
| 4796 | .iter() |
| 4797 | .map(|source| mcp_config_mtime(source)) |
| 4798 | .collect(); |
| 4799 | |
| 4800 | if self.workspace.as_deref() != Some(workspace.as_path()) { |
| 4801 | self.dynamic_servers = Arc::new(RwLock::new(HashMap::new())); |
| 4802 | } |
| 4803 | self.drop_all_connections("config source switch"); |
| 4804 | self.config_hash = hash_mcp_config(&new_config); |
| 4805 | self.config = new_config; |
| 4806 | self.config_sources = new_sources; |
| 4807 | self.last_mtimes = new_mtimes; |
| 4808 | self.workspace = Some(workspace); |
| 4809 | self.plugin_registry = Some(plugins); |
| 4810 | self.catalog_generation.fetch_add(1, Ordering::SeqCst); |
| 4811 | Ok(()) |
| 4812 | } |
| 4813 | |
| 4814 | /// Refresh one retained caller snapshot through the same transactional |
| 4815 | /// source loader. A different attachment must fork; it cannot retarget a |
| 4816 | /// parent's shared pool. No transport, credential or catalog owner changes. |
| 4817 | pub fn bind_caller_plugins( |
| 4818 | &mut self, |
| 4819 | plugins: Arc<codewhale_plugins::PluginRegistry>, |
| 4820 | ) -> Result<()> { |
| 4821 | let workspace = checked_workspace_path(plugins.workspace())?; |
| 4822 | anyhow::ensure!( |
| 4823 | self.workspace |
| 4824 | .as_deref() |
| 4825 | .is_none_or(|current| current == workspace), |
| 4826 | "another MCP workspace must use its own selected pool fork" |
| 4827 | ); |
| 4828 | let next = plugins.caller_selection(); |
| 4829 | let previous = self |
| 4830 | .plugin_registry |
| 4831 | .as_deref() |
| 4832 | .and_then(codewhale_plugins::PluginRegistry::caller_selection); |
| 4833 | if next == previous && self.workspace.as_deref() == Some(workspace.as_path()) { |
| 4834 | return Ok(()); |
| 4835 | } |
| 4836 | anyhow::ensure!( |
| 4837 | previous.is_none() || next.is_some(), |
| 4838 | "MCP caller selection was omitted" |
| 4839 | ); |
| 4840 | if let (Some(previous), Some(next)) = (previous, next) { |
| 4841 | anyhow::ensure!( |
| 4842 | previous.attachment_id == next.attachment_id, |
| 4843 | "another MCP caller must use its selected pool fork" |
| 4844 | ); |
| 4845 | } |
| 4846 | crate::extension_host::validate_caller_plugins(Some(&plugins)) |
| 4847 | .map_err(anyhow::Error::msg)?; |
| 4848 | if let Some(path) = self.config_sources.first().cloned() { |
| 4849 | let workspace = plugins.workspace().to_path_buf(); |
| 4850 | self.switch_workspace_config_source(&path, &workspace, plugins)?; |
| 4851 | } else { |
| 4852 | let mut config = self.config.clone(); |
| 4853 | config |
| 4854 | .servers |
| 4855 | .retain(|_, server| server.reviewed_plugin.is_none()); |
| 4856 | let config = merge_plugin_mcp_servers(config, &plugins)?; |
| 4857 | self.drop_all_connections("caller selection changed"); |
| 4858 | self.config_hash = hash_mcp_config(&config); |
| 4859 | self.config = config; |
| 4860 | self.workspace = Some(workspace); |
| 4861 | self.plugin_registry = Some(plugins); |
| 4862 | self.catalog_generation.fetch_add(1, Ordering::SeqCst); |
| 4863 | } |
| 4864 | self.native_mcp_epoch = crate::extension_host::native_mcp::epoch(); |
| 4865 | Ok(()) |
| 4866 | } |
| 4867 | |
| 4868 | /// A selected child uses this same Rust pool factory with its own caller |
| 4869 | /// receipt. Dynamic operator servers retain their owning workspace registry. |
| 4870 | pub fn fork_for_plugins( |
| 4871 | &self, |
| 4872 | plugins: Arc<codewhale_plugins::PluginRegistry>, |
| 4873 | ) -> Result<Self> { |
| 4874 | self.fork_for_plugins_inner(plugins, false, None) |
| 4875 | } |
| 4876 | |
| 4877 | pub fn fork_isolated_for_plugins( |
| 4878 | &self, |
| 4879 | plugins: Arc<codewhale_plugins::PluginRegistry>, |
| 4880 | network_policy_override: Option<NetworkPolicyDecider>, |
| 4881 | ) -> Result<Self> { |
| 4882 | self.fork_for_plugins_inner(plugins, true, network_policy_override) |
| 4883 | } |
| 4884 | |
| 4885 | fn fork_for_plugins_inner( |
| 4886 | &self, |
| 4887 | plugins: Arc<codewhale_plugins::PluginRegistry>, |
| 4888 | isolated: bool, |
| 4889 | network_policy_override: Option<NetworkPolicyDecider>, |
| 4890 | ) -> Result<Self> { |
| 4891 | let workspace = checked_workspace_path(plugins.workspace())?; |
| 4892 | let config = match self.config_sources.first() { |
| 4893 | Some(primary) => { |
| 4894 | load_config_with_workspace_and_plugins(primary, &workspace, plugins.as_ref())? |
| 4895 | } |
| 4896 | None => { |
| 4897 | let mut config = self.config.clone(); |
| 4898 | config |
| 4899 | .servers |
| 4900 | .retain(|_, server| server.reviewed_plugin.is_none()); |
| 4901 | merge_plugin_mcp_servers(config, plugins.as_ref())? |
| 4902 | } |
| 4903 | }; |
| 4904 | let mut pool = Self::new_with_auth_context(config, Arc::clone(&self.auth_context)) |
| 4905 | .with_backend(self.backend) |
| 4906 | .with_disallowed_tools(self.disallowed_tools.clone()); |
| 4907 | pool.network_policy = network_policy_override.or_else(|| self.network_policy.clone()); |
| 4908 | pool.oauth_callback_port = self.oauth_callback_port; |
| 4909 | pool.oauth_callback_url = self.oauth_callback_url.clone(); |
| 4910 | if !isolated && self.workspace.as_deref() == Some(workspace.as_path()) { |
| 4911 | pool.dynamic_servers = Arc::clone(&self.dynamic_servers); |
| 4912 | } |
| 4913 | pool.config_sources = self.config_sources.clone(); |
| 4914 | if pool.config_sources.len() > 1 { |
| 4915 | pool.config_sources[1] = checked_workspace_mcp_config_path(&workspace)?; |
| 4916 | } |
| 4917 | pool.last_mtimes = pool |
| 4918 | .config_sources |
| 4919 | .iter() |
| 4920 | .map(|path| mcp_config_mtime(path)) |
| 4921 | .collect(); |
| 4922 | pool.workspace = Some(workspace); |
| 4923 | pool.plugin_registry = Some(plugins); |
| 4924 | Ok(pool) |
| 4925 | } |
| 4926 | |
| 4927 | #[must_use] |
| 4928 | pub fn static_server_config(&self, server_name: &str) -> Option<&McpServerConfig> { |
| 4929 | self.config.servers.get(server_name) |
| 4930 | } |
| 4931 | pub fn validate_native_caller( |
| 4932 | &self, |
| 4933 | plugins: Option<&codewhale_plugins::PluginRegistry>, |
| 4934 | ) -> Result<()> { |
| 4935 | if self.config.servers.values().any(|server| { |
| 4936 | server |
| 4937 | .reviewed_plugin_source() |
| 4938 | .is_some_and(|source| source.native_mcp.is_some()) |
| 4939 | }) { |
| 4940 | let selection = plugins.and_then(codewhale_plugins::PluginRegistry::caller_selection); |
| 4941 | anyhow::ensure!( |
| 4942 | selection |
| 4943 | == self |
| 4944 | .plugin_registry |
| 4945 | .as_deref() |
| 4946 | .and_then(codewhale_plugins::PluginRegistry::caller_selection) |
| 4947 | && self |
| 4948 | .config |
| 4949 | .servers |
| 4950 | .values() |
| 4951 | .filter_map(|server| server.reviewed_plugin_source()?.native_mcp.as_ref()) |
| 4952 | .all(|receipt| Some(receipt.selection()) == selection), |
| 4953 | "Native MCP pool belongs to another caller composition" |
| 4954 | ); |
| 4955 | crate::extension_host::validate_caller_plugins(plugins).map_err(anyhow::Error::msg)?; |
| 4956 | } |
| 4957 | Ok(()) |
| 4958 | } |
| 4959 | /// Get or create a connection to a server |
| 4960 | pub async fn get_or_connect(&mut self, server_name: &str) -> Result<&mut McpConnection> { |
| 4961 | self.get_or_connect_inner(server_name, &tokio_util::sync::CancellationToken::new()) |
| 4962 | .await |
| 4963 | } |
| 4964 | |
| 4965 | pub async fn get_or_connect_with_cancel( |
| 4966 | &mut self, |
| 4967 | server_name: &str, |
| 4968 | cancel: &tokio_util::sync::CancellationToken, |
| 4969 | ) -> Result<&mut McpConnection> { |
| 4970 | self.get_or_connect_inner(server_name, cancel).await |
| 4971 | } |
| 4972 | |
| 4973 | async fn get_or_connect_inner( |
| 4974 | &mut self, |
| 4975 | server_name: &str, |
| 4976 | cancel: &tokio_util::sync::CancellationToken, |
| 4977 | ) -> Result<&mut McpConnection> { |
| 4978 | if cancel.is_cancelled() { |
| 4979 | anyhow::bail!("MCP connection '{server_name}' was cancelled"); |
| 4980 | } |
| 4981 | // Lazy auto-reload (#1267 part 2): cheap mtime-then-hash check before |
| 4982 | // each connection lookup. Transient FS errors are logged but not |
| 4983 | // propagated so a brief hiccup can't take down the whole tool dispatch. |
| 4984 | if let Err(e) = self.reload_if_config_changed().await { |
| 4985 | tracing::warn!("MCP config reload check failed: {e:#}"); |
| 4986 | } |
| 4987 | |
| 4988 | self.require_server(server_name)?; |
| 4989 | let plugin_source = self |
| 4990 | .connections |
| 4991 | .get(server_name) |
| 4992 | .and_then(|connection| connection.config().reviewed_plugin_source().cloned()) |
| 4993 | .or_else(|| { |
| 4994 | self.config |
| 4995 | .servers |
| 4996 | .get(server_name) |
| 4997 | .and_then(|config| config.reviewed_plugin_source().cloned()) |
| 4998 | }); |
| 4999 | if let Some(source) = plugin_source |
| 5000 | && let Err(error) = source.validate_before_use(server_name, "use") |
| 5001 | { |
| 5002 | self.drop_connection(server_name, "plugin authority revoked or changed"); |
| 5003 | return Err(error); |
| 5004 | } |
| 5005 | |
| 5006 | // Authority was just validated above for this same source; checking |
| 5007 | // it again here would re-hash the bundle within one dispatch (#6209). |
| 5008 | let is_ready = self |
| 5009 | .connections |
| 5010 | .get(server_name) |
| 5011 | .map(McpConnection::is_transport_ready) |
| 5012 | .unwrap_or(false); |
| 5013 | if is_ready { |
| 5014 | return self |
| 5015 | .connections |
| 5016 | .get_mut(server_name) |
| 5017 | .ok_or_else(|| anyhow::anyhow!("MCP connection disappeared for {server_name}")); |
| 5018 | } |
| 5019 | |
| 5020 | // Take (don't drop) the stale connection: if the reconnect attempt |
| 5021 | // below fails, the previous connection is restored so its last-good |
| 5022 | // tool catalog stays model-visible during the outage instead of |
| 5023 | // disappearing with a dropped transport (#6187). |
| 5024 | let previous_connection = self.connections.remove(server_name); |
| 5025 | if previous_connection.is_some() { |
| 5026 | tracing::debug!( |
| 5027 | target: "mcp", |
| 5028 | server = %server_name, |
| 5029 | reason = "reconnect", |
| 5030 | "detached MCP connection for reconnect" |
| 5031 | ); |
| 5032 | } |
| 5033 | |
| 5034 | // Check static config first, then dynamic servers |
| 5035 | let server_config = self |
| 5036 | .config |
| 5037 | .servers |
| 5038 | .get(server_name) |
| 5039 | .cloned() |
| 5040 | .or_else(|| self.dynamic_servers.read().get(server_name).cloned()) |
| 5041 | .ok_or_else(|| anyhow::anyhow!("Failed to find MCP server: {server_name}"))?; |
| 5042 | |
| 5043 | if !server_config.is_enabled() { |
| 5044 | anyhow::bail!("Failed to connect MCP server '{server_name}': server is disabled"); |
| 5045 | } |
| 5046 | |
| 5047 | let mut connection = match McpConnection::connect_with_backend_auth_and_cancel( |
| 5048 | server_name.to_string(), |
| 5049 | server_config, |
| 5050 | &self.config.timeouts, |
| 5051 | self.network_policy.as_ref(), |
| 5052 | self.backend, |
| 5053 | Arc::clone(&self.auth_context), |
| 5054 | cancel.clone(), |
| 5055 | ) |
| 5056 | .await |
| 5057 | { |
| 5058 | Ok(connection) => connection, |
| 5059 | Err(error) => { |
| 5060 | self.note_connect_failure(server_name, &error); |
| 5061 | if let Some(previous) = previous_connection { |
| 5062 | tracing::debug!( |
| 5063 | target: "mcp", |
| 5064 | server = %server_name, |
| 5065 | "reconnect failed; restored the previous MCP connection and its last-good catalog" |
| 5066 | ); |
| 5067 | self.connections.insert(server_name.to_string(), previous); |
| 5068 | } |
| 5069 | return Err(error); |
| 5070 | } |
| 5071 | }; |
| 5072 | connection.catalog_generation = self.current_catalog_generation(); |
| 5073 | |
| 5074 | self.store_ready_connection(server_name.to_string(), connection)?; |
| 5075 | self.connections |
| 5076 | .get_mut(server_name) |
| 5077 | .ok_or_else(|| anyhow::anyhow!("Failed to store MCP connection for {server_name}")) |
| 5078 | } |
| 5079 | |
| 5080 | /// Retry exactly one server against the configuration already owned by |
| 5081 | /// this pool. |
| 5082 | /// |
| 5083 | /// Unlike normal lazy tool dispatch, an explicit row retry must not notice |
| 5084 | /// a concurrent config mtime and invalidate healthy siblings. Config edits |
| 5085 | /// remain owned by the explicit reload path; this operation only replaces |
| 5086 | /// the named transport. |
| 5087 | pub async fn retry_connection(&mut self, server_name: &str) -> Result<&mut McpConnection> { |
| 5088 | let server_config = self.retry_server_config(server_name)?; |
| 5089 | let mut connection = match McpConnection::connect_with_backend_and_auth_context( |
| 5090 | server_name.to_string(), |
| 5091 | server_config, |
| 5092 | &self.config.timeouts, |
| 5093 | self.network_policy.as_ref(), |
| 5094 | self.backend, |
| 5095 | Arc::clone(&self.auth_context), |
| 5096 | ) |
| 5097 | .await |
| 5098 | { |
| 5099 | Ok(connection) => connection, |
| 5100 | Err(error) => { |
| 5101 | self.note_connect_failure(server_name, &error); |
| 5102 | return Err(error); |
| 5103 | } |
| 5104 | }; |
| 5105 | connection.catalog_generation = self.current_catalog_generation(); |
| 5106 | self.store_ready_connection(server_name.to_string(), connection)?; |
| 5107 | self.connections |
| 5108 | .get_mut(server_name) |
| 5109 | .ok_or_else(|| anyhow::anyhow!("Failed to store MCP connection for {server_name}")) |
| 5110 | } |
| 5111 | |
| 5112 | pub fn take_retry_connect(&mut self, server_name: &str) -> Result<McpPendingConnect> { |
| 5113 | let server_config = self.retry_server_config(server_name)?; |
| 5114 | self.connecting.insert(server_name.to_string()); |
| 5115 | Ok((server_name.to_string(), server_config)) |
| 5116 | } |
| 5117 | |
| 5118 | fn retry_server_config(&mut self, server_name: &str) -> Result<McpServerConfig> { |
| 5119 | self.sync_runtime_servers(); |
| 5120 | self.require_server(server_name)?; |
| 5121 | // A person asked for this one by name. Clear the cooldown so the |
| 5122 | // attempt happens now and, if it fails again, the ladder restarts |
| 5123 | // from the short end rather than from wherever it had climbed to. |
| 5124 | // Explicit intent restarts supervision: the cooldown, the dead mark, |
| 5125 | // and any park all clear, so the supervisor resumes watching whatever |
| 5126 | // this retry stores — or stays quiet while the server is connectionless. |
| 5127 | self.connect_backoff.remove(server_name); |
| 5128 | self.supervised_dead.remove(server_name); |
| 5129 | self.supervised_parked.remove(server_name); |
| 5130 | let plugin_source = self |
| 5131 | .connections |
| 5132 | .get(server_name) |
| 5133 | .and_then(|connection| connection.config().reviewed_plugin_source().cloned()) |
| 5134 | .or_else(|| { |
| 5135 | self.config |
| 5136 | .servers |
| 5137 | .get(server_name) |
| 5138 | .and_then(|config| config.reviewed_plugin_source().cloned()) |
| 5139 | }); |
| 5140 | if let Some(source) = plugin_source |
| 5141 | && let Err(error) = source.validate_before_use(server_name, "use") |
| 5142 | { |
| 5143 | self.drop_connection(server_name, "plugin authority revoked or changed"); |
| 5144 | return Err(error); |
| 5145 | } |
| 5146 | |
| 5147 | self.drop_connection(server_name, "retry"); |
| 5148 | |
| 5149 | let server_config = self |
| 5150 | .config |
| 5151 | .servers |
| 5152 | .get(server_name) |
| 5153 | .cloned() |
| 5154 | .or_else(|| self.dynamic_servers.read().get(server_name).cloned()) |
| 5155 | .ok_or_else(|| anyhow::anyhow!("Failed to find MCP server: {server_name}"))?; |
| 5156 | |
| 5157 | if !server_config.is_enabled() { |
| 5158 | anyhow::bail!("Failed to connect MCP server '{server_name}': server is disabled"); |
| 5159 | } |
| 5160 | Ok(server_config) |
| 5161 | } |
| 5162 | |
| 5163 | pub fn store_ready_connection( |
| 5164 | &mut self, |
| 5165 | name: String, |
| 5166 | mut connection: McpConnection, |
| 5167 | ) -> Result<()> { |
| 5168 | self.sync_runtime_servers(); |
| 5169 | self.require_server(&name)?; |
| 5170 | anyhow::ensure!( |
| 5171 | Arc::ptr_eq(&connection.auth_context, &self.auth_context), |
| 5172 | "MCP connection belongs to another credential authority" |
| 5173 | ); |
| 5174 | anyhow::ensure!( |
| 5175 | connection.catalog_generation == self.current_catalog_generation(), |
| 5176 | "MCP configuration changed while connecting {name}; retry against the current config" |
| 5177 | ); |
| 5178 | let current = self |
| 5179 | .server_config(&name) |
| 5180 | .ok_or_else(|| anyhow::anyhow!("MCP server {name} was removed while connecting"))?; |
| 5181 | anyhow::ensure!( |
| 5182 | current.runtime_added == connection.config.runtime_added |
| 5183 | && mcp_configured_server_identity(self.config.timeouts, &name, ¤t) |
| 5184 | == mcp_configured_server_identity( |
| 5185 | self.config.timeouts, |
| 5186 | &name, |
| 5187 | &connection.config |
| 5188 | ), |
| 5189 | "MCP configuration changed while connecting {name}; retry against the current config" |
| 5190 | ); |
| 5191 | connection.runtime_registration = |
| 5192 | (!self.config.servers.contains_key(&name)).then(|| Arc::clone(&self.dynamic_servers)); |
| 5193 | if let Some(source) = connection.config().reviewed_plugin_source() { |
| 5194 | source.validate_before_use(&name, "use")?; |
| 5195 | } |
| 5196 | // A successful connect settles the auth question for this server, |
| 5197 | // and the cooldown with it — plus any supervisor dead mark or park, |
| 5198 | // since a stored-ready connection is alive by construction. |
| 5199 | self.connecting.remove(&name); |
| 5200 | self.connect_backoff.remove(&name); |
| 5201 | self.supervised_dead.remove(&name); |
| 5202 | self.supervised_parked.remove(&name); |
| 5203 | if self.needs_auth_servers.remove(&name) { |
| 5204 | self.needs_auth_generation = self.needs_auth_generation.wrapping_add(1); |
| 5205 | } |
| 5206 | self.connections.insert(name, connection); |
| 5207 | Ok(()) |
| 5208 | } |
| 5209 | |
| 5210 | pub fn retire_for_handoff(&mut self) -> McpHandoff { |
| 5211 | self.retired = true; |
| 5212 | let connections = std::mem::take(&mut self.connections) |
| 5213 | .into_iter() |
| 5214 | .filter_map(|(name, connection)| { |
| 5215 | let identity = mcp_server_identity(&self.config, &name)?; |
| 5216 | (identity.1.is_none() |
| 5217 | && connection.config().url.is_none() |
| 5218 | && !connection |
| 5219 | .config() |
| 5220 | .env |
| 5221 | .values() |
| 5222 | .any(|value| value.contains("${")) |
| 5223 | && connection.is_transport_ready()) |
| 5224 | .then_some((name, identity, connection)) |
| 5225 | }) |
| 5226 | .collect(); |
| 5227 | McpHandoff { |
| 5228 | auth_context: Arc::clone(&self.auth_context), |
| 5229 | workspace: self.workspace.clone(), |
| 5230 | backend: self.backend, |
| 5231 | connections, |
| 5232 | } |
| 5233 | } |
| 5234 | |
| 5235 | pub fn adopt_handoff(&mut self, handoff: McpHandoff) -> usize { |
| 5236 | if self.retired |
| 5237 | || handoff.workspace != self.workspace |
| 5238 | || handoff.backend != self.backend |
| 5239 | || !Arc::ptr_eq(&handoff.auth_context, &self.auth_context) |
| 5240 | { |
| 5241 | return 0; |
| 5242 | } |
| 5243 | let generation = self.current_catalog_generation(); |
| 5244 | let mut adopted = 0; |
| 5245 | for (name, identity, mut connection) in handoff.connections { |
| 5246 | if mcp_server_identity(&self.config, &name).as_ref() != Some(&identity) |
| 5247 | || !connection.is_transport_ready() |
| 5248 | { |
| 5249 | continue; |
| 5250 | } |
| 5251 | connection.catalog_generation = generation; |
| 5252 | if self.store_ready_connection(name, connection).is_ok() { |
| 5253 | adopted += 1; |
| 5254 | } |
| 5255 | } |
| 5256 | adopted |
| 5257 | } |
| 5258 | |
| 5259 | /// Record a connect failure's auth classification. When the failure looks |
| 5260 | /// like a missing/expired OAuth login, the next model catalog offers the |
| 5261 | /// synthetic `mcp_<server>_authenticate` tool so the model can self-serve |
| 5262 | /// the login instead of dead-ending on the error item. A non-auth |
| 5263 | /// failure replaces the verdict — the state is "the most recent connect |
| 5264 | /// failed auth-required", not "some connect once did". |
| 5265 | pub fn note_connect_failure(&mut self, name: &str, error: &anyhow::Error) { |
| 5266 | if self.sync_runtime_servers() { |
| 5267 | return; |
| 5268 | } |
| 5269 | self.connecting.remove(name); |
| 5270 | if !self.server_allowed(name) { |
| 5271 | return; |
| 5272 | } |
| 5273 | let entry = self |
| 5274 | .connect_backoff |
| 5275 | .entry(name.to_string()) |
| 5276 | .or_insert(ConnectBackoff { |
| 5277 | consecutive_failures: 0, |
| 5278 | retry_after: std::time::Instant::now(), |
| 5279 | last_error: String::new(), |
| 5280 | }); |
| 5281 | entry.consecutive_failures = entry.consecutive_failures.saturating_add(1); |
| 5282 | entry.retry_after = |
| 5283 | std::time::Instant::now() + connect_backoff_delay(entry.consecutive_failures); |
| 5284 | entry.last_error = format_mcp_error_for_display(error); |
| 5285 | let changed = if self.error_needs_oauth_login(name, error) { |
| 5286 | self.needs_auth_servers.insert(name.to_string()) |
| 5287 | } else { |
| 5288 | self.needs_auth_servers.remove(name) |
| 5289 | }; |
| 5290 | if changed { |
| 5291 | self.needs_auth_generation = self.needs_auth_generation.wrapping_add(1); |
| 5292 | } |
| 5293 | } |
| 5294 | |
| 5295 | /// Whether `error` from `name` is an OAuth-style auth-required failure. |
| 5296 | /// An expired AWS login on a server that is not OAuth-capable often says |
| 5297 | /// `401`/`Unauthorized` too, but `/mcp login` and the synthetic |
| 5298 | /// authenticate tool cannot renew it: it is excluded here so the |
| 5299 | /// needs-auth set (and every surface derived from it) never misroutes it. |
| 5300 | fn error_needs_oauth_login(&self, name: &str, error: &anyhow::Error) -> bool { |
| 5301 | if !oauth::error_looks_auth_required(error) { |
| 5302 | return false; |
| 5303 | } |
| 5304 | let oauth_capable = self |
| 5305 | .server_config(name) |
| 5306 | .is_some_and(|config| mcp_server_oauth_capable(&config)); |
| 5307 | !mcp_error_is_aws_login(&format!("{error:#}"), oauth_capable) |
| 5308 | } |
| 5309 | |
| 5310 | /// Current needs-auth surface generation. Compare across a tool call to |
| 5311 | /// learn whether the call flipped a server into or out of the |
| 5312 | /// `◆ auth required` state (a live 401, or a login that landed). |
| 5313 | #[must_use] |
| 5314 | pub fn needs_auth_generation(&self) -> u64 { |
| 5315 | self.needs_auth_generation |
| 5316 | } |
| 5317 | |
| 5318 | /// Whether the server's most recent connect attempt failed auth-required |
| 5319 | /// (the typed `◆ auth required` state). Cleared by a successful connect, |
| 5320 | /// by any full connection drop (explicit reload, source switch, shutdown) |
| 5321 | /// and by an edit to that server's config. |
| 5322 | #[must_use] |
| 5323 | pub fn server_needs_auth(&self, name: &str) -> bool { |
| 5324 | self.server_allowed(name) && self.needs_auth_servers.contains(name) |
| 5325 | } |
| 5326 | |
| 5327 | pub fn has_connection_backoff( |
| 5328 | &self, |
| 5329 | name: &str, |
| 5330 | timeouts: McpTimeouts, |
| 5331 | server: &McpServerConfig, |
| 5332 | ) -> Option<bool> { |
| 5333 | let current = self.config.servers.get(name)?; |
| 5334 | if !self.server_allowed(name) |
| 5335 | || !server.is_enabled() |
| 5336 | || !current.is_enabled() |
| 5337 | || self.connecting.contains(name) |
| 5338 | || self |
| 5339 | .connections |
| 5340 | .get(name) |
| 5341 | .is_some_and(McpConnection::is_transport_ready) |
| 5342 | || mcp_configured_server_identity(self.config.timeouts, name, current) |
| 5343 | != mcp_configured_server_identity(timeouts, name, server) |
| 5344 | { |
| 5345 | return None; |
| 5346 | } |
| 5347 | Some(self.connect_backoff.contains_key(name)) |
| 5348 | } |
| 5349 | |
| 5350 | #[must_use] |
| 5351 | pub fn last_connect_error( |
| 5352 | &self, |
| 5353 | name: &str, |
| 5354 | timeouts: McpTimeouts, |
| 5355 | server: &McpServerConfig, |
| 5356 | ) -> Option<&str> { |
| 5357 | if self.has_connection_backoff(name, timeouts, server) != Some(true) { |
| 5358 | return None; |
| 5359 | } |
| 5360 | let current = self.config.servers.get(name)?; |
| 5361 | if current.runtime_added != server.runtime_added |
| 5362 | || (current.reviewed_plugin.is_some() && current.reviewed_plugin_source().is_none()) |
| 5363 | || (server.reviewed_plugin.is_some() && server.reviewed_plugin_source().is_none()) |
| 5364 | || server |
| 5365 | .reviewed_plugin_source() |
| 5366 | .is_some_and(|source| source.validate_before_use(name, "inspect").is_err()) |
| 5367 | || runtime_servers_hash(&self.dynamic_servers.read()) != self.runtime_config_hash |
| 5368 | { |
| 5369 | return None; |
| 5370 | } |
| 5371 | let error = self.connect_backoff.get(name)?.last_error.as_str(); |
| 5372 | (!error.is_empty()).then_some(error) |
| 5373 | } |
| 5374 | |
| 5375 | /// The needs-auth server that owns a model tool name (`mcp_<server>_…`), |
| 5376 | /// if any: the server the model is trying to reach with a real tool name |
| 5377 | /// from a catalog built before its login lapsed. Longest configured name |
| 5378 | /// wins so `mcp_a_b_tool` routes to server `a_b` over `a`. |
| 5379 | fn needs_auth_server_for_tool_name(&self, prefixed_name: &str) -> Option<String> { |
| 5380 | let rest = prefixed_name.strip_prefix("mcp_")?; |
| 5381 | self.needs_auth_servers |
| 5382 | .iter() |
| 5383 | .filter(|server| { |
| 5384 | self.server_allowed(server) |
| 5385 | && self.tool_allowed(prefixed_name) |
| 5386 | && rest |
| 5387 | .strip_prefix(server.as_str()) |
| 5388 | .is_some_and(|suffix| suffix.starts_with('_')) |
| 5389 | }) |
| 5390 | .max_by_key(|server| server.len()) |
| 5391 | .cloned() |
| 5392 | } |
| 5393 | |
| 5394 | /// Peak concurrent spawn+handshake attempts. Uncapped, a config full of |
| 5395 | /// `npx` servers would start one node runtime per server at the same |
| 5396 | /// instant — a memory spike on low-end machines the sequential loop never |
| 5397 | /// produced. Eight keeps wall-clock wins (the connect timeout dominates) |
| 5398 | /// while bounding peak memory. |
| 5399 | const CONNECT_CONCURRENCY: usize = 8; |
| 5400 | |
| 5401 | /// Consecutive failed reconnects after which the supervisor parks a |
| 5402 | /// server instead of redialing it. The cooldown ladder already spaces |
| 5403 | /// attempts, but a server that never answers (wrong binary, dead port) |
| 5404 | /// should not burn a spawn+handshake every sweep forever. A stored-ready |
| 5405 | /// connection or an explicit `/mcp retry` clears the park — and every |
| 5406 | /// success resets the count, so an occasionally-crashing server keeps |
| 5407 | /// recovering instead of parking. |
| 5408 | const SUPERVISOR_PARK_AFTER_CONSECUTIVE_FAILURES: u32 = 5; |
| 5409 | |
| 5410 | /// Supervisor sweep cadence. Death is noticed within one tick; an idle |
| 5411 | /// tick costs one pool lock plus a `try_wait` per stdio child. |
| 5412 | const SUPERVISOR_TICK: std::time::Duration = std::time::Duration::from_secs(5); |
| 5413 | |
| 5414 | /// One supervisor sweep's reconnect candidates, computed under a brief |
| 5415 | /// pool lock. Handshakes run outside the lock via |
| 5416 | /// [`Self::spawn_pending_connects`], so a wedged server never blocks a |
| 5417 | /// live turn's pool access while it burns its connect timeout. |
| 5418 | pub fn plan_supervision(&mut self) -> SupervisionPlan { |
| 5419 | self.sync_runtime_servers(); |
| 5420 | let dynamic = self.dynamic_servers.read(); |
| 5421 | let candidates: Vec<(String, McpServerConfig)> = self |
| 5422 | .config |
| 5423 | .servers |
| 5424 | .iter() |
| 5425 | .filter(|(name, server)| server.is_enabled() && self.server_allowed(name)) |
| 5426 | .map(|(name, server)| (name.clone(), server.clone())) |
| 5427 | .chain( |
| 5428 | dynamic |
| 5429 | .iter() |
| 5430 | .filter(|(name, server)| { |
| 5431 | server.is_enabled() |
| 5432 | && self.server_allowed(name) |
| 5433 | && !self.config.servers.contains_key(*name) |
| 5434 | }) |
| 5435 | .map(|(name, server)| (name.clone(), server.clone())), |
| 5436 | ) |
| 5437 | .collect(); |
| 5438 | drop(dynamic); |
| 5439 | let watched: HashSet<String> = candidates.iter().map(|(name, _)| name.clone()).collect(); |
| 5440 | // Removed or disabled servers leave supervision without an event. |
| 5441 | self.supervised_dead |
| 5442 | .retain(|name| watched.contains(name) && self.connections.contains_key(name)); |
| 5443 | self.supervised_parked.retain(|name| watched.contains(name)); |
| 5444 | let mut due = Vec::new(); |
| 5445 | let mut recovered = Vec::new(); |
| 5446 | let mut parked = Vec::new(); |
| 5447 | let now = std::time::Instant::now(); |
| 5448 | for (name, config) in candidates { |
| 5449 | let had_connection = self.connections.contains_key(&name); |
| 5450 | if !had_connection |
| 5451 | && (config.lazy |
| 5452 | || self.config.servers.contains_key(&name) |
| 5453 | || !self.dynamic_servers.read().contains_key(&name)) |
| 5454 | { |
| 5455 | continue; |
| 5456 | } |
| 5457 | if self |
| 5458 | .connections |
| 5459 | .get(&name) |
| 5460 | .is_some_and(McpConnection::is_transport_ready) |
| 5461 | { |
| 5462 | if self.supervised_dead.remove(&name) { |
| 5463 | self.supervised_parked.remove(&name); |
| 5464 | recovered.push(name); |
| 5465 | } |
| 5466 | continue; |
| 5467 | } |
| 5468 | // A login-pending server cannot be fixed by redialing; the auth |
| 5469 | // surface owns it. It stays out of the dead set so recovery via |
| 5470 | // login reports nothing stale. |
| 5471 | if self.needs_auth_servers.contains(&name) { |
| 5472 | continue; |
| 5473 | } |
| 5474 | let fresh_death = had_connection && self.supervised_dead.insert(name.clone()); |
| 5475 | if self.connecting.contains(&name) { |
| 5476 | continue; |
| 5477 | } |
| 5478 | if let Some(backoff) = self.connect_backoff.get(&name) { |
| 5479 | if backoff.consecutive_failures >= Self::SUPERVISOR_PARK_AFTER_CONSECUTIVE_FAILURES |
| 5480 | { |
| 5481 | if self.supervised_parked.insert(name.clone()) { |
| 5482 | parked.push(name); |
| 5483 | } |
| 5484 | continue; |
| 5485 | } |
| 5486 | if now < backoff.retry_after { |
| 5487 | continue; |
| 5488 | } |
| 5489 | } |
| 5490 | self.connecting.insert(name.clone()); |
| 5491 | due.push(SupervisionDue { |
| 5492 | name, |
| 5493 | config, |
| 5494 | fresh_death, |
| 5495 | }); |
| 5496 | } |
| 5497 | SupervisionPlan { |
| 5498 | auth_context: Arc::clone(&self.auth_context), |
| 5499 | backend: self.backend, |
| 5500 | due, |
| 5501 | recovered, |
| 5502 | parked, |
| 5503 | timeouts: self.config.timeouts, |
| 5504 | network_policy: self.network_policy.clone(), |
| 5505 | catalog_generation: self.current_catalog_generation(), |
| 5506 | } |
| 5507 | } |
| 5508 | |
| 5509 | /// Rediscover every ready catalog whose TTL expired or whose server |
| 5510 | /// announced a list change. A failed rediscovery retires the connection |
| 5511 | /// so ordinary supervision redials it instead of serving stale entries. |
| 5512 | pub async fn revalidate_catalogs(&mut self) -> Vec<String> { |
| 5513 | let stale: Vec<String> = self |
| 5514 | .connections |
| 5515 | .iter_mut() |
| 5516 | .filter(|(_, connection)| { |
| 5517 | connection.is_transport_ready() && !connection.call_lane_busy() |
| 5518 | }) |
| 5519 | .filter_map(|(name, connection)| { |
| 5520 | connection |
| 5521 | .catalog_needs_revalidation() |
| 5522 | .then(|| name.clone()) |
| 5523 | }) |
| 5524 | .collect(); |
| 5525 | let mut refreshed = Vec::new(); |
| 5526 | for name in stale { |
| 5527 | let Some(connection) = self.connections.get_mut(&name) else { |
| 5528 | continue; |
| 5529 | }; |
| 5530 | match connection.revalidate_catalog().await { |
| 5531 | Ok(true) => refreshed.push(name), |
| 5532 | Ok(false) => {} |
| 5533 | Err(error) => { |
| 5534 | tracing::debug!(target: "mcp", server = name, %error, "MCP catalog revalidation failed"); |
| 5535 | connection.state = ConnectionState::Disconnected; |
| 5536 | } |
| 5537 | } |
| 5538 | } |
| 5539 | refreshed |
| 5540 | } |
| 5541 | |
| 5542 | /// Resolve one supervised reconnect attempt. Success stores the live |
| 5543 | /// connection (which clears the backoff, the dead mark, and any park); |
| 5544 | /// failure records the backoff and reports the death or the repeated |
| 5545 | /// failure with the diagnosis, parking on the threshold crossing. |
| 5546 | pub fn resolve_supervision_attempt( |
| 5547 | &mut self, |
| 5548 | name: &str, |
| 5549 | fresh_death: bool, |
| 5550 | result: Result<McpConnection, anyhow::Error>, |
| 5551 | ) -> McpSupervisorUpdate { |
| 5552 | let mut update = McpSupervisorUpdate::default(); |
| 5553 | if self.sync_runtime_servers() { |
| 5554 | return update; |
| 5555 | } |
| 5556 | if self |
| 5557 | .connections |
| 5558 | .get(name) |
| 5559 | .is_some_and(McpConnection::is_ready) |
| 5560 | { |
| 5561 | if !fresh_death { |
| 5562 | update.recovered.push(name.to_string()); |
| 5563 | } |
| 5564 | return update; |
| 5565 | } |
| 5566 | let stored = |
| 5567 | result.and_then(|connection| self.store_ready_connection(name.to_string(), connection)); |
| 5568 | match stored { |
| 5569 | Ok(()) => { |
| 5570 | if !fresh_death { |
| 5571 | update.recovered.push(name.to_string()); |
| 5572 | } |
| 5573 | } |
| 5574 | Err(error) => { |
| 5575 | self.note_connect_failure(name, &error); |
| 5576 | let last_error = self |
| 5577 | .connect_backoff |
| 5578 | .get(name) |
| 5579 | .map(|backoff| backoff.last_error.clone()) |
| 5580 | .unwrap_or_else(|| format!("{error:#}")); |
| 5581 | if fresh_death { |
| 5582 | update.died.push((name.to_string(), last_error)); |
| 5583 | } else { |
| 5584 | update.failed.push((name.to_string(), last_error)); |
| 5585 | } |
| 5586 | if self.connect_backoff.get(name).is_some_and(|backoff| { |
| 5587 | backoff.consecutive_failures >= Self::SUPERVISOR_PARK_AFTER_CONSECUTIVE_FAILURES |
| 5588 | }) && self.supervised_parked.insert(name.to_string()) |
| 5589 | { |
| 5590 | update.parked.push(name.to_string()); |
| 5591 | } |
| 5592 | } |
| 5593 | } |
| 5594 | update |
| 5595 | } |
| 5596 | |
| 5597 | /// Watch every live connection and reconnect the dead ones. Exits when |
| 5598 | /// the pool is dropped or the engine stops listening, even between |
| 5599 | /// updates. Reports transitions only, so the engine emits a snapshot |
| 5600 | /// update exactly when something changed (#6187). |
| 5601 | pub async fn supervise_pool( |
| 5602 | pool: std::sync::Weak<tokio::sync::Mutex<McpPool>>, |
| 5603 | tx: tokio::sync::mpsc::Sender<McpSupervisorUpdate>, |
| 5604 | ) { |
| 5605 | loop { |
| 5606 | tokio::select! { |
| 5607 | () = tokio::time::sleep(Self::SUPERVISOR_TICK) => {} |
| 5608 | () = tx.closed() => break, |
| 5609 | } |
| 5610 | let Some(pool) = pool.upgrade() else { break }; |
| 5611 | let refreshed = pool.lock().await.revalidate_catalogs().await; |
| 5612 | if !refreshed.is_empty() |
| 5613 | && tx |
| 5614 | .send(McpSupervisorUpdate { |
| 5615 | refreshed, |
| 5616 | ..Default::default() |
| 5617 | }) |
| 5618 | .await |
| 5619 | .is_err() |
| 5620 | { |
| 5621 | break; |
| 5622 | } |
| 5623 | let plan = pool.lock().await.plan_supervision(); |
| 5624 | if plan.due.is_empty() && plan.recovered.is_empty() && plan.parked.is_empty() { |
| 5625 | continue; |
| 5626 | } |
| 5627 | let mut connects = Self::spawn_pending_connects_with_auth_context( |
| 5628 | plan.due |
| 5629 | .iter() |
| 5630 | .map(|due| (due.name.clone(), due.config.clone())) |
| 5631 | .collect(), |
| 5632 | plan.timeouts, |
| 5633 | plan.network_policy.clone(), |
| 5634 | plan.catalog_generation, |
| 5635 | plan.backend, |
| 5636 | Arc::clone(&plan.auth_context), |
| 5637 | ); |
| 5638 | let mut update = McpSupervisorUpdate { |
| 5639 | recovered: plan.recovered, |
| 5640 | parked: plan.parked, |
| 5641 | ..Default::default() |
| 5642 | }; |
| 5643 | let fresh_by_name: HashMap<String, bool> = plan |
| 5644 | .due |
| 5645 | .into_iter() |
| 5646 | .map(|due| (due.name, due.fresh_death)) |
| 5647 | .collect(); |
| 5648 | while let Some(joined) = connects.join_next().await { |
| 5649 | let (name, result) = joined |
| 5650 | .unwrap_or_else(|error| ("connection task".to_string(), Err(error.into()))); |
| 5651 | let fresh_death = fresh_by_name.get(&name).copied().unwrap_or(false); |
| 5652 | let mut guard = pool.lock().await; |
| 5653 | if guard.current_catalog_generation() != plan.catalog_generation { |
| 5654 | if guard.connections.contains_key(&name) { |
| 5655 | guard.connecting.remove(&name); |
| 5656 | } |
| 5657 | continue; |
| 5658 | } |
| 5659 | update.merge(guard.resolve_supervision_attempt(&name, fresh_death, result)); |
| 5660 | } |
| 5661 | if !update.is_empty() && tx.send(update).await.is_err() { |
| 5662 | break; |
| 5663 | } |
| 5664 | } |
| 5665 | } |
| 5666 | |
| 5667 | /// Collect the configured servers a connect pass should start. `only` |
| 5668 | /// scopes the pass to the given names; `None` connects every enabled, |
| 5669 | /// allowed server (`connect_all`). Dynamic runtime servers stay |
| 5670 | /// registered and connect via [`Self::get_or_connect`]; connect passes |
| 5671 | /// have never spawned them. Every emitted name is marked |
| 5672 | /// [`Self::connecting`] until its spawn resolves. |
| 5673 | pub fn collect_pending_connects( |
| 5674 | &mut self, |
| 5675 | only: Option<&HashSet<String>>, |
| 5676 | ) -> (Vec<McpPendingConnect>, Vec<McpConnectError>) { |
| 5677 | self.sync_runtime_servers(); |
| 5678 | let names: Vec<String> = self |
| 5679 | .config |
| 5680 | .servers |
| 5681 | .iter() |
| 5682 | .filter(|(name, server)| server.is_enabled() && self.server_allowed(name)) |
| 5683 | .filter(|(name, _)| only.is_none_or(|set| set.contains(*name))) |
| 5684 | .map(|(name, _)| name.clone()) |
| 5685 | .collect(); |
| 5686 | let mut pending = Vec::new(); |
| 5687 | let mut errors = Vec::new(); |
| 5688 | for name in names { |
| 5689 | let Some(server_config) = self.config.servers.get(&name).cloned() else { |
| 5690 | continue; |
| 5691 | }; |
| 5692 | |
| 5693 | let plugin_source = self |
| 5694 | .connections |
| 5695 | .get(&name) |
| 5696 | .and_then(|connection| connection.config().reviewed_plugin_source().cloned()) |
| 5697 | .or_else(|| server_config.reviewed_plugin_source().cloned()); |
| 5698 | if let Some(source) = plugin_source |
| 5699 | && let Err(error) = source.validate_before_use(&name, "use") |
| 5700 | { |
| 5701 | self.drop_connection(&name, "plugin authority revoked or changed"); |
| 5702 | errors.push((name, error)); |
| 5703 | continue; |
| 5704 | } |
| 5705 | |
| 5706 | // Authority validated immediately above for this same source. |
| 5707 | if self |
| 5708 | .connections |
| 5709 | .get(&name) |
| 5710 | .is_some_and(McpConnection::is_transport_ready) |
| 5711 | { |
| 5712 | continue; |
| 5713 | } |
| 5714 | // Inside its cooldown a failed server costs nothing and still |
| 5715 | // tells the truth: the recorded diagnosis is replayed so the row |
| 5716 | // keeps reading `error`, rather than going quiet and looking |
| 5717 | // healthy because nobody asked. |
| 5718 | if let Some(backoff) = self.connect_backoff.get(&name) |
| 5719 | && std::time::Instant::now() < backoff.retry_after |
| 5720 | { |
| 5721 | errors.push((name, anyhow::anyhow!(backoff.last_error.clone()))); |
| 5722 | continue; |
| 5723 | } |
| 5724 | if self.connecting.contains(&name) { |
| 5725 | // An earlier pass spawned this connect and it has not |
| 5726 | // resolved; a second pass must not spawn a duplicate. |
| 5727 | continue; |
| 5728 | } |
| 5729 | self.drop_connection(&name, "reconnect"); |
| 5730 | self.connecting.insert(name.clone()); |
| 5731 | pending.push((name, server_config)); |
| 5732 | } |
| 5733 | (pending, errors) |
| 5734 | } |
| 5735 | |
| 5736 | /// Start connects for servers an explicit tool selection named. Unlike a |
| 5737 | /// boot pass the selection is the intent — cooldowns do not apply — but |
| 5738 | /// servers already ready or already in flight are left alone, and plugin |
| 5739 | /// authority is re-validated exactly as in |
| 5740 | /// [`Self::collect_pending_connects`]. Covers dynamic servers too: a |
| 5741 | /// selection can name one. |
| 5742 | pub fn take_pending_connects_for( |
| 5743 | &mut self, |
| 5744 | names: &[String], |
| 5745 | ) -> (Vec<McpPendingConnect>, Vec<McpConnectError>) { |
| 5746 | self.sync_runtime_servers(); |
| 5747 | let mut pending = Vec::new(); |
| 5748 | let mut errors = Vec::new(); |
| 5749 | for name in names { |
| 5750 | let Some(server_config) = self.server_config(name) else { |
| 5751 | continue; |
| 5752 | }; |
| 5753 | if !server_config.is_enabled() || !self.server_allowed(name) { |
| 5754 | continue; |
| 5755 | } |
| 5756 | let plugin_source = self |
| 5757 | .connections |
| 5758 | .get(name) |
| 5759 | .and_then(|connection| connection.config().reviewed_plugin_source().cloned()) |
| 5760 | .or_else(|| server_config.reviewed_plugin_source().cloned()); |
| 5761 | if let Some(source) = plugin_source |
| 5762 | && let Err(error) = source.validate_before_use(name, "use") |
| 5763 | { |
| 5764 | self.drop_connection(name, "plugin authority revoked or changed"); |
| 5765 | errors.push((name.clone(), error)); |
| 5766 | continue; |
| 5767 | } |
| 5768 | // Authority validated immediately above for this same source. |
| 5769 | if self |
| 5770 | .connections |
| 5771 | .get(name) |
| 5772 | .is_some_and(McpConnection::is_transport_ready) |
| 5773 | || !self.connecting.insert(name.clone()) |
| 5774 | { |
| 5775 | continue; |
| 5776 | } |
| 5777 | self.drop_connection(name, "reconnect"); |
| 5778 | pending.push((name.clone(), server_config)); |
| 5779 | } |
| 5780 | (pending, errors) |
| 5781 | } |
| 5782 | |
| 5783 | /// Forget in-flight marks for connects whose spawns were aborted before |
| 5784 | /// resolution (boot-pass abort on config change, deadline expiry). |
| 5785 | pub fn cancel_connecting(&mut self, names: &HashSet<String>) { |
| 5786 | self.connecting.retain(|name| !names.contains(name)); |
| 5787 | } |
| 5788 | |
| 5789 | /// Servers with a connect in flight right now — the one honest answer to |
| 5790 | /// "which servers are connecting" (#6033). |
| 5791 | pub fn connecting_servers(&self) -> Vec<String> { |
| 5792 | self.connecting.iter().cloned().collect() |
| 5793 | } |
| 5794 | |
| 5795 | /// Enabled, allowed configured servers the boot pass starts at session |
| 5796 | /// start: every one, user-configured or plugin-contributed, except those |
| 5797 | /// marked `lazy = true`, which connect on demand unless `required` or |
| 5798 | /// covered by the session's explicit tool selections. |
| 5799 | pub fn eager_boot_server_names(&self, requested: &[String]) -> HashSet<String> { |
| 5800 | self.config |
| 5801 | .servers |
| 5802 | .iter() |
| 5803 | .filter(|(name, server)| server.is_enabled() && self.server_allowed(name)) |
| 5804 | .filter(|(name, server)| { |
| 5805 | server.required || !server.lazy || tool_selection_covers_server(requested, name) |
| 5806 | }) |
| 5807 | .map(|(name, _)| name.clone()) |
| 5808 | .collect() |
| 5809 | } |
| 5810 | |
| 5811 | /// Configured servers a turn may name to the model, sorted: enabled, |
| 5812 | /// allowed and `permitted`, the same fail-closed gates |
| 5813 | /// [`Self::configured_servers_for_search`] applies before a handshake. |
| 5814 | /// Names only — nothing is connected and no schema is read. |
| 5815 | pub fn discoverable_configured_servers(&self, permitted: impl Fn(&str) -> bool) -> Vec<String> { |
| 5816 | let mut names: Vec<String> = self |
| 5817 | .config |
| 5818 | .servers |
| 5819 | .iter() |
| 5820 | .filter(|(name, config)| { |
| 5821 | config.is_enabled() && self.server_allowed(name) && permitted(name) |
| 5822 | }) |
| 5823 | .map(|(name, _)| name.clone()) |
| 5824 | .collect(); |
| 5825 | names.sort(); |
| 5826 | names |
| 5827 | } |
| 5828 | |
| 5829 | pub fn model_server_statuses( |
| 5830 | &self, |
| 5831 | permitted: impl Fn(&str) -> bool, |
| 5832 | visible_tools: &HashSet<String>, |
| 5833 | discovery_available: bool, |
| 5834 | failed: &HashSet<String>, |
| 5835 | ) -> Vec<(String, codewhale_mcp::ModelServerStatus)> { |
| 5836 | self.model_server_statuses_for( |
| 5837 | permitted, |
| 5838 | visible_tools, |
| 5839 | discovery_available, |
| 5840 | failed, |
| 5841 | &self.resolved_tool_servers(), |
| 5842 | ) |
| 5843 | } |
| 5844 | |
| 5845 | pub(crate) fn model_server_statuses_for( |
| 5846 | &self, |
| 5847 | permitted: impl Fn(&str) -> bool, |
| 5848 | visible_tools: &HashSet<String>, |
| 5849 | discovery_available: bool, |
| 5850 | failed: &HashSet<String>, |
| 5851 | routes: &std::collections::BTreeMap<String, String>, |
| 5852 | ) -> Vec<(String, codewhale_mcp::ModelServerStatus)> { |
| 5853 | use codewhale_mcp::ModelServerStatus; |
| 5854 | |
| 5855 | let mut names: BTreeSet<String> = if discovery_available { |
| 5856 | self.discoverable_configured_servers(&permitted) |
| 5857 | .into_iter() |
| 5858 | .collect() |
| 5859 | } else { |
| 5860 | BTreeSet::new() |
| 5861 | }; |
| 5862 | names.extend( |
| 5863 | routes |
| 5864 | .iter() |
| 5865 | .filter(|(tool, server)| { |
| 5866 | visible_tools.contains(*tool) |
| 5867 | && permitted(server) |
| 5868 | && self |
| 5869 | .server_config(server) |
| 5870 | .is_some_and(|config| config.is_enabled()) |
| 5871 | }) |
| 5872 | .map(|(_, server)| server.clone()), |
| 5873 | ); |
| 5874 | let generation = self.current_catalog_generation(); |
| 5875 | let mut rows: Vec<_> = names |
| 5876 | .into_iter() |
| 5877 | .map(|name| { |
| 5878 | let connection = self.connections.get(&name); |
| 5879 | let status = if self.needs_auth_servers.contains(&name) { |
| 5880 | ModelServerStatus::AuthorizationRequired |
| 5881 | } else if self.connecting.contains(&name) { |
| 5882 | ModelServerStatus::Connecting |
| 5883 | } else if connection.is_some_and(|conn| conn.catalog_generation != generation) { |
| 5884 | ModelServerStatus::Unknown |
| 5885 | } else if connection.is_some_and(McpConnection::is_ready) { |
| 5886 | ModelServerStatus::Connected |
| 5887 | } else if connection.is_some() |
| 5888 | || self.connect_backoff.contains_key(&name) |
| 5889 | || failed.contains(&name) |
| 5890 | { |
| 5891 | ModelServerStatus::Failed |
| 5892 | } else { |
| 5893 | ModelServerStatus::Configured |
| 5894 | }; |
| 5895 | (name, status) |
| 5896 | }) |
| 5897 | .collect(); |
| 5898 | rows.sort_by(|(left, a), (right, b)| a.cmp(b).then_with(|| left.cmp(right))); |
| 5899 | rows |
| 5900 | } |
| 5901 | |
| 5902 | fn mcp_search_tokens(text: &str) -> Vec<String> { |
| 5903 | const NOISE_TOKENS: &[&str] = &[ |
| 5904 | "http", |
| 5905 | "sse", |
| 5906 | "stdio", |
| 5907 | "www", |
| 5908 | "com", |
| 5909 | "org", |
| 5910 | "net", |
| 5911 | "app", |
| 5912 | "dev", |
| 5913 | "api", |
| 5914 | "mcp", |
| 5915 | "server", |
| 5916 | "localhost", |
| 5917 | "local", |
| 5918 | "npx", |
| 5919 | "node", |
| 5920 | "python", |
| 5921 | "run", |
| 5922 | "tool", |
| 5923 | "search", |
| 5924 | "list", |
| 5925 | "get", |
| 5926 | "read", |
| 5927 | "write", |
| 5928 | "find", |
| 5929 | "create", |
| 5930 | "update", |
| 5931 | "delete", |
| 5932 | "file", |
| 5933 | "the", |
| 5934 | "and", |
| 5935 | "for", |
| 5936 | "with", |
| 5937 | "from", |
| 5938 | ]; |
| 5939 | crate::core::engine::tool_catalog::split_identifier_tokens(text) |
| 5940 | .into_iter() |
| 5941 | .filter_map(|token| { |
| 5942 | let singular = token |
| 5943 | .strip_suffix('s') |
| 5944 | .filter(|stem| stem.len() >= 3) |
| 5945 | .unwrap_or(token.as_str()); |
| 5946 | (singular.len() >= 3 && !NOISE_TOKENS.contains(&singular)) |
| 5947 | .then(|| singular.to_string()) |
| 5948 | }) |
| 5949 | .collect() |
| 5950 | } |
| 5951 | |
| 5952 | fn runner_package_basename(config: &McpServerConfig) -> Option<&str> { |
| 5953 | if !config.launches_package_runner() { |
| 5954 | return None; |
| 5955 | } |
| 5956 | let package = config.args.iter().find(|arg| !arg.starts_with('-'))?; |
| 5957 | let name = match package.strip_prefix('@') { |
| 5958 | Some(scoped) => scoped.split_once('/')?.1, |
| 5959 | None => package.as_str(), |
| 5960 | }; |
| 5961 | let name = name.split_once("==").map_or(name, |(name, _)| name); |
| 5962 | let name = name.split_once('@').map_or(name, |(name, _)| name); |
| 5963 | (name.starts_with(|ch: char| ch.is_ascii_alphabetic()) |
| 5964 | && name |
| 5965 | .chars() |
| 5966 | .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))) |
| 5967 | .then_some(name) |
| 5968 | } |
| 5969 | |
| 5970 | fn search_metadata_matches( |
| 5971 | name: &str, |
| 5972 | config: &McpServerConfig, |
| 5973 | query_tokens: &HashSet<String>, |
| 5974 | ) -> bool { |
| 5975 | let host = config.url.as_deref().and_then(host_from_url); |
| 5976 | std::iter::once(name) |
| 5977 | .chain( |
| 5978 | config |
| 5979 | .reviewed_plugin_source() |
| 5980 | .map(ReviewedPluginMcpSource::plugin_name), |
| 5981 | ) |
| 5982 | .chain(config.enabled_tools.iter().map(String::as_str)) |
| 5983 | .chain(host.as_deref()) |
| 5984 | .chain(Self::runner_package_basename(config)) |
| 5985 | .flat_map(Self::mcp_search_tokens) |
| 5986 | .any(|token| query_tokens.contains(&token)) |
| 5987 | } |
| 5988 | |
| 5989 | pub(crate) fn model_server_summaries_for( |
| 5990 | &self, |
| 5991 | permitted: impl Fn(&str) -> bool, |
| 5992 | visible_tools: &HashSet<String>, |
| 5993 | discovery_available: bool, |
| 5994 | failed: &HashSet<String>, |
| 5995 | routes: &std::collections::BTreeMap<String, String>, |
| 5996 | ) -> Vec<crate::runtime_handoff::McpServerSummary> { |
| 5997 | use codewhale_mcp::ModelServerStatus; |
| 5998 | |
| 5999 | self.model_server_statuses_for( |
| 6000 | permitted, |
| 6001 | visible_tools, |
| 6002 | discovery_available, |
| 6003 | failed, |
| 6004 | routes, |
| 6005 | ) |
| 6006 | .into_iter() |
| 6007 | .map(|(name, status)| { |
| 6008 | let connection = self |
| 6009 | .connections |
| 6010 | .get(&name) |
| 6011 | .filter(|_| status == ModelServerStatus::Connected); |
| 6012 | let mut tools: Vec<String> = connection |
| 6013 | .map(|conn| { |
| 6014 | conn.tools() |
| 6015 | .iter() |
| 6016 | .filter(|tool| { |
| 6017 | let qualified = Self::mcp_model_tool_name(&name, &tool.name); |
| 6018 | routes.get(&qualified) == Some(&name) |
| 6019 | && visible_tools.contains(&qualified) |
| 6020 | }) |
| 6021 | .map(|tool| tool.name.clone()) |
| 6022 | .collect() |
| 6023 | }) |
| 6024 | .unwrap_or_default(); |
| 6025 | tools.sort(); |
| 6026 | let connection = connection.filter(|_| !tools.is_empty()); |
| 6027 | let mut capabilities = Vec::new(); |
| 6028 | if let Some(caps) = connection.and_then(|conn| conn.server_capabilities) { |
| 6029 | if caps.tools { |
| 6030 | capabilities.push("tools"); |
| 6031 | } |
| 6032 | if caps.resources { |
| 6033 | capabilities.push("resources"); |
| 6034 | } |
| 6035 | if caps.prompts { |
| 6036 | capabilities.push("prompts"); |
| 6037 | } |
| 6038 | } |
| 6039 | let description = connection.and_then(|conn| { |
| 6040 | conn.instructions() |
| 6041 | .and_then(|text| text.lines().map(str::trim).find(|line| !line.is_empty())) |
| 6042 | .or_else(|| { |
| 6043 | conn.config() |
| 6044 | .reviewed_plugin_source() |
| 6045 | .map(ReviewedPluginMcpSource::plugin_name) |
| 6046 | }) |
| 6047 | .map(str::to_string) |
| 6048 | }); |
| 6049 | crate::runtime_handoff::McpServerSummary { |
| 6050 | name, |
| 6051 | status, |
| 6052 | description, |
| 6053 | capabilities, |
| 6054 | tools, |
| 6055 | } |
| 6056 | }) |
| 6057 | .collect() |
| 6058 | } |
| 6059 | |
| 6060 | /// Match discovery intent against actual configured server entries only. |
| 6061 | /// No guessed tool/schema is inserted; the caller still obtains tools/list. |
| 6062 | pub fn configured_servers_for_search( |
| 6063 | &self, |
| 6064 | query: &str, |
| 6065 | match_kind: &str, |
| 6066 | permitted: impl Fn(&str) -> bool, |
| 6067 | ) -> Result<Vec<String>> { |
| 6068 | const MAX_DISCOVERY_SERVERS: usize = 8; |
| 6069 | let regex = match match_kind { |
| 6070 | "regex" => { |
| 6071 | Some(codewhale_runtime::regex_cache::compile_user_regex_case_insensitive(query)?) |
| 6072 | } |
| 6073 | "bm25" => None, |
| 6074 | _ => anyhow::bail!("Unsupported tool search match algorithm"), |
| 6075 | }; |
| 6076 | let query = query.trim().to_ascii_lowercase(); |
| 6077 | let query_tokens: HashSet<String> = query |
| 6078 | .split_whitespace() |
| 6079 | .filter(|term| !term.starts_with("mcp_")) |
| 6080 | .flat_map(Self::mcp_search_tokens) |
| 6081 | .collect(); |
| 6082 | let mut ranked = Vec::new(); |
| 6083 | for (name, config) in &self.config.servers { |
| 6084 | if !config.is_enabled() || !self.server_allowed(name) || !permitted(name) { |
| 6085 | continue; |
| 6086 | } |
| 6087 | let name_lower = name.to_ascii_lowercase(); |
| 6088 | let prefix = format!("mcp_{name_lower}_"); |
| 6089 | let rank = if let Some(regex) = ®ex { |
| 6090 | // A general regex such as .* is not MCP launch intent. Match |
| 6091 | // only a named server, or an explicit MCP namespace search. |
| 6092 | ((query.contains("mcp_") |
| 6093 | && (regex.is_match(&prefix) |
| 6094 | || query.trim_start_matches('^').starts_with(&prefix))) |
| 6095 | || query == name_lower) |
| 6096 | .then_some(0) |
| 6097 | } else { |
| 6098 | query |
| 6099 | .split_whitespace() |
| 6100 | .filter_map(|term| { |
| 6101 | if term == name_lower || term.starts_with(&prefix) { |
| 6102 | Some(0) |
| 6103 | } else if term == "mcp" { |
| 6104 | Some(3) |
| 6105 | } else { |
| 6106 | (!term.starts_with("mcp_") |
| 6107 | && term.len() >= 3 |
| 6108 | && name_lower.contains(term)) |
| 6109 | .then_some(1) |
| 6110 | } |
| 6111 | }) |
| 6112 | .chain(Self::search_metadata_matches(name, config, &query_tokens).then_some(2)) |
| 6113 | .min() |
| 6114 | }; |
| 6115 | if let Some(rank) = rank |
| 6116 | && !self |
| 6117 | .connections |
| 6118 | .get(name) |
| 6119 | .is_some_and(McpConnection::is_ready) |
| 6120 | { |
| 6121 | ranked.push((rank, name.clone())); |
| 6122 | } |
| 6123 | } |
| 6124 | ranked.sort(); |
| 6125 | ranked.truncate(MAX_DISCOVERY_SERVERS); |
| 6126 | Ok(ranked.into_iter().map(|(_, name)| name).collect()) |
| 6127 | } |
| 6128 | |
| 6129 | /// Enabled, allowed servers — configured or dynamic — covered by an |
| 6130 | /// explicit tool selection (`mcp_<server>_*` names or `mcp_<prefix>*` |
| 6131 | /// globs). These are the names a turn is allowed to start on demand. |
| 6132 | pub fn explicitly_selected_server_names(&self, requested: &[String]) -> Vec<String> { |
| 6133 | let dynamic = self.dynamic_servers.read(); |
| 6134 | self.config |
| 6135 | .servers |
| 6136 | .iter() |
| 6137 | .chain(dynamic.iter()) |
| 6138 | .filter(|(name, server)| server.is_enabled() && self.server_allowed(name)) |
| 6139 | .filter(|(name, _)| tool_selection_covers_server(requested, name)) |
| 6140 | .map(|(name, _)| name.clone()) |
| 6141 | .collect() |
| 6142 | } |
| 6143 | |
| 6144 | pub fn push_required_server_errors(&self, errors: &mut Vec<McpConnectError>) { |
| 6145 | for (name, server_cfg) in &self.config.servers { |
| 6146 | // Only stand in for a missing diagnosis. When the connect attempt |
| 6147 | // above already reported why this server failed, appending a |
| 6148 | // second, contentless entry for the same name buries it: callers |
| 6149 | // fold these pairs into a `HashMap<name, message>`, so the later |
| 6150 | // generic string silently replaced the real cause. |
| 6151 | if self.server_allowed(name) |
| 6152 | && server_cfg.required |
| 6153 | && server_cfg.is_enabled() |
| 6154 | && !self |
| 6155 | .connections |
| 6156 | .get(name) |
| 6157 | .is_some_and(McpConnection::is_ready) |
| 6158 | && !errors.iter().any(|(failed, _)| failed == name) |
| 6159 | { |
| 6160 | errors.push(( |
| 6161 | name.clone(), |
| 6162 | anyhow::anyhow!("required MCP server failed to initialize"), |
| 6163 | )); |
| 6164 | } |
| 6165 | } |
| 6166 | } |
| 6167 | |
| 6168 | /// Handshake the pending servers concurrently without holding the pool |
| 6169 | /// lock. Callers insert results under a short lock so a live turn can |
| 6170 | /// snapshot ready tools while optional servers are still connecting. |
| 6171 | pub fn spawn_pending_connects( |
| 6172 | pending: Vec<McpPendingConnect>, |
| 6173 | timeouts: McpTimeouts, |
| 6174 | network_policy: Option<NetworkPolicyDecider>, |
| 6175 | catalog_generation: u64, |
| 6176 | backend: McpBackend, |
| 6177 | ) -> tokio::task::JoinSet<(String, Result<McpConnection, anyhow::Error>)> { |
| 6178 | Self::spawn_pending_connects_with_auth_context( |
| 6179 | pending, |
| 6180 | timeouts, |
| 6181 | network_policy, |
| 6182 | catalog_generation, |
| 6183 | backend, |
| 6184 | process_mcp_auth_context(), |
| 6185 | ) |
| 6186 | } |
| 6187 | |
| 6188 | pub fn spawn_pending_connects_with_auth_context( |
| 6189 | pending: Vec<McpPendingConnect>, |
| 6190 | timeouts: McpTimeouts, |
| 6191 | network_policy: Option<NetworkPolicyDecider>, |
| 6192 | catalog_generation: u64, |
| 6193 | backend: McpBackend, |
| 6194 | auth_context: Arc<dyn AuthContext>, |
| 6195 | ) -> tokio::task::JoinSet<(String, Result<McpConnection, anyhow::Error>)> { |
| 6196 | let semaphore = std::sync::Arc::new(tokio::sync::Semaphore::new(Self::CONNECT_CONCURRENCY)); |
| 6197 | let mut joins: tokio::task::JoinSet<(String, Result<McpConnection, anyhow::Error>)> = |
| 6198 | tokio::task::JoinSet::new(); |
| 6199 | for (name, config) in pending { |
| 6200 | let permit = semaphore.clone(); |
| 6201 | let network_policy = network_policy.clone(); |
| 6202 | let auth_context = Arc::clone(&auth_context); |
| 6203 | joins.spawn(async move { |
| 6204 | let connection = std::panic::AssertUnwindSafe(async { |
| 6205 | let _permit = permit.acquire_owned().await; |
| 6206 | McpConnection::connect_with_backend_and_auth_context( |
| 6207 | name.clone(), |
| 6208 | config, |
| 6209 | &timeouts, |
| 6210 | network_policy.as_ref(), |
| 6211 | backend, |
| 6212 | auth_context, |
| 6213 | ) |
| 6214 | .await |
| 6215 | .map(|mut connection| { |
| 6216 | connection.catalog_generation = catalog_generation; |
| 6217 | connection |
| 6218 | }) |
| 6219 | }) |
| 6220 | .catch_unwind() |
| 6221 | .await |
| 6222 | .unwrap_or_else(|_| Err(anyhow::anyhow!("MCP connection task panicked"))); |
| 6223 | (name, connection) |
| 6224 | }); |
| 6225 | } |
| 6226 | |
| 6227 | joins |
| 6228 | } |
| 6229 | |
| 6230 | /// Connect to all enabled servers, returning errors for failed connections. |
| 6231 | /// |
| 6232 | /// Servers connect **concurrently** (bounded by [`Self::CONNECT_CONCURRENCY`]). |
| 6233 | /// This used to be a sequential loop over `get_or_connect`, so every |
| 6234 | /// server paid the slowest server's spawn+handshake from its own budget: |
| 6235 | /// with the default 10s connect timeout, N servers meant a worst case of |
| 6236 | /// N×10s before the pool was usable. Each connection still gets its own |
| 6237 | /// configured connect timeout; one wedged server can no longer serialize |
| 6238 | /// the rest. |
| 6239 | /// |
| 6240 | /// Semantics preserved from the sequential loop: only configured servers |
| 6241 | /// are connected (dynamic runtime entries stay registered), the config is |
| 6242 | /// reloaded before the name snapshot (so a server added mid-session |
| 6243 | /// connects on this call, not the next), plugin-authority revocation |
| 6244 | /// drops the connection instead of silently reconnecting, and the |
| 6245 | /// required-server sweep reports at most one error per name. Config edits |
| 6246 | /// that land while the batch is in flight are reconciled by one retry |
| 6247 | /// pass: a content change drops the connections of servers whose config |
| 6248 | /// changed, and the retry pass redials them. |
| 6249 | pub async fn connect_all(&mut self) -> Vec<(String, anyhow::Error)> { |
| 6250 | let mut errors = Vec::new(); |
| 6251 | // Reload before taking the configured-name snapshot. Previously the |
| 6252 | // first call after adding a server captured the old names, then only |
| 6253 | // noticed the config change inside `get_or_connect`, delaying the new |
| 6254 | // server until a second turn. |
| 6255 | if let Err(err) = self.reload_if_config_changed().await { |
| 6256 | errors.push(("configuration".to_string(), err)); |
| 6257 | return errors; |
| 6258 | } |
| 6259 | |
| 6260 | // Drop needs-auth markers for servers that are no longer connectable |
| 6261 | // (removed from config or disabled); the loop below re-marks any |
| 6262 | // server whose fresh connect attempt still fails auth-required. |
| 6263 | { |
| 6264 | let dynamic = self.dynamic_servers.read(); |
| 6265 | let before = self.needs_auth_servers.len(); |
| 6266 | self.needs_auth_servers.retain(|name| { |
| 6267 | self.config |
| 6268 | .servers |
| 6269 | .get(name) |
| 6270 | .is_some_and(|server| server.is_enabled()) |
| 6271 | || dynamic.get(name).is_some_and(|server| server.is_enabled()) |
| 6272 | }); |
| 6273 | if self.needs_auth_servers.len() != before { |
| 6274 | self.needs_auth_generation = self.needs_auth_generation.wrapping_add(1); |
| 6275 | } |
| 6276 | } |
| 6277 | |
| 6278 | for _pass in 0..2 { |
| 6279 | let (pending, auth_errors) = self.collect_pending_connects(None); |
| 6280 | errors.extend(auth_errors); |
| 6281 | if pending.is_empty() { |
| 6282 | break; |
| 6283 | } |
| 6284 | |
| 6285 | let mut connects = Self::spawn_pending_connects_with_auth_context( |
| 6286 | pending, |
| 6287 | self.config.timeouts, |
| 6288 | self.network_policy.clone(), |
| 6289 | self.current_catalog_generation(), |
| 6290 | self.backend, |
| 6291 | Arc::clone(&self.auth_context), |
| 6292 | ); |
| 6293 | while let Some(joined) = connects.join_next().await { |
| 6294 | let (name, result) = joined |
| 6295 | .unwrap_or_else(|error| ("connection task".to_string(), Err(error.into()))); |
| 6296 | let result = result |
| 6297 | .and_then(|connection| self.store_ready_connection(name.clone(), connection)); |
| 6298 | if let Err(error) = result { |
| 6299 | self.note_connect_failure(&name, &error); |
| 6300 | errors.push((name, error)); |
| 6301 | } |
| 6302 | } |
| 6303 | |
| 6304 | // Reconcile a config edit that landed mid-batch: a content |
| 6305 | // change dropped the connections of servers whose config changed, |
| 6306 | // so run one more pass against the new config and drop the stale |
| 6307 | // pass's errors with it. |
| 6308 | match self.reload_if_config_changed().await { |
| 6309 | Ok(true) => { |
| 6310 | errors.clear(); |
| 6311 | continue; |
| 6312 | } |
| 6313 | Ok(false) => break, |
| 6314 | Err(error) => { |
| 6315 | errors.push(("configuration".to_string(), error)); |
| 6316 | break; |
| 6317 | } |
| 6318 | } |
| 6319 | } |
| 6320 | |
| 6321 | self.push_required_server_errors(&mut errors); |
| 6322 | errors |
| 6323 | } |
| 6324 | |
| 6325 | /// The single definition of an MCP tool's model-facing name. |
| 6326 | /// |
| 6327 | /// [`Self::all_tools`] (which builds the model catalog) and |
| 6328 | /// [`Self::resolved_tool_servers`] (which tells tool inspection which |
| 6329 | /// server owns a name) both call this, so a human-facing server |
| 6330 | /// attribution can never drift from the name the model actually received. |
| 6331 | #[must_use] |
| 6332 | pub fn mcp_model_tool_name(server: &str, tool: &str) -> String { |
| 6333 | format!("mcp_{server}_{tool}") |
| 6334 | } |
| 6335 | |
| 6336 | /// Map an exact `mcp_<server>_authenticate` model tool name to its server |
| 6337 | /// when the synthetic self-serve OAuth login tool should answer for it: |
| 6338 | /// the server's last connect failed auth-required, or the name matches a |
| 6339 | /// configured OAuth-capable server whose catalog entry is stale (a login |
| 6340 | /// completed since the catalog was built). Never fires when a ready |
| 6341 | /// connection advertises a real tool under the same model name — the |
| 6342 | /// server's own `authenticate` tool always wins. |
| 6343 | pub fn authenticate_tool_target(&self, prefixed_name: &str) -> Option<String> { |
| 6344 | if !self.tool_allowed(prefixed_name) { |
| 6345 | return None; |
| 6346 | } |
| 6347 | let target = self |
| 6348 | .needs_auth_servers |
| 6349 | .iter() |
| 6350 | .find(|server| { |
| 6351 | Self::mcp_model_tool_name(server, AUTHENTICATE_TOOL_NAME) == prefixed_name |
| 6352 | }) |
| 6353 | .cloned() |
| 6354 | .or_else(|| { |
| 6355 | let dynamic = self.dynamic_servers.read(); |
| 6356 | self.config |
| 6357 | .servers |
| 6358 | .iter() |
| 6359 | .chain(dynamic.iter()) |
| 6360 | .find(|(name, _)| { |
| 6361 | Self::mcp_model_tool_name(name, AUTHENTICATE_TOOL_NAME) == prefixed_name |
| 6362 | }) |
| 6363 | .map(|(name, _)| name.clone()) |
| 6364 | })?; |
| 6365 | let capable = { |
| 6366 | let dynamic = self.dynamic_servers.read(); |
| 6367 | self.config |
| 6368 | .servers |
| 6369 | .get(&target) |
| 6370 | .or_else(|| dynamic.get(&target)) |
| 6371 | .is_some_and(oauth::server_supports_oauth_login) |
| 6372 | }; |
| 6373 | if !capable || !self.server_allowed(&target) { |
| 6374 | return None; |
| 6375 | } |
| 6376 | if self.parse_prefixed_name(prefixed_name).is_ok() { |
| 6377 | return None; |
| 6378 | } |
| 6379 | Some(target) |
| 6380 | } |
| 6381 | |
| 6382 | /// The configured server by name, static config first, then the |
| 6383 | /// session's dynamically added servers. |
| 6384 | fn server_config(&self, server_name: &str) -> Option<McpServerConfig> { |
| 6385 | self.config |
| 6386 | .servers |
| 6387 | .get(server_name) |
| 6388 | .cloned() |
| 6389 | .or_else(|| self.dynamic_servers.read().get(server_name).cloned()) |
| 6390 | } |
| 6391 | |
| 6392 | /// Phase one of the synthetic `mcp_<server>_authenticate` tool: decide |
| 6393 | /// whether a browser login is needed and, if so, start it. Only touches |
| 6394 | /// config, the connection map, discovery, and the token store — it returns as soon |
| 6395 | /// as the authorization URL exists, so a caller holding the pool lock can |
| 6396 | /// release it before the (up to 15 minute) browser wait in |
| 6397 | /// [`oauth::McpOAuthToolLogin::finish`]. Holding the lock across that wait |
| 6398 | /// would freeze every other MCP call, the `/mcp` manager, and the |
| 6399 | /// Extensions view for the whole sign-in. |
| 6400 | pub async fn begin_authenticate_tool( |
| 6401 | &self, |
| 6402 | server_name: &str, |
| 6403 | ) -> Result<AuthenticateToolStart> { |
| 6404 | self.require_server(server_name)?; |
| 6405 | Self::authorize_call( |
| 6406 | &self.disallowed_tools, |
| 6407 | &Self::mcp_model_tool_name(server_name, AUTHENTICATE_TOOL_NAME), |
| 6408 | &serde_json::json!({}), |
| 6409 | )?; |
| 6410 | let server = self |
| 6411 | .server_config(server_name) |
| 6412 | .ok_or_else(|| anyhow::anyhow!("MCP server '{server_name}' is no longer configured"))?; |
| 6413 | if !server.is_enabled() { |
| 6414 | anyhow::bail!("MCP server '{server_name}' is disabled"); |
| 6415 | } |
| 6416 | |
| 6417 | // Already-authorized branch: a login that completed since the catalog |
| 6418 | // was built (e.g. `codewhale mcp login` in another window) must not |
| 6419 | // restart the browser flow — adopt the stored tokens by reconnecting. |
| 6420 | let ready = self |
| 6421 | .connections |
| 6422 | .get(server_name) |
| 6423 | .is_some_and(McpConnection::is_ready); |
| 6424 | if ready |
| 6425 | || oauth::has_usable_stored_tokens_with_auth_context( |
| 6426 | server_name, |
| 6427 | &server, |
| 6428 | self.network_policy.as_ref(), |
| 6429 | Arc::clone(&self.auth_context), |
| 6430 | ) |
| 6431 | .await? |
| 6432 | { |
| 6433 | return Ok(AuthenticateToolStart::AlreadyAuthorized); |
| 6434 | } |
| 6435 | let login = oauth::begin_oauth_login_for_server_tool_with_auth_context( |
| 6436 | server_name, |
| 6437 | &server, |
| 6438 | None, |
| 6439 | self.oauth_callback_port, |
| 6440 | self.oauth_callback_url.as_deref(), |
| 6441 | self.network_policy.as_ref(), |
| 6442 | Arc::clone(&self.auth_context), |
| 6443 | ) |
| 6444 | .await?; |
| 6445 | Ok(AuthenticateToolStart::Login(Box::new(login))) |
| 6446 | } |
| 6447 | |
| 6448 | /// Phase two of the synthetic authenticate tool: reconnect the server so |
| 6449 | /// its real tools resolve in this session, and describe the outcome for |
| 6450 | /// the model. `get_or_connect` drops any non-ready connection itself, so |
| 6451 | /// both the fresh-login and already-authorized outcomes fall through to |
| 6452 | /// it. Errors are never swallowed — a reconnect that still fails |
| 6453 | /// auth-required re-marks the server (via `get_or_connect`) and surfaces |
| 6454 | /// truthfully for the model to relay. |
| 6455 | pub async fn finish_authenticate_tool( |
| 6456 | &mut self, |
| 6457 | server_name: &str, |
| 6458 | outcome: AuthenticateToolOutcome, |
| 6459 | ) -> Result<serde_json::Value> { |
| 6460 | self.require_server(server_name)?; |
| 6461 | let rules = self.disallowed_tools.clone(); |
| 6462 | match self.get_or_connect(server_name).await { |
| 6463 | Ok(conn) => { |
| 6464 | let tools: Vec<String> = conn |
| 6465 | .tools() |
| 6466 | .iter() |
| 6467 | .filter(|tool| conn.config().is_tool_enabled(&tool.name)) |
| 6468 | .map(|tool| Self::mcp_model_tool_name(server_name, &tool.name)) |
| 6469 | .filter(|name| { |
| 6470 | !codewhale_execpolicy::tool_rules::tool_matches_any_rule(&rules, name) |
| 6471 | }) |
| 6472 | .collect(); |
| 6473 | let (status, detail) = match &outcome { |
| 6474 | AuthenticateToolOutcome::Authenticated { .. } => ( |
| 6475 | "authenticated", |
| 6476 | "authenticated successfully and is now connected", |
| 6477 | ), |
| 6478 | AuthenticateToolOutcome::AlreadyAuthorized => ( |
| 6479 | "already_authorized", |
| 6480 | "already had valid OAuth credentials and is now connected", |
| 6481 | ), |
| 6482 | }; |
| 6483 | let mut result = serde_json::json!({ |
| 6484 | "status": status, |
| 6485 | "server": server_name, |
| 6486 | "tools": tools, |
| 6487 | "message": format!( |
| 6488 | "MCP server '{server_name}' {detail}. Its real MCP tools (listed in 'tools') replaced the synthetic authenticate tool and are callable from the next model request in this session." |
| 6489 | ), |
| 6490 | }); |
| 6491 | if let AuthenticateToolOutcome::Authenticated { authorization_url } = outcome { |
| 6492 | result["authorization_url"] = serde_json::Value::String(authorization_url); |
| 6493 | } |
| 6494 | Ok(result) |
| 6495 | } |
| 6496 | Err(error) => { |
| 6497 | // A stored token the server just rejected must not feed the |
| 6498 | // loop again: `begin_authenticate_tool` short-circuits to |
| 6499 | // AlreadyAuthorized whenever usable-looking tokens exist, so |
| 6500 | // keeping them means the model re-calls the synthetic tool |
| 6501 | // forever while every reconnect fails auth-required. Drop |
| 6502 | // the durable copy so the next begin starts a real login. |
| 6503 | if matches!(outcome, AuthenticateToolOutcome::AlreadyAuthorized) |
| 6504 | && oauth::error_looks_auth_required(&error) |
| 6505 | && let Some(server) = self.server_config(server_name) |
| 6506 | { |
| 6507 | match oauth::delete_oauth_tokens_for_server(server_name, &server) { |
| 6508 | Ok(true) => tracing::info!( |
| 6509 | target: "mcp", |
| 6510 | server = %server_name, |
| 6511 | "rejected stored OAuth token removed after failed AlreadyAuthorized reconnect" |
| 6512 | ), |
| 6513 | Ok(false) => {} |
| 6514 | Err(delete_err) => tracing::warn!( |
| 6515 | target: "mcp", |
| 6516 | server = %server_name, |
| 6517 | error = %delete_err, |
| 6518 | "could not remove rejected stored OAuth token" |
| 6519 | ), |
| 6520 | } |
| 6521 | } |
| 6522 | Err(error).with_context(|| { |
| 6523 | format!( |
| 6524 | "MCP server '{server_name}' completed OAuth login but the reconnect failed" |
| 6525 | ) |
| 6526 | }) |
| 6527 | } |
| 6528 | } |
| 6529 | } |
| 6530 | |
| 6531 | /// Execute the synthetic `mcp_<server>_authenticate` tool in place, |
| 6532 | /// holding `&mut self` (and therefore any enclosing pool lock) for the |
| 6533 | /// whole flow. Engine tool execution uses |
| 6534 | /// [`authenticate_tool_via_pool`] instead, which releases the shared |
| 6535 | /// pool between the two phases. |
| 6536 | async fn run_authenticate_tool(&mut self, server_name: &str) -> Result<serde_json::Value> { |
| 6537 | let outcome = match self.begin_authenticate_tool(server_name).await? { |
| 6538 | AuthenticateToolStart::AlreadyAuthorized => AuthenticateToolOutcome::AlreadyAuthorized, |
| 6539 | AuthenticateToolStart::Login(login) => { |
| 6540 | let authorization_url = login.authorization_url().to_string(); |
| 6541 | login.finish().await?; |
| 6542 | AuthenticateToolOutcome::Authenticated { authorization_url } |
| 6543 | } |
| 6544 | }; |
| 6545 | self.finish_authenticate_tool(server_name, outcome).await |
| 6546 | } |
| 6547 | |
| 6548 | /// The model-facing recovery for a server in the `◆ auth required` |
| 6549 | /// state: the one call that recovers it. Names the synthetic |
| 6550 | /// `mcp_<server>_authenticate` tool when the server is OAuth-servable, and |
| 6551 | /// otherwise the credential source (plugin environment header, manual |
| 6552 | /// bearer) the server is allowed to authenticate with. |
| 6553 | fn auth_required_hint(&self, server_name: &str) -> String { |
| 6554 | let tool_name = Self::mcp_model_tool_name(server_name, AUTHENTICATE_TOOL_NAME); |
| 6555 | if self.authenticate_tool_target(&tool_name).is_some() { |
| 6556 | return format!( |
| 6557 | "MCP server '{server_name}' requires OAuth login (◆ auth required); call the `{tool_name}` tool to authenticate, or run `/mcp login {server_name}`" |
| 6558 | ); |
| 6559 | } |
| 6560 | let recovery = match self.server_config(server_name) { |
| 6561 | Some(server) => oauth::auth_required_recovery_hint(server_name, &server), |
| 6562 | None => oauth::auth_required_login_hint(server_name), |
| 6563 | }; |
| 6564 | format!("MCP server '{server_name}' requires authentication (◆ auth required); {recovery}") |
| 6565 | } |
| 6566 | |
| 6567 | /// Route an auth-required failure from a live request into the same |
| 6568 | /// typed state a failed connect produces: drop the connection (its |
| 6569 | /// credential is no longer accepted), mark the server needs-auth so the |
| 6570 | /// next catalog offers the synthetic login tool, and name the recovery on |
| 6571 | /// the error. Any other error passes through untouched. |
| 6572 | fn note_live_call_failure(&mut self, server_name: &str, error: anyhow::Error) -> anyhow::Error { |
| 6573 | if !self.error_needs_oauth_login(server_name, &error) { |
| 6574 | // An expired AWS login on a live call names its own recovery |
| 6575 | // instead of passing through as a bare 401. |
| 6576 | let text = format!("{error:#}"); |
| 6577 | if let Some(config) = self.server_config(server_name) |
| 6578 | && mcp_error_is_aws_login(&text, mcp_server_oauth_capable(&config)) |
| 6579 | { |
| 6580 | let hint = aws_login_hint(&config, server_name, &text); |
| 6581 | self.drop_connection(server_name, "AWS credentials expired on live call"); |
| 6582 | self.note_connect_failure(server_name, &error); |
| 6583 | return error.context(hint); |
| 6584 | } |
| 6585 | return error; |
| 6586 | } |
| 6587 | self.drop_connection(server_name, "auth required on live call"); |
| 6588 | self.note_connect_failure(server_name, &error); |
| 6589 | error.context(self.auth_required_hint(server_name)) |
| 6590 | } |
| 6591 | |
| 6592 | /// Fold `(server, tool)` pairs into `model name -> owning server`. |
| 6593 | /// |
| 6594 | /// Mirrors [`Self::all_tools`]' ambiguity rule: when two servers produce |
| 6595 | /// the same model name, the name is dropped entirely rather than |
| 6596 | /// attributed to an arbitrary winner. Callers then report it as unknown. |
| 6597 | #[must_use] |
| 6598 | pub fn resolve_tool_server_map<'a>( |
| 6599 | pairs: impl Iterator<Item = (&'a str, &'a str)>, |
| 6600 | ) -> std::collections::BTreeMap<String, String> { |
| 6601 | let mut resolved: std::collections::BTreeMap<String, Option<String>> = |
| 6602 | std::collections::BTreeMap::new(); |
| 6603 | for (server, tool) in pairs { |
| 6604 | match resolved.entry(Self::mcp_model_tool_name(server, tool)) { |
| 6605 | std::collections::btree_map::Entry::Vacant(entry) => { |
| 6606 | entry.insert(Some(server.to_string())); |
| 6607 | } |
| 6608 | std::collections::btree_map::Entry::Occupied(mut entry) => { |
| 6609 | entry.insert(None); |
| 6610 | } |
| 6611 | } |
| 6612 | } |
| 6613 | resolved |
| 6614 | .into_iter() |
| 6615 | .filter_map(|(name, server)| server.map(|server| (name, server))) |
| 6616 | .collect() |
| 6617 | } |
| 6618 | |
| 6619 | /// Model tool name -> owning server name, for the tools this pool actually |
| 6620 | /// resolved. Names the pool did not resolve are simply absent, so callers |
| 6621 | /// report them as unknown instead of parsing `mcp_{server}_{tool}` (a |
| 6622 | /// server name may itself contain `_`, so that split is a guess). |
| 6623 | /// |
| 6624 | /// Read-only projection used by tool inspection; it never connects or |
| 6625 | /// executes. |
| 6626 | #[must_use] |
| 6627 | pub fn resolved_tool_servers(&self) -> std::collections::BTreeMap<String, String> { |
| 6628 | Self::resolve_tool_server_map(self.connections.iter().flat_map(|(server, conn)| { |
| 6629 | let authorized = self.server_allowed(server) && conn.catalog_authorized(); |
| 6630 | conn.tools().iter().filter_map(move |tool| { |
| 6631 | (authorized |
| 6632 | && conn.config().is_tool_enabled(&tool.name) |
| 6633 | && self.tool_allowed(&Self::mcp_model_tool_name(server, &tool.name))) |
| 6634 | .then_some((server.as_str(), tool.name.as_str())) |
| 6635 | }) |
| 6636 | })) |
| 6637 | } |
| 6638 | |
| 6639 | /// Guidance from connected servers that may be put in front of the model, |
| 6640 | /// as `(server, instructions)` sorted by server name. |
| 6641 | /// |
| 6642 | /// A server qualifies only when it is ready, allowed and still authorized |
| 6643 | /// (the same gates as [`Self::resolved_tool_servers`]), supplied non-empty |
| 6644 | /// instructions, and owns at least one enabled tool for which |
| 6645 | /// `model_visible` holds — the caller passes the turn's final catalog, so |
| 6646 | /// a server whose tools are all denied by the permission posture |
| 6647 | /// contributes nothing. |
| 6648 | #[must_use] |
| 6649 | pub fn model_server_instructions( |
| 6650 | &self, |
| 6651 | model_visible: impl Fn(&str) -> bool, |
| 6652 | ) -> Vec<(String, String)> { |
| 6653 | self.model_server_instructions_for(model_visible, None, &self.resolved_tool_servers()) |
| 6654 | .0 |
| 6655 | } |
| 6656 | |
| 6657 | pub(crate) fn model_server_instructions_for( |
| 6658 | &self, |
| 6659 | model_visible: impl Fn(&str) -> bool, |
| 6660 | composition: Option<&str>, |
| 6661 | routes: &std::collections::BTreeMap<String, String>, |
| 6662 | ) -> (Vec<(String, String)>, Vec<String>) { |
| 6663 | let mut allowed_members = Vec::new(); |
| 6664 | let servers: BTreeSet<String> = routes |
| 6665 | .iter() |
| 6666 | .filter(|(tool, _)| model_visible(tool)) |
| 6667 | .map(|(_, server)| server.clone()) |
| 6668 | .collect(); |
| 6669 | let instructions = servers |
| 6670 | .into_iter() |
| 6671 | .filter_map(|server| { |
| 6672 | let conn = self.connections.get(&server)?; |
| 6673 | if conn.catalog_generation != self.current_catalog_generation() || !conn.is_ready() |
| 6674 | { |
| 6675 | return None; |
| 6676 | } |
| 6677 | let guidance = conn.instructions().unwrap_or_default(); |
| 6678 | let batch = composition.filter(|name| { |
| 6679 | routes.get(*name) == Some(&server) && model_visible(name) |
| 6680 | }); |
| 6681 | let mut text = String::new(); |
| 6682 | if let Some((name, members)) = batch.and_then(|name| { |
| 6683 | conn.tools().iter() |
| 6684 | .find(|t| Self::mcp_model_tool_name(&server, &t.name) == name) |
| 6685 | .and_then(|t| named_batch_members(&t.input_schema)) |
| 6686 | .map(|(_, members)| (name, members)) |
| 6687 | }) { |
| 6688 | let available: Vec<_> = members.iter().filter_map(|member| { |
| 6689 | let member = member.as_str()?; |
| 6690 | let qualified = Self::mcp_model_tool_name(&server, member); |
| 6691 | (routes.get(&qualified) == Some(&server) && model_visible(&qualified) |
| 6692 | && !crate::tools::approval_cache::computer_use_human_decision_tool(&qualified)) |
| 6693 | .then(|| conn.tools().iter().find(|t| t.name == member))? |
| 6694 | }).collect(); |
| 6695 | if available.is_empty() { |
| 6696 | return (!guidance.is_empty()).then(|| (server, guidance.to_string())); |
| 6697 | } |
| 6698 | text.push_str(&format!("Use execute_tools with batch={{tool:\"{name}\",arguments:{{...}}}} for known steps. Put the requested sequence and its postconditions together in one call when no new decision is needed. Use code to branch on intermediate results. Stop on refusal or uncertain delivery. ")); |
| 6699 | if conn.config().reviewed_plugin_source().is_some_and(|source| source.plugin_name() == "computer-use") |
| 6700 | && available.iter().any(|member| member.name == "open_application") |
| 6701 | { |
| 6702 | text.push_str("For a named Mac app, bind it first with open_application using the requested pid (or name/bundle_id) and activate:false. An app_ref read does not bind input. Named find selectors resolve a fresh target during the action, so known labels do not need a separate discovery turn. Use a selector per target field; any app_ref belongs inside each selector. Verify the requested effects in the same app; scope the final observe to its app_ref. "); |
| 6703 | } |
| 6704 | text.push_str("Member arguments (? optional):"); |
| 6705 | for tool in available { |
| 6706 | allowed_members.push(tool.name.clone()); |
| 6707 | if let Some(signature) = batch_member_signature(tool) |
| 6708 | && text.len() + signature.len() < 2304 |
| 6709 | { |
| 6710 | text.push(' '); |
| 6711 | text.push_str(&signature); |
| 6712 | } |
| 6713 | } |
| 6714 | text.push('\n'); |
| 6715 | } |
| 6716 | text.push_str(guidance); |
| 6717 | (!text.is_empty()).then_some((server, text)) |
| 6718 | }) |
| 6719 | .collect(); |
| 6720 | (instructions, allowed_members) |
| 6721 | } |
| 6722 | |
| 6723 | /// Insert a ready, idle connection with the given tools and guidance, for |
| 6724 | /// tests outside this module that need a pool without spawning a server. |
| 6725 | #[cfg(any(test, feature = "test-support"))] |
| 6726 | pub fn insert_test_connection( |
| 6727 | &mut self, |
| 6728 | server: &str, |
| 6729 | tools: &[&str], |
| 6730 | instructions: Option<&str>, |
| 6731 | ) { |
| 6732 | struct IdleTransport; |
| 6733 | #[async_trait::async_trait] |
| 6734 | impl McpTransport for IdleTransport { |
| 6735 | async fn send(&mut self, _msg: Vec<u8>) -> Result<()> { |
| 6736 | Ok(()) |
| 6737 | } |
| 6738 | async fn recv(&mut self) -> Result<Vec<u8>> { |
| 6739 | anyhow::bail!("idle test transport has no responses") |
| 6740 | } |
| 6741 | } |
| 6742 | let config: McpServerConfig = serde_json::from_value(serde_json::json!({ |
| 6743 | "command": "codewhale-test-idle-mcp" |
| 6744 | })) |
| 6745 | .expect("minimal server config"); |
| 6746 | let conn = McpConnection { |
| 6747 | auth_context: Arc::clone(&self.auth_context), |
| 6748 | name: server.to_string(), |
| 6749 | transport: Box::new(IdleTransport), |
| 6750 | tools: tools |
| 6751 | .iter() |
| 6752 | .map(|name| McpTool { |
| 6753 | name: (*name).to_string(), |
| 6754 | description: None, |
| 6755 | input_schema: serde_json::json!({"type": "object"}), |
| 6756 | annotations: None, |
| 6757 | }) |
| 6758 | .collect(), |
| 6759 | resources: Vec::new(), |
| 6760 | resource_templates: Vec::new(), |
| 6761 | prompts: Vec::new(), |
| 6762 | skills: Vec::new(), |
| 6763 | skills_extension: false, |
| 6764 | request_id: AtomicU64::new(1), |
| 6765 | state: ConnectionState::Ready, |
| 6766 | config, |
| 6767 | runtime_registration: None, |
| 6768 | server_capabilities: None, |
| 6769 | instructions: instructions.map(str::to_string), |
| 6770 | discovery_timeout: Duration::from_secs(1), |
| 6771 | read_timeout_secs: 1, |
| 6772 | cancel_token: tokio_util::sync::CancellationToken::new(), |
| 6773 | authority_revocation_reason: Arc::new(std::sync::Mutex::new(None)), |
| 6774 | authority_watch: None, |
| 6775 | catalog_generation: self.current_catalog_generation(), |
| 6776 | catalog_revision: 0, |
| 6777 | catalog_fresh_until: None, |
| 6778 | catalog_stale: false, |
| 6779 | decision_key: None, |
| 6780 | call_lane: None, |
| 6781 | }; |
| 6782 | self.connections.insert(server.to_string(), conn); |
| 6783 | } |
| 6784 | |
| 6785 | /// Get all discovered tools with server-prefixed names |
| 6786 | pub fn all_tools(&self) -> Vec<(String, &McpTool)> { |
| 6787 | let mut by_name: std::collections::BTreeMap<String, Option<&McpTool>> = |
| 6788 | std::collections::BTreeMap::new(); |
| 6789 | for (server, conn) in &self.connections { |
| 6790 | if !self.server_allowed(server) || !conn.catalog_authorized() { |
| 6791 | continue; |
| 6792 | } |
| 6793 | for tool in conn.tools() { |
| 6794 | if !conn.config().is_tool_enabled(&tool.name) { |
| 6795 | continue; |
| 6796 | } |
| 6797 | let name = Self::mcp_model_tool_name(server, &tool.name); |
| 6798 | if !self.tool_allowed(&name) { |
| 6799 | continue; |
| 6800 | } |
| 6801 | match by_name.entry(name.clone()) { |
| 6802 | std::collections::btree_map::Entry::Vacant(entry) => { |
| 6803 | entry.insert(Some(tool)); |
| 6804 | } |
| 6805 | std::collections::btree_map::Entry::Occupied(mut entry) => { |
| 6806 | tracing::warn!( |
| 6807 | target: "mcp", |
| 6808 | model_tool = %name, |
| 6809 | "hiding ambiguous MCP model tool name" |
| 6810 | ); |
| 6811 | entry.insert(None); |
| 6812 | } |
| 6813 | } |
| 6814 | } |
| 6815 | } |
| 6816 | by_name |
| 6817 | .into_iter() |
| 6818 | .filter_map(|(name, tool)| tool.map(|tool| (name, tool))) |
| 6819 | .collect() |
| 6820 | } |
| 6821 | |
| 6822 | /// Get all discovered resources with server-prefixed names |
| 6823 | pub fn all_resources(&self) -> Vec<(String, &McpResource)> { |
| 6824 | let mut resources = Vec::new(); |
| 6825 | for (server, conn) in &self.connections { |
| 6826 | if !self.server_allowed(server) || !conn.catalog_authorized() { |
| 6827 | continue; |
| 6828 | } |
| 6829 | for resource in conn.resources() { |
| 6830 | // Format: mcp_{server}_{resource_name} |
| 6831 | // Note: resource names might contain spaces, we should probably slugify them |
| 6832 | let safe_name = resource.name.replace(' ', "_").to_lowercase(); |
| 6833 | resources.push((format!("mcp_{server}_{safe_name}"), resource)); |
| 6834 | } |
| 6835 | } |
| 6836 | resources |
| 6837 | } |
| 6838 | |
| 6839 | /// Get all discovered resource templates with server-prefixed names |
| 6840 | pub fn all_resource_templates(&self) -> Vec<(String, &McpResourceTemplate)> { |
| 6841 | let mut templates = Vec::new(); |
| 6842 | for (server, conn) in &self.connections { |
| 6843 | if !self.server_allowed(server) || !conn.catalog_authorized() { |
| 6844 | continue; |
| 6845 | } |
| 6846 | for template in conn.resource_templates() { |
| 6847 | let safe_name = template.name.replace(' ', "_").to_lowercase(); |
| 6848 | templates.push((format!("mcp_{server}_{safe_name}"), template)); |
| 6849 | } |
| 6850 | } |
| 6851 | templates |
| 6852 | } |
| 6853 | |
| 6854 | async fn list_resources(&mut self, server: Option<String>) -> Result<Vec<serde_json::Value>> { |
| 6855 | if let Some(server_name) = server { |
| 6856 | let conn = self.get_or_connect(&server_name).await?; |
| 6857 | let resources = conn |
| 6858 | .resources() |
| 6859 | .iter() |
| 6860 | .map(|resource| { |
| 6861 | serde_json::json!({ |
| 6862 | "server": server_name.clone(), |
| 6863 | "uri": resource.uri, |
| 6864 | "name": resource.name, |
| 6865 | "description": resource.description, |
| 6866 | "mime_type": resource.mime_type, |
| 6867 | }) |
| 6868 | }) |
| 6869 | .chain(conn.skill_items(&server_name)) |
| 6870 | .collect(); |
| 6871 | return Ok(resources); |
| 6872 | } |
| 6873 | |
| 6874 | if let Err(error) = self.reload_if_config_changed().await { |
| 6875 | tracing::warn!("MCP config reload check failed: {error:#}"); |
| 6876 | } |
| 6877 | Ok(self.connected_resource_items(false, &[])) |
| 6878 | } |
| 6879 | |
| 6880 | async fn list_resource_templates( |
| 6881 | &mut self, |
| 6882 | server: Option<String>, |
| 6883 | ) -> Result<Vec<serde_json::Value>> { |
| 6884 | if let Some(server_name) = server { |
| 6885 | let conn = self.get_or_connect(&server_name).await?; |
| 6886 | let templates = conn |
| 6887 | .resource_templates() |
| 6888 | .iter() |
| 6889 | .map(|template| { |
| 6890 | serde_json::json!({ |
| 6891 | "server": server_name.clone(), |
| 6892 | "uri_template": template.uri_template, |
| 6893 | "name": template.name, |
| 6894 | "description": template.description, |
| 6895 | "mime_type": template.mime_type, |
| 6896 | }) |
| 6897 | }) |
| 6898 | .collect(); |
| 6899 | return Ok(templates); |
| 6900 | } |
| 6901 | |
| 6902 | if let Err(error) = self.reload_if_config_changed().await { |
| 6903 | tracing::warn!("MCP config reload check failed: {error:#}"); |
| 6904 | } |
| 6905 | Ok(self.connected_resource_items(true, &[])) |
| 6906 | } |
| 6907 | |
| 6908 | fn connected_resource_items( |
| 6909 | &self, |
| 6910 | templates: bool, |
| 6911 | rules: &[String], |
| 6912 | ) -> Vec<serde_json::Value> { |
| 6913 | let mut items: Vec<serde_json::Value> = self |
| 6914 | .enabled_server_names() |
| 6915 | .into_iter() |
| 6916 | .filter(|server| { |
| 6917 | !Self::server_denied_by(rules, server) |
| 6918 | && !self |
| 6919 | .connections |
| 6920 | .get(server) |
| 6921 | .is_some_and(McpConnection::is_ready) |
| 6922 | }) |
| 6923 | .filter_map(|server| { |
| 6924 | if self.server_needs_auth(&server) { |
| 6925 | return Some(self.mcp_auth_required_error_item(&server)); |
| 6926 | } |
| 6927 | let backoff = self.connect_backoff.get(&server)?; |
| 6928 | self.mcp_recovery_error_item(&server, &anyhow::anyhow!(backoff.last_error.clone())) |
| 6929 | }) |
| 6930 | .collect(); |
| 6931 | for (server, conn) in &self.connections { |
| 6932 | if !self.server_allowed(server) |
| 6933 | || Self::server_denied_by(rules, server) |
| 6934 | || !conn.catalog_authorized() |
| 6935 | { |
| 6936 | continue; |
| 6937 | } |
| 6938 | if templates { |
| 6939 | items.extend(conn.resource_templates().iter().map(|template| { |
| 6940 | serde_json::json!({ |
| 6941 | "server": server, |
| 6942 | "uri_template": template.uri_template, |
| 6943 | "name": template.name, |
| 6944 | "description": template.description, |
| 6945 | "mime_type": template.mime_type, |
| 6946 | }) |
| 6947 | })); |
| 6948 | } else { |
| 6949 | items.extend(conn.resources().iter().map(|resource| { |
| 6950 | serde_json::json!({ |
| 6951 | "server": server, |
| 6952 | "uri": resource.uri, |
| 6953 | "name": resource.name, |
| 6954 | "description": resource.description, |
| 6955 | "mime_type": resource.mime_type, |
| 6956 | }) |
| 6957 | })); |
| 6958 | items.extend(conn.skill_items(server)); |
| 6959 | } |
| 6960 | } |
| 6961 | items |
| 6962 | } |
| 6963 | |
| 6964 | /// Project recoverable connection failures for every resource listing. |
| 6965 | /// AWS CLI credentials cannot be renewed by the synthetic OAuth tool. |
| 6966 | fn mcp_recovery_error_item( |
| 6967 | &self, |
| 6968 | server: &str, |
| 6969 | error: &anyhow::Error, |
| 6970 | ) -> Option<serde_json::Value> { |
| 6971 | let text = format!("{error:#}"); |
| 6972 | if let Some(config) = self.server_config(server) |
| 6973 | && mcp_error_is_aws_login(&text, mcp_server_oauth_capable(&config)) |
| 6974 | { |
| 6975 | return Some(serde_json::json!({ |
| 6976 | "error": "aws_login_required", |
| 6977 | "server": server, |
| 6978 | "message": aws_login_hint(&config, server, &text), |
| 6979 | })); |
| 6980 | } |
| 6981 | self.error_needs_oauth_login(server, error) |
| 6982 | .then(|| self.mcp_auth_required_error_item(server)) |
| 6983 | } |
| 6984 | |
| 6985 | /// Listing-time error item for a needs-auth server. Carries the same |
| 6986 | /// recovery the tool-call path names (the synthetic authenticate tool |
| 6987 | /// when OAuth-servable) so a resource or prompt listing never dead-ends |
| 6988 | /// on a login the model could have self-served. |
| 6989 | fn mcp_auth_required_error_item(&self, server: &str) -> serde_json::Value { |
| 6990 | let mut item = serde_json::json!({ |
| 6991 | "error": "authentication_required", |
| 6992 | "server": server, |
| 6993 | "message": self.auth_required_hint(server), |
| 6994 | }); |
| 6995 | let tool_name = Self::mcp_model_tool_name(server, AUTHENTICATE_TOOL_NAME); |
| 6996 | if self.authenticate_tool_target(&tool_name).is_some() { |
| 6997 | item["authenticate_tool"] = serde_json::Value::String(tool_name); |
| 6998 | } |
| 6999 | item |
| 7000 | } |
| 7001 | |
| 7002 | /// Get all discovered prompts with server-prefixed names |
| 7003 | pub fn all_prompts(&self) -> Vec<(String, &McpPrompt)> { |
| 7004 | let mut prompts = Vec::new(); |
| 7005 | for (server, conn) in &self.connections { |
| 7006 | if !self.server_allowed(server) || !conn.catalog_authorized() { |
| 7007 | continue; |
| 7008 | } |
| 7009 | for prompt in conn.prompts() { |
| 7010 | // Format: mcp_{server}_{prompt} |
| 7011 | prompts.push((format!("mcp_{}_{}", server, prompt.name), prompt)); |
| 7012 | } |
| 7013 | } |
| 7014 | prompts |
| 7015 | } |
| 7016 | |
| 7017 | /// Read a resource from a specific server |
| 7018 | pub async fn read_resource( |
| 7019 | &mut self, |
| 7020 | server_name: &str, |
| 7021 | uri: &str, |
| 7022 | ) -> Result<serde_json::Value> { |
| 7023 | let global_timeouts = self.config.timeouts; |
| 7024 | let conn = self.get_or_connect(server_name).await?; |
| 7025 | let skill_file = conn.skill_file(uri); |
| 7026 | let advertised_literal = conn.resources().iter().any(|resource| resource.uri == uri); |
| 7027 | let advertised_template = conn |
| 7028 | .resource_templates() |
| 7029 | .iter() |
| 7030 | .any(|template| resource_uri_matches_template(uri, &template.uri_template)); |
| 7031 | if !advertised_literal && !advertised_template && skill_file.is_none() { |
| 7032 | anyhow::bail!("MCP resource URI '{uri}' was not advertised by server '{server_name}'"); |
| 7033 | } |
| 7034 | let timeout = conn.config().effective_read_timeout(&global_timeouts); |
| 7035 | let result = conn |
| 7036 | .read_resource(uri, timeout) |
| 7037 | .await |
| 7038 | .map_err(|error| self.note_live_call_failure(server_name, error))?; |
| 7039 | if let Some(file) = skill_file { |
| 7040 | verify_mcp_skill_file(&file, &result)?; |
| 7041 | } |
| 7042 | Ok(result) |
| 7043 | } |
| 7044 | |
| 7045 | /// Get a prompt from a specific server |
| 7046 | pub async fn get_prompt( |
| 7047 | &mut self, |
| 7048 | server_name: &str, |
| 7049 | prompt_name: &str, |
| 7050 | arguments: serde_json::Value, |
| 7051 | ) -> Result<serde_json::Value> { |
| 7052 | let global_timeouts = self.config.timeouts; |
| 7053 | let conn = self.get_or_connect(server_name).await?; |
| 7054 | if !conn |
| 7055 | .prompts() |
| 7056 | .iter() |
| 7057 | .any(|prompt| prompt.name == prompt_name) |
| 7058 | { |
| 7059 | anyhow::bail!( |
| 7060 | "MCP prompt '{prompt_name}' was not advertised by server '{server_name}'" |
| 7061 | ); |
| 7062 | } |
| 7063 | let timeout = conn.config().effective_execute_timeout(&global_timeouts); |
| 7064 | conn.get_prompt(prompt_name, arguments, timeout) |
| 7065 | .await |
| 7066 | .map_err(|error| self.note_live_call_failure(server_name, error)) |
| 7067 | } |
| 7068 | |
| 7069 | pub(crate) fn tool_is_disabled(&self, name: &str) -> bool { |
| 7070 | if matches!(name, "mcp_read_resource" | "mcp_get_prompt") { |
| 7071 | return false; |
| 7072 | } |
| 7073 | if let Ok((server, tool)) = self.parse_prefixed_name(name) |
| 7074 | && let Some(current) = self.server_config(&server) |
| 7075 | && current.is_enabled() |
| 7076 | && current.is_tool_enabled(&tool) |
| 7077 | && let Some(connection) = self.connections.get(&server) |
| 7078 | && connection.is_ready() |
| 7079 | && current.runtime_added == connection.config().runtime_added |
| 7080 | && mcp_configured_server_identity(self.config.timeouts, &server, ¤t) |
| 7081 | == mcp_configured_server_identity( |
| 7082 | self.config.timeouts, |
| 7083 | &server, |
| 7084 | connection.config(), |
| 7085 | ) |
| 7086 | { |
| 7087 | return false; |
| 7088 | } |
| 7089 | if let Some(server) = self.authenticate_tool_target(name) |
| 7090 | && self.server_config(&server).is_some_and(|current| { |
| 7091 | current.is_enabled() && oauth::server_supports_oauth_login(¤t) |
| 7092 | }) |
| 7093 | { |
| 7094 | return false; |
| 7095 | } |
| 7096 | let dynamic = self.dynamic_servers.read(); |
| 7097 | self.config |
| 7098 | .servers |
| 7099 | .iter() |
| 7100 | .chain( |
| 7101 | dynamic |
| 7102 | .iter() |
| 7103 | .filter(|(server, _)| !self.config.servers.contains_key(*server)), |
| 7104 | ) |
| 7105 | .any(|(server, config)| { |
| 7106 | config |
| 7107 | .disabled_tools |
| 7108 | .iter() |
| 7109 | .any(|tool| Self::mcp_model_tool_name(server, tool) == name) |
| 7110 | }) |
| 7111 | } |
| 7112 | |
| 7113 | pub(crate) fn delegated_read(&self, name: &str) -> Option<Arc<DelegatedMcpRead>> { |
| 7114 | if self.config_sources.is_empty() || self.config.delegated_operations.is_empty() { |
| 7115 | return None; |
| 7116 | } |
| 7117 | let (server, tool) = self.parse_prefixed_name(name).ok()?; |
| 7118 | self.delegated_read_for(name, &server, &tool) |
| 7119 | } |
| 7120 | |
| 7121 | pub(crate) fn delegated_read_for( |
| 7122 | &self, |
| 7123 | name: &str, |
| 7124 | server: &str, |
| 7125 | tool: &str, |
| 7126 | ) -> Option<Arc<DelegatedMcpRead>> { |
| 7127 | let declaration = self.config.delegated_operations.get(server)?.get(tool)?; |
| 7128 | let conn = self.connections.get(server)?; |
| 7129 | let configured = self.config.servers.get(server)?; |
| 7130 | if declaration.effect != codewhale_mcp::config::McpOperationEffect::Read |
| 7131 | || self.config_sources.is_empty() |
| 7132 | || !self.server_allowed(server) |
| 7133 | || !self.tool_allowed(name) |
| 7134 | || !conn.catalog_authorized() |
| 7135 | || !conn.is_ready() |
| 7136 | || !configured.is_enabled() |
| 7137 | || !configured.is_tool_enabled(tool) |
| 7138 | || declaration.allowed_arguments.is_empty() |
| 7139 | || !declaration |
| 7140 | .allowed_arguments |
| 7141 | .iter() |
| 7142 | .all(serde_json::Value::is_object) |
| 7143 | || static_mcp_binding(configured).as_ref() != Some(&declaration.binding_sha256) |
| 7144 | || static_mcp_binding(conn.config()).as_ref() != Some(&declaration.binding_sha256) |
| 7145 | { |
| 7146 | return None; |
| 7147 | } |
| 7148 | let route = self |
| 7149 | .capture_tool_route(server.to_owned(), tool.to_owned()) |
| 7150 | .ok()?; |
| 7151 | if route.tool.input_schema != declaration.input_schema |
| 7152 | || route |
| 7153 | .tool |
| 7154 | .annotations |
| 7155 | .is_some_and(|hint| hint.destructive_hint == Some(true)) |
| 7156 | || self.authenticate_tool_target(name).is_some() |
| 7157 | { |
| 7158 | return None; |
| 7159 | } |
| 7160 | Some(Arc::new(DelegatedMcpRead { |
| 7161 | route, |
| 7162 | lifetime: conn.cancel_token.clone(), |
| 7163 | instance: Arc::clone(&conn.authority_revocation_reason), |
| 7164 | grant: declaration.clone(), |
| 7165 | })) |
| 7166 | } |
| 7167 | |
| 7168 | #[cfg(test)] |
| 7169 | pub(crate) async fn call_delegated_read( |
| 7170 | &mut self, |
| 7171 | expected: &DelegatedMcpRead, |
| 7172 | name: &str, |
| 7173 | input: serde_json::Value, |
| 7174 | rules: &[String], |
| 7175 | ) -> Result<serde_json::Value> { |
| 7176 | self.admit_delegated_read(expected, name, &input, rules)?; |
| 7177 | let conn = self |
| 7178 | .connections |
| 7179 | .get_mut(&expected.route.server_name) |
| 7180 | .context("delegated connector is unavailable")?; |
| 7181 | let timeout = conn |
| 7182 | .config() |
| 7183 | .effective_execute_timeout(&self.config.timeouts); |
| 7184 | conn.call_tool_decided(&expected.route.tool.name, input, timeout, None) |
| 7185 | .await |
| 7186 | } |
| 7187 | |
| 7188 | async fn begin_delegated_read( |
| 7189 | &mut self, |
| 7190 | expected: &DelegatedMcpRead, |
| 7191 | name: &str, |
| 7192 | input: &serde_json::Value, |
| 7193 | rules: &[String], |
| 7194 | turn: Option<McpCallTurn>, |
| 7195 | ) -> Result<McpToolCallStep> { |
| 7196 | self.admit_delegated_read(expected, name, input, rules)?; |
| 7197 | let conn = self |
| 7198 | .connections |
| 7199 | .get_mut(&expected.route.server_name) |
| 7200 | .context("delegated connector is unavailable")?; |
| 7201 | let timeout = conn |
| 7202 | .config() |
| 7203 | .effective_execute_timeout(&self.config.timeouts); |
| 7204 | match conn.lease_for_call(turn).await { |
| 7205 | Ok(leased) => Ok(McpToolCallStep::Call(Box::new(McpLeasedCall { |
| 7206 | leased, |
| 7207 | action: McpLeasedAction::Tool { |
| 7208 | route: Box::new(expected.route.clone()), |
| 7209 | arguments: input.clone(), |
| 7210 | }, |
| 7211 | timeout, |
| 7212 | final_attempt: true, |
| 7213 | }))), |
| 7214 | Err(lane) => Ok(McpToolCallStep::Wait(McpCallQueue { lane, retry: None })), |
| 7215 | } |
| 7216 | } |
| 7217 | |
| 7218 | fn admit_delegated_read( |
| 7219 | &mut self, |
| 7220 | expected: &DelegatedMcpRead, |
| 7221 | name: &str, |
| 7222 | input: &serde_json::Value, |
| 7223 | rules: &[String], |
| 7224 | ) -> Result<()> { |
| 7225 | Self::authorize_call(&self.disallowed_tools, name, input)?; |
| 7226 | Self::authorize_call(rules, name, input)?; |
| 7227 | self.reload_from_config_sources(ConfigRefresh::VerifyContents)?; |
| 7228 | let current = self |
| 7229 | .delegated_read(name) |
| 7230 | .context("delegated connector binding is stale")?; |
| 7231 | anyhow::ensure!( |
| 7232 | expected.current() |
| 7233 | && Arc::ptr_eq(&expected.instance, ¤t.instance) |
| 7234 | && current.route.server_name == expected.route.server_name |
| 7235 | && current.route.tool == expected.route.tool |
| 7236 | && current.route.catalog_generation == expected.route.catalog_generation |
| 7237 | && current.route.catalog_revision == expected.route.catalog_revision |
| 7238 | && current.grant == expected.grant, |
| 7239 | "delegated connector binding changed" |
| 7240 | ); |
| 7241 | anyhow::ensure!( |
| 7242 | expected.permits_arguments(input), |
| 7243 | "delegated connector disclosure denied" |
| 7244 | ); |
| 7245 | Ok(()) |
| 7246 | } |
| 7247 | |
| 7248 | pub(crate) fn always_allow_binding(&self, name: &str) -> Option<u64> { |
| 7249 | let (server, tool) = self.parse_prefixed_name(name).ok()?; |
| 7250 | let cfg = self.config.servers.get(&server)?; |
| 7251 | (cfg.reviewed_plugin.is_none() && cfg.is_tool_always_allowed(&tool)) |
| 7252 | .then_some(self.config_hash) |
| 7253 | } |
| 7254 | |
| 7255 | /// Parse a prefixed name into (server_name, tool_name) |
| 7256 | pub fn parse_prefixed_name(&self, prefixed_name: &str) -> Result<(String, String)> { |
| 7257 | Self::authorize_call( |
| 7258 | &self.disallowed_tools, |
| 7259 | prefixed_name, |
| 7260 | &serde_json::json!({}), |
| 7261 | )?; |
| 7262 | let Some(rest) = prefixed_name.strip_prefix("mcp_") else { |
| 7263 | anyhow::bail!("Invalid MCP tool name: {prefixed_name}"); |
| 7264 | }; |
| 7265 | |
| 7266 | let mut matched: Option<(String, String)> = None; |
| 7267 | for (server, connection) in &self.connections { |
| 7268 | if !self.server_allowed(server) || !connection.catalog_authorized() { |
| 7269 | continue; |
| 7270 | } |
| 7271 | for tool in connection.tools() { |
| 7272 | if !connection.config().is_tool_enabled(&tool.name) |
| 7273 | || format!("{server}_{}", tool.name) != rest |
| 7274 | { |
| 7275 | continue; |
| 7276 | } |
| 7277 | if matched.is_some() { |
| 7278 | anyhow::bail!( |
| 7279 | "Ambiguous MCP tool name '{prefixed_name}' matches more than one server/tool authority" |
| 7280 | ); |
| 7281 | } |
| 7282 | matched = Some((server.clone(), tool.name.clone())); |
| 7283 | } |
| 7284 | } |
| 7285 | if let Some(matched) = matched { |
| 7286 | return Ok(matched); |
| 7287 | } |
| 7288 | |
| 7289 | Err(anyhow::anyhow!("Unknown MCP tool name: {prefixed_name}")) |
| 7290 | } |
| 7291 | |
| 7292 | /// Resolve an MCP tool through an exact advertised catalog. A configured |
| 7293 | /// but lazy server may be connected and asked for `tools/list`; the |
| 7294 | /// requested suffix is never treated as authority on its own. |
| 7295 | async fn resolve_advertised_tool(&mut self, prefixed_name: &str) -> Result<McpToolRoute> { |
| 7296 | Self::authorize_call( |
| 7297 | &self.disallowed_tools, |
| 7298 | prefixed_name, |
| 7299 | &serde_json::json!({}), |
| 7300 | )?; |
| 7301 | if let Ok((server_name, tool_name)) = self.parse_prefixed_name(prefixed_name) { |
| 7302 | return self.capture_tool_route(server_name, tool_name); |
| 7303 | } |
| 7304 | let Some(rest) = prefixed_name.strip_prefix("mcp_") else { |
| 7305 | anyhow::bail!("Invalid MCP tool name: {prefixed_name}"); |
| 7306 | }; |
| 7307 | let mut candidates = { |
| 7308 | let dynamic = self.dynamic_servers.read(); |
| 7309 | self.config |
| 7310 | .servers |
| 7311 | .iter() |
| 7312 | .filter_map(|(name, config)| { |
| 7313 | (config.is_enabled() |
| 7314 | && self.server_allowed(name) |
| 7315 | && rest |
| 7316 | .strip_prefix(name) |
| 7317 | .is_some_and(|suffix| suffix.starts_with('_'))) |
| 7318 | .then_some(name.clone()) |
| 7319 | }) |
| 7320 | .chain(dynamic.iter().filter_map(|(name, config)| { |
| 7321 | (config.is_enabled() |
| 7322 | && self.server_allowed(name) |
| 7323 | && rest |
| 7324 | .strip_prefix(name) |
| 7325 | .is_some_and(|suffix| suffix.starts_with('_'))) |
| 7326 | .then_some(name.clone()) |
| 7327 | })) |
| 7328 | .collect::<Vec<_>>() |
| 7329 | }; |
| 7330 | candidates.sort(); |
| 7331 | candidates.dedup(); |
| 7332 | for server in candidates { |
| 7333 | // Connecting and catalog discovery are the only lazy side effects. |
| 7334 | // A guessed method is never sent to the transport. |
| 7335 | let _ = self.get_or_connect(&server).await?; |
| 7336 | } |
| 7337 | let (server_name, tool_name) = self.parse_prefixed_name(prefixed_name)?; |
| 7338 | self.capture_tool_route(server_name, tool_name) |
| 7339 | } |
| 7340 | |
| 7341 | fn capture_tool_route(&self, server_name: String, tool_name: String) -> Result<McpToolRoute> { |
| 7342 | let connection = self |
| 7343 | .connections |
| 7344 | .get(&server_name) |
| 7345 | .context("advertised MCP connection disappeared during resolution")?; |
| 7346 | let tool = connection |
| 7347 | .tools() |
| 7348 | .iter() |
| 7349 | .find(|tool| tool.name == tool_name) |
| 7350 | .context("advertised MCP operation is no longer available")? |
| 7351 | .clone(); |
| 7352 | let server_identity = |
| 7353 | mcp_configured_server_identity(self.config.timeouts, &server_name, connection.config()); |
| 7354 | Ok(McpToolRoute { |
| 7355 | server_name, |
| 7356 | tool, |
| 7357 | catalog_generation: connection.catalog_generation, |
| 7358 | catalog_revision: connection.catalog_revision, |
| 7359 | server_identity, |
| 7360 | runtime_added: connection.config().runtime_added, |
| 7361 | }) |
| 7362 | } |
| 7363 | |
| 7364 | /// Every model-facing tool name the runtime MCP pool can own right now: |
| 7365 | /// the current `to_api_tools` output plus the synthetic |
| 7366 | /// `mcp_<server>_authenticate` name for every enabled OAuth-servable |
| 7367 | /// server, whether or not it is currently needs-auth. The turn loop |
| 7368 | /// uses this universe to REPLACE the pool's slice of the tool catalog |
| 7369 | /// instead of additively merging it — the synthetic entry must leave |
| 7370 | /// after a login, and dead real tools must leave after a live 401. |
| 7371 | /// The model-visible tool-name universe for an already-built catalog. |
| 7372 | /// |
| 7373 | /// Takes the catalog rather than rebuilding it: `to_api_tools` re-verifies |
| 7374 | /// every reviewed plugin bundle, so calling both meant hashing each bundle |
| 7375 | /// twice per turn to produce two views of one thing — and the two could |
| 7376 | /// disagree if authority drifted between them (#6209). |
| 7377 | pub fn model_tool_names( |
| 7378 | &self, |
| 7379 | api_tools: &[codewhale_models::Tool], |
| 7380 | ) -> std::collections::HashSet<String> { |
| 7381 | let mut names: std::collections::HashSet<String> = |
| 7382 | api_tools.iter().map(|tool| tool.name.clone()).collect(); |
| 7383 | let dynamic = self.dynamic_servers.read(); |
| 7384 | for (server, config) in self.config.servers.iter().chain(dynamic.iter()) { |
| 7385 | if self.server_allowed(server) |
| 7386 | && config.is_enabled() |
| 7387 | && oauth::server_supports_oauth_login(config) |
| 7388 | && self.tool_allowed(&Self::mcp_model_tool_name(server, AUTHENTICATE_TOOL_NAME)) |
| 7389 | { |
| 7390 | names.insert(Self::mcp_model_tool_name(server, AUTHENTICATE_TOOL_NAME)); |
| 7391 | } |
| 7392 | } |
| 7393 | names |
| 7394 | } |
| 7395 | |
| 7396 | /// Record the approval hints for this catalog's tools (CW-11). Every |
| 7397 | /// server this pool lists is rewritten, so a tool whose server lost its |
| 7398 | /// plugin review, or dropped a hint, loses the relaxation with it. |
| 7399 | fn record_tool_approval_hints(&self) { |
| 7400 | let mut hints = MCP_TOOL_APPROVAL_HINTS.write(); |
| 7401 | for (server, conn) in &self.connections { |
| 7402 | let authorized = self.server_allowed(server) && conn.catalog_authorized(); |
| 7403 | let reviewed_plugin = conn.config().reviewed_plugin.is_some(); |
| 7404 | for tool in conn.tools() { |
| 7405 | let name = Self::mcp_model_tool_name(server, &tool.name); |
| 7406 | match approval_hint_for(tool, reviewed_plugin).filter(|_| authorized) { |
| 7407 | Some(hint) => { |
| 7408 | hints.insert(name, hint); |
| 7409 | } |
| 7410 | None => { |
| 7411 | hints.remove(&name); |
| 7412 | } |
| 7413 | } |
| 7414 | } |
| 7415 | } |
| 7416 | } |
| 7417 | |
| 7418 | /// Convert discovered tools to API Tool format |
| 7419 | pub fn to_api_tools(&self) -> Vec<codewhale_models::Tool> { |
| 7420 | self.record_tool_approval_hints(); |
| 7421 | let mut api_tools = Vec::new(); |
| 7422 | // Add regular tools |
| 7423 | for (name, tool) in self.all_tools() { |
| 7424 | let mut input_schema = tool.input_schema.clone(); |
| 7425 | codewhale_models::schema_sanitize::sanitize(&mut input_schema); |
| 7426 | codewhale_models::schema_canonicalize::canonicalize_schema(&mut input_schema); |
| 7427 | api_tools.push(codewhale_models::Tool { |
| 7428 | tool_type: None, |
| 7429 | name, |
| 7430 | description: tool.description.clone().unwrap_or_default(), |
| 7431 | input_schema, |
| 7432 | allowed_callers: Some(vec!["direct".to_string()]), |
| 7433 | defer_loading: Some(false), |
| 7434 | input_examples: None, |
| 7435 | strict: None, |
| 7436 | cache_control: None, |
| 7437 | }); |
| 7438 | } |
| 7439 | |
| 7440 | // A server whose last connect failed auth-required has no real tools |
| 7441 | // to advertise. In their place offer exactly one synthetic |
| 7442 | // `mcp_<server>_authenticate` tool so the model can self-serve the |
| 7443 | // OAuth login instead of dead-ending on the listing's error item. |
| 7444 | // Never shadow a real tool that owns the same model name. |
| 7445 | { |
| 7446 | let dynamic = self.dynamic_servers.read(); |
| 7447 | for server in &self.needs_auth_servers { |
| 7448 | let Some(config) = self |
| 7449 | .config |
| 7450 | .servers |
| 7451 | .get(server) |
| 7452 | .or_else(|| dynamic.get(server)) |
| 7453 | else { |
| 7454 | continue; |
| 7455 | }; |
| 7456 | if !self.server_allowed(server) |
| 7457 | || !config.is_enabled() |
| 7458 | || !oauth::server_supports_oauth_login(config) |
| 7459 | { |
| 7460 | continue; |
| 7461 | } |
| 7462 | let name = Self::mcp_model_tool_name(server, AUTHENTICATE_TOOL_NAME); |
| 7463 | if !self.tool_allowed(&name) { |
| 7464 | continue; |
| 7465 | } |
| 7466 | if api_tools.iter().any(|tool| tool.name == name) { |
| 7467 | continue; |
| 7468 | } |
| 7469 | api_tools.push(codewhale_models::Tool { |
| 7470 | tool_type: None, |
| 7471 | name, |
| 7472 | description: oauth::authenticate_tool_description(server), |
| 7473 | input_schema: serde_json::json!({ |
| 7474 | "type": "object", |
| 7475 | "properties": {} |
| 7476 | }), |
| 7477 | allowed_callers: Some(vec!["direct".to_string()]), |
| 7478 | defer_loading: Some(false), |
| 7479 | input_examples: None, |
| 7480 | strict: None, |
| 7481 | cache_control: None, |
| 7482 | }); |
| 7483 | } |
| 7484 | } |
| 7485 | |
| 7486 | // Only advertise each resource-listing meta-tool when the servers actually |
| 7487 | // expose the corresponding kind. Previously both were injected whenever any |
| 7488 | // MCP server was configured, so tools-only servers left the model with |
| 7489 | // meta-tools that can only ever return empty results — a wasted tool slot |
| 7490 | // and prompt tokens. Gate each on its own non-empty collection, mirroring |
| 7491 | // the `mcp_read_resource` guard below (`!resources.is_empty()`). |
| 7492 | if !self.all_resources().is_empty() { |
| 7493 | api_tools.push(codewhale_models::Tool { |
| 7494 | tool_type: None, |
| 7495 | name: "list_mcp_resources".to_string(), |
| 7496 | description: "List available MCP resources across servers (optionally filtered by server).".to_string(), |
| 7497 | input_schema: serde_json::json!({ |
| 7498 | "type": "object", |
| 7499 | "properties": { |
| 7500 | "server": { "type": "string", "description": "Optional MCP server name to filter by" } |
| 7501 | } |
| 7502 | }), |
| 7503 | allowed_callers: Some(vec!["direct".to_string()]), |
| 7504 | defer_loading: Some(false), |
| 7505 | input_examples: None, |
| 7506 | strict: None, |
| 7507 | cache_control: None, |
| 7508 | }); |
| 7509 | } |
| 7510 | if !self.all_resource_templates().is_empty() { |
| 7511 | api_tools.push(codewhale_models::Tool { |
| 7512 | tool_type: None, |
| 7513 | name: "list_mcp_resource_templates".to_string(), |
| 7514 | description: "List available MCP resource templates across servers (optionally filtered by server).".to_string(), |
| 7515 | input_schema: serde_json::json!({ |
| 7516 | "type": "object", |
| 7517 | "properties": { |
| 7518 | "server": { "type": "string", "description": "Optional MCP server name to filter by" } |
| 7519 | } |
| 7520 | }), |
| 7521 | allowed_callers: Some(vec!["direct".to_string()]), |
| 7522 | defer_loading: Some(false), |
| 7523 | input_examples: None, |
| 7524 | strict: None, |
| 7525 | cache_control: None, |
| 7526 | }); |
| 7527 | } |
| 7528 | |
| 7529 | // Add resource reading tools if resources exist |
| 7530 | let resources = self.all_resources(); |
| 7531 | if !resources.is_empty() { |
| 7532 | api_tools.push(codewhale_models::Tool { |
| 7533 | tool_type: None, |
| 7534 | name: "mcp_read_resource".to_string(), |
| 7535 | description: "Read a resource from an MCP server using its URI".to_string(), |
| 7536 | input_schema: serde_json::json!({ |
| 7537 | "type": "object", |
| 7538 | "properties": { |
| 7539 | "server": { "type": "string", "description": "The name of the MCP server" }, |
| 7540 | "uri": { "type": "string", "description": "The URI of the resource to read" } |
| 7541 | }, |
| 7542 | "required": ["server", "uri"] |
| 7543 | }), |
| 7544 | allowed_callers: Some(vec!["direct".to_string()]), |
| 7545 | defer_loading: Some(false), |
| 7546 | input_examples: None, |
| 7547 | strict: None, |
| 7548 | cache_control: None, |
| 7549 | }); |
| 7550 | api_tools.push(codewhale_models::Tool { |
| 7551 | tool_type: None, |
| 7552 | name: "read_mcp_resource".to_string(), |
| 7553 | description: "Alias for mcp_read_resource.".to_string(), |
| 7554 | input_schema: serde_json::json!({ |
| 7555 | "type": "object", |
| 7556 | "properties": { |
| 7557 | "server": { "type": "string", "description": "The name of the MCP server" }, |
| 7558 | "uri": { "type": "string", "description": "The URI of the resource to read" } |
| 7559 | }, |
| 7560 | "required": ["server", "uri"] |
| 7561 | }), |
| 7562 | allowed_callers: Some(vec!["direct".to_string()]), |
| 7563 | defer_loading: Some(false), |
| 7564 | input_examples: None, |
| 7565 | strict: None, |
| 7566 | cache_control: None, |
| 7567 | }); |
| 7568 | } |
| 7569 | |
| 7570 | // Add prompt getting tools if prompts exist |
| 7571 | let prompts = self.all_prompts(); |
| 7572 | if !prompts.is_empty() { |
| 7573 | api_tools.push(codewhale_models::Tool { |
| 7574 | tool_type: None, |
| 7575 | name: "mcp_get_prompt".to_string(), |
| 7576 | description: "Get a prompt from an MCP server".to_string(), |
| 7577 | input_schema: serde_json::json!({ |
| 7578 | "type": "object", |
| 7579 | "properties": { |
| 7580 | "server": { "type": "string", "description": "The name of the MCP server" }, |
| 7581 | "name": { "type": "string", "description": "The name of the prompt" }, |
| 7582 | "arguments": { |
| 7583 | "type": "object", |
| 7584 | "description": "Optional arguments for the prompt", |
| 7585 | "additionalProperties": { "type": "string" } |
| 7586 | } |
| 7587 | }, |
| 7588 | "required": ["server", "name"] |
| 7589 | }), |
| 7590 | allowed_callers: Some(vec!["direct".to_string()]), |
| 7591 | defer_loading: Some(false), |
| 7592 | input_examples: None, |
| 7593 | strict: None, |
| 7594 | cache_control: None, |
| 7595 | }); |
| 7596 | } |
| 7597 | |
| 7598 | // Sort by name for prefix-cache stability — the tool block sent to |
| 7599 | // the model needs to be deterministic across runs (#1319). |
| 7600 | api_tools.retain(|tool| self.tool_allowed(&tool.name)); |
| 7601 | api_tools.sort_by(|a, b| a.name.cmp(&b.name)); |
| 7602 | api_tools |
| 7603 | } |
| 7604 | |
| 7605 | /// Apply a child's narrower ceiling without changing the shared pool. |
| 7606 | pub async fn call_tool_with_disallowed( |
| 7607 | &mut self, |
| 7608 | name: &str, |
| 7609 | input: serde_json::Value, |
| 7610 | rules: &[String], |
| 7611 | decision: Option<&crate::core::engine::HumanDecision>, |
| 7612 | ) -> Result<serde_json::Value> { |
| 7613 | Self::authorize_call(&self.disallowed_tools, name, &input)?; |
| 7614 | Self::authorize_call(rules, name, &input)?; |
| 7615 | if !rules.is_empty() |
| 7616 | && rules != self.disallowed_tools.as_slice() |
| 7617 | && matches!(name, "list_mcp_resources" | "list_mcp_resource_templates") |
| 7618 | && input |
| 7619 | .get("server") |
| 7620 | .and_then(serde_json::Value::as_str) |
| 7621 | .is_none() |
| 7622 | { |
| 7623 | self.reload_if_config_changed().await?; |
| 7624 | let mut items = |
| 7625 | self.connected_resource_items(name == "list_mcp_resource_templates", rules); |
| 7626 | for item in &mut items { |
| 7627 | if item |
| 7628 | .get("authenticate_tool") |
| 7629 | .and_then(serde_json::Value::as_str) |
| 7630 | .is_some_and(|tool| { |
| 7631 | codewhale_execpolicy::tool_rules::tool_matches_any_rule(rules, tool) |
| 7632 | }) |
| 7633 | { |
| 7634 | item.as_object_mut() |
| 7635 | .expect("error item object") |
| 7636 | .remove("authenticate_tool"); |
| 7637 | item["message"] = serde_json::json!("MCP server requires authentication"); |
| 7638 | } |
| 7639 | } |
| 7640 | let field = if name == "list_mcp_resources" { |
| 7641 | "resources" |
| 7642 | } else { |
| 7643 | "templates" |
| 7644 | }; |
| 7645 | return Ok(serde_json::json!({ field: items })); |
| 7646 | } |
| 7647 | let synthetic_auth = self.authenticate_tool_target(name).is_some(); |
| 7648 | let mut result = self.call_tool_with_decision(name, input, decision).await?; |
| 7649 | if synthetic_auth { |
| 7650 | Self::filter_authenticate_result(&mut result, rules); |
| 7651 | } |
| 7652 | Ok(result) |
| 7653 | } |
| 7654 | |
| 7655 | pub fn filter_authenticate_result(result: &mut serde_json::Value, rules: &[String]) { |
| 7656 | if let Some(tools) = result |
| 7657 | .get_mut("tools") |
| 7658 | .and_then(serde_json::Value::as_array_mut) |
| 7659 | { |
| 7660 | tools.retain(|name| { |
| 7661 | name.as_str().is_some_and(|name| { |
| 7662 | !codewhale_execpolicy::tool_rules::tool_matches_any_rule(rules, name) |
| 7663 | }) |
| 7664 | }); |
| 7665 | } |
| 7666 | } |
| 7667 | |
| 7668 | /// Call a tool by its prefixed name (mcp_{server}_{tool}) |
| 7669 | #[cfg(any(test, feature = "test-support"))] |
| 7670 | pub async fn call_tool( |
| 7671 | &mut self, |
| 7672 | prefixed_name: &str, |
| 7673 | arguments: serde_json::Value, |
| 7674 | ) -> Result<serde_json::Value> { |
| 7675 | self.call_tool_with_decision(prefixed_name, arguments, None) |
| 7676 | .await |
| 7677 | } |
| 7678 | |
| 7679 | /// Call a tool, carrying a person's card decision for this exact call. |
| 7680 | pub async fn call_tool_with_decision( |
| 7681 | &mut self, |
| 7682 | prefixed_name: &str, |
| 7683 | arguments: serde_json::Value, |
| 7684 | decision: Option<&crate::core::engine::HumanDecision>, |
| 7685 | ) -> Result<serde_json::Value> { |
| 7686 | Self::authorize_call(&self.disallowed_tools, prefixed_name, &arguments)?; |
| 7687 | if decision.is_some_and(|decision| !decision.authorizes(prefixed_name, &arguments)) { |
| 7688 | anyhow::bail!("Human approval does not authorize this exact MCP call"); |
| 7689 | } |
| 7690 | if prefixed_name == "list_mcp_resources" { |
| 7691 | let server = arguments |
| 7692 | .get("server") |
| 7693 | .and_then(|v| v.as_str()) |
| 7694 | .map(str::to_string); |
| 7695 | let resources = self.list_resources(server).await?; |
| 7696 | return Ok(serde_json::json!({ "resources": resources })); |
| 7697 | } |
| 7698 | |
| 7699 | if prefixed_name == "list_mcp_resource_templates" { |
| 7700 | let server = arguments |
| 7701 | .get("server") |
| 7702 | .and_then(|v| v.as_str()) |
| 7703 | .map(str::to_string); |
| 7704 | let templates = self.list_resource_templates(server).await?; |
| 7705 | return Ok(serde_json::json!({ "templates": templates })); |
| 7706 | } |
| 7707 | |
| 7708 | if prefixed_name == "mcp_read_resource" { |
| 7709 | let server_name = arguments |
| 7710 | .get("server") |
| 7711 | .and_then(|v| v.as_str()) |
| 7712 | .context("Missing 'server' argument")?; |
| 7713 | let uri = arguments |
| 7714 | .get("uri") |
| 7715 | .and_then(|v| v.as_str()) |
| 7716 | .context("Missing 'uri' argument")?; |
| 7717 | return self.read_resource(server_name, uri).await; |
| 7718 | } |
| 7719 | |
| 7720 | if prefixed_name == "read_mcp_resource" { |
| 7721 | let server_name = arguments |
| 7722 | .get("server") |
| 7723 | .and_then(|v| v.as_str()) |
| 7724 | .context("Missing 'server' argument")?; |
| 7725 | let uri = arguments |
| 7726 | .get("uri") |
| 7727 | .and_then(|v| v.as_str()) |
| 7728 | .context("Missing 'uri' argument")?; |
| 7729 | return self.read_resource(server_name, uri).await; |
| 7730 | } |
| 7731 | |
| 7732 | if prefixed_name == "mcp_get_prompt" { |
| 7733 | let server_name = arguments |
| 7734 | .get("server") |
| 7735 | .and_then(|v| v.as_str()) |
| 7736 | .context("Missing 'server' argument")?; |
| 7737 | let name = arguments |
| 7738 | .get("name") |
| 7739 | .and_then(|v| v.as_str()) |
| 7740 | .context("Missing 'name' argument")?; |
| 7741 | let args = arguments |
| 7742 | .get("arguments") |
| 7743 | .cloned() |
| 7744 | .unwrap_or(serde_json::json!({})); |
| 7745 | return self.get_prompt(server_name, name, args).await; |
| 7746 | } |
| 7747 | |
| 7748 | // Synthetic self-serve OAuth login: `mcp_<server>_authenticate` runs |
| 7749 | // the same flow `/mcp login` uses and reconnects the server on |
| 7750 | // success, so the real tools resolve in this session. |
| 7751 | if let Some(server_name) = self.authenticate_tool_target(prefixed_name) { |
| 7752 | return self.run_authenticate_tool(&server_name).await; |
| 7753 | } |
| 7754 | |
| 7755 | let route = self.resolve_tool_call(prefixed_name).await?; |
| 7756 | let server_name = route.server_name.clone(); |
| 7757 | let tool_name = route.tool.name.clone(); |
| 7758 | // Copy the global timeouts to avoid borrow conflict |
| 7759 | let global_timeouts = self.config.timeouts; |
| 7760 | let conn = self.get_or_connect(&server_name).await?; |
| 7761 | if conn.catalog_revision != route.catalog_revision || !route.permits(conn, global_timeouts) |
| 7762 | { |
| 7763 | anyhow::bail!("MCP operation binding changed after tool resolution; retry the call"); |
| 7764 | } |
| 7765 | let timeout = conn.config().effective_execute_timeout(&global_timeouts); |
| 7766 | let result = match conn |
| 7767 | .call_tool_decided(&tool_name, arguments.clone(), timeout, decision) |
| 7768 | .await |
| 7769 | { |
| 7770 | Ok(result) => Ok(result), |
| 7771 | // A rejected credential is not a stale session: reconnecting |
| 7772 | // replays the same rejection, so it takes the auth-required |
| 7773 | // path below instead of the transparent retry. Only a typed |
| 7774 | // transport-level refusal of the session id proves the server |
| 7775 | // never ran the call, so only that class is replayed. |
| 7776 | Err(err) |
| 7777 | if is_mcp_session_rejected_error(&err) |
| 7778 | && !oauth::error_looks_auth_required(&err) => |
| 7779 | { |
| 7780 | tracing::debug!( |
| 7781 | target: "mcp", |
| 7782 | server = server_name, |
| 7783 | tool = tool_name, |
| 7784 | error = %err, |
| 7785 | "retrying MCP tool call after stale session" |
| 7786 | ); |
| 7787 | self.drop_connection(&server_name, "stale session retry"); |
| 7788 | // No `?` here: a reconnect that fails auth-required must |
| 7789 | // still reach the classification below. |
| 7790 | match self.get_or_connect(&server_name).await { |
| 7791 | Ok(conn) => { |
| 7792 | if decision.is_some() || !route.permits(conn, global_timeouts) { |
| 7793 | Err(anyhow::anyhow!( |
| 7794 | "MCP operation binding changed on reconnect; prepare a new call" |
| 7795 | )) |
| 7796 | } else { |
| 7797 | let timeout = conn.config().effective_execute_timeout(&global_timeouts); |
| 7798 | conn.call_tool_decided(&tool_name, arguments, timeout, decision) |
| 7799 | .await |
| 7800 | } |
| 7801 | } |
| 7802 | // A reconnect that fails must not swallow the call error |
| 7803 | // that triggered it: report both, original first. |
| 7804 | Err(reconnect_err) => Err(anyhow::anyhow!( |
| 7805 | "{err:#}; reconnect failed: {reconnect_err:#}" |
| 7806 | )), |
| 7807 | } |
| 7808 | } |
| 7809 | // The transport died after the request was written, or the |
| 7810 | // server answered this request id with a session error: either |
| 7811 | // way it may already have run the tool, so replaying it could |
| 7812 | // repeat a side effect. Keep the connection as a dead entry, so the |
| 7813 | // supervisor or the next call rebuilds it, and let the caller |
| 7814 | // decide whether to repeat this one. |
| 7815 | Err(err) |
| 7816 | if is_mcp_connection_lost_error(&err) |
| 7817 | && !oauth::error_looks_auth_required(&err) => |
| 7818 | { |
| 7819 | tracing::debug!( |
| 7820 | target: "mcp", |
| 7821 | server = server_name, |
| 7822 | tool = tool_name, |
| 7823 | error = %err, |
| 7824 | "MCP connection lost during tool call; not retrying" |
| 7825 | ); |
| 7826 | if let Some(connection) = self.connections.get_mut(&server_name) { |
| 7827 | connection.transport.shutdown().await; |
| 7828 | connection.close(); |
| 7829 | } |
| 7830 | Err(err.context(format!( |
| 7831 | "MCP server '{server_name}' connection closed during tool call \ |
| 7832 | '{tool_name}'; outcome unknown, not retried" |
| 7833 | ))) |
| 7834 | } |
| 7835 | Err(err) => Err(err), |
| 7836 | }; |
| 7837 | // A credential the server stopped accepting mid-session (revoked or |
| 7838 | // rotated elsewhere, refresh rejected) is the same `◆ auth required` |
| 7839 | // class as a failed connect: land it in the same typed state so the |
| 7840 | // next catalog offers the login tool instead of a dead error. |
| 7841 | result.map_err(|err| self.note_live_call_failure(&server_name, err)) |
| 7842 | } |
| 7843 | |
| 7844 | async fn resolve_tool_call(&mut self, prefixed_name: &str) -> Result<McpToolRoute> { |
| 7845 | match self.resolve_advertised_tool(prefixed_name).await { |
| 7846 | Ok(route) => Ok(route), |
| 7847 | Err(error) => { |
| 7848 | // A real tool name reached a server whose login has lapsed |
| 7849 | // (stale catalog, or a mid-session 401). Name the one call |
| 7850 | // that recovers it instead of leaving a dead error. |
| 7851 | if let Some(server) = self.needs_auth_server_for_tool_name(prefixed_name) { |
| 7852 | return Err(error.context(self.auth_required_hint(&server))); |
| 7853 | } |
| 7854 | Err(error) |
| 7855 | } |
| 7856 | } |
| 7857 | } |
| 7858 | |
| 7859 | fn is_pool_served_tool(&self, name: &str) -> bool { |
| 7860 | matches!( |
| 7861 | name, |
| 7862 | "list_mcp_resources" |
| 7863 | | "list_mcp_resource_templates" |
| 7864 | | "mcp_read_resource" |
| 7865 | | "read_mcp_resource" |
| 7866 | | "mcp_get_prompt" |
| 7867 | ) || self.authenticate_tool_target(name).is_some() |
| 7868 | } |
| 7869 | |
| 7870 | async fn begin_read_resource( |
| 7871 | &mut self, |
| 7872 | server_name: &str, |
| 7873 | uri: &str, |
| 7874 | turn: Option<McpCallTurn>, |
| 7875 | ) -> Result<McpToolCallStep> { |
| 7876 | let global_timeouts = self.config.timeouts; |
| 7877 | let conn = self.get_or_connect(server_name).await?; |
| 7878 | let skill_file = conn.skill_file(uri); |
| 7879 | let advertised_literal = conn.resources().iter().any(|resource| resource.uri == uri); |
| 7880 | let advertised_template = conn |
| 7881 | .resource_templates() |
| 7882 | .iter() |
| 7883 | .any(|template| resource_uri_matches_template(uri, &template.uri_template)); |
| 7884 | if !advertised_literal && !advertised_template && skill_file.is_none() { |
| 7885 | anyhow::bail!("MCP resource URI '{uri}' was not advertised by server '{server_name}'"); |
| 7886 | } |
| 7887 | let timeout = conn.config().effective_read_timeout(&global_timeouts); |
| 7888 | match conn.lease_for_call(turn).await { |
| 7889 | Ok(leased) => Ok(McpToolCallStep::Call(Box::new(McpLeasedCall { |
| 7890 | leased, |
| 7891 | action: McpLeasedAction::ReadResource { |
| 7892 | server_name: server_name.to_string(), |
| 7893 | uri: uri.to_string(), |
| 7894 | skill_file, |
| 7895 | }, |
| 7896 | timeout, |
| 7897 | final_attempt: true, |
| 7898 | }))), |
| 7899 | Err(lane) => Ok(McpToolCallStep::Wait(McpCallQueue { lane, retry: None })), |
| 7900 | } |
| 7901 | } |
| 7902 | |
| 7903 | async fn begin_get_prompt( |
| 7904 | &mut self, |
| 7905 | server_name: &str, |
| 7906 | prompt_name: &str, |
| 7907 | arguments: serde_json::Value, |
| 7908 | turn: Option<McpCallTurn>, |
| 7909 | ) -> Result<McpToolCallStep> { |
| 7910 | let global_timeouts = self.config.timeouts; |
| 7911 | let conn = self.get_or_connect(server_name).await?; |
| 7912 | if !conn |
| 7913 | .prompts() |
| 7914 | .iter() |
| 7915 | .any(|prompt| prompt.name == prompt_name) |
| 7916 | { |
| 7917 | anyhow::bail!( |
| 7918 | "MCP prompt '{prompt_name}' was not advertised by server '{server_name}'" |
| 7919 | ); |
| 7920 | } |
| 7921 | let timeout = conn.config().effective_execute_timeout(&global_timeouts); |
| 7922 | match conn.lease_for_call(turn).await { |
| 7923 | Ok(leased) => Ok(McpToolCallStep::Call(Box::new(McpLeasedCall { |
| 7924 | leased, |
| 7925 | action: McpLeasedAction::GetPrompt { |
| 7926 | server_name: server_name.to_string(), |
| 7927 | prompt_name: prompt_name.to_string(), |
| 7928 | arguments, |
| 7929 | }, |
| 7930 | timeout, |
| 7931 | final_attempt: true, |
| 7932 | }))), |
| 7933 | Err(lane) => Ok(McpToolCallStep::Wait(McpCallQueue { lane, retry: None })), |
| 7934 | } |
| 7935 | } |
| 7936 | |
| 7937 | async fn begin_tool_call( |
| 7938 | &mut self, |
| 7939 | name: &str, |
| 7940 | input: &serde_json::Value, |
| 7941 | rules: &[String], |
| 7942 | decision: Option<&crate::core::engine::HumanDecision>, |
| 7943 | turn: Option<McpCallTurn>, |
| 7944 | retry: Option<Box<McpToolRoute>>, |
| 7945 | ) -> Result<McpToolCallStep> { |
| 7946 | if let Some(route) = retry { |
| 7947 | return self.lease_route(*route, input, decision, turn, true).await; |
| 7948 | } |
| 7949 | Self::authorize_call(&self.disallowed_tools, name, input)?; |
| 7950 | Self::authorize_call(rules, name, input)?; |
| 7951 | if decision.is_some_and(|decision| !decision.authorizes(name, input)) { |
| 7952 | anyhow::bail!("Human approval does not authorize this exact MCP call"); |
| 7953 | } |
| 7954 | if matches!(name, "mcp_read_resource" | "read_mcp_resource") { |
| 7955 | let server_name = input |
| 7956 | .get("server") |
| 7957 | .and_then(|v| v.as_str()) |
| 7958 | .context("Missing 'server' argument")? |
| 7959 | .to_string(); |
| 7960 | let uri = input |
| 7961 | .get("uri") |
| 7962 | .and_then(|v| v.as_str()) |
| 7963 | .context("Missing 'uri' argument")? |
| 7964 | .to_string(); |
| 7965 | return self.begin_read_resource(&server_name, &uri, turn).await; |
| 7966 | } |
| 7967 | if name == "mcp_get_prompt" { |
| 7968 | let server_name = input |
| 7969 | .get("server") |
| 7970 | .and_then(|v| v.as_str()) |
| 7971 | .context("Missing 'server' argument")? |
| 7972 | .to_string(); |
| 7973 | let prompt_name = input |
| 7974 | .get("name") |
| 7975 | .and_then(|v| v.as_str()) |
| 7976 | .context("Missing 'name' argument")? |
| 7977 | .to_string(); |
| 7978 | let args = input |
| 7979 | .get("arguments") |
| 7980 | .cloned() |
| 7981 | .unwrap_or(serde_json::json!({})); |
| 7982 | return self |
| 7983 | .begin_get_prompt(&server_name, &prompt_name, args, turn) |
| 7984 | .await; |
| 7985 | } |
| 7986 | if self.is_pool_served_tool(name) { |
| 7987 | return self |
| 7988 | .call_tool_with_disallowed(name, input.clone(), rules, decision) |
| 7989 | .await |
| 7990 | .map(McpToolCallStep::Done); |
| 7991 | } |
| 7992 | let route = self.resolve_tool_call(name).await?; |
| 7993 | self.lease_route(route, input, decision, turn, false).await |
| 7994 | } |
| 7995 | |
| 7996 | async fn lease_route( |
| 7997 | &mut self, |
| 7998 | route: McpToolRoute, |
| 7999 | input: &serde_json::Value, |
| 8000 | decision: Option<&crate::core::engine::HumanDecision>, |
| 8001 | turn: Option<McpCallTurn>, |
| 8002 | final_attempt: bool, |
| 8003 | ) -> Result<McpToolCallStep> { |
| 8004 | let global_timeouts = self.config.timeouts; |
| 8005 | let attempt = match self.get_or_connect(&route.server_name).await { |
| 8006 | Err(error) => Err(error), |
| 8007 | Ok(conn) => { |
| 8008 | let bound = if final_attempt { |
| 8009 | decision.is_none() && route.permits(conn, global_timeouts) |
| 8010 | } else { |
| 8011 | conn.catalog_revision == route.catalog_revision |
| 8012 | && route.permits(conn, global_timeouts) |
| 8013 | }; |
| 8014 | if bound { |
| 8015 | let timeout = conn.config().effective_execute_timeout(&global_timeouts); |
| 8016 | Ok((timeout, conn.lease_for_call(turn).await)) |
| 8017 | } else if final_attempt { |
| 8018 | Err(anyhow::anyhow!( |
| 8019 | "MCP operation binding changed on reconnect; prepare a new call" |
| 8020 | )) |
| 8021 | } else { |
| 8022 | Err(anyhow::anyhow!( |
| 8023 | "MCP operation binding changed after tool resolution; retry the call" |
| 8024 | )) |
| 8025 | } |
| 8026 | } |
| 8027 | }; |
| 8028 | match attempt { |
| 8029 | Ok((timeout, Ok(leased))) => Ok(McpToolCallStep::Call(Box::new(McpLeasedCall { |
| 8030 | leased, |
| 8031 | action: McpLeasedAction::Tool { |
| 8032 | route: Box::new(route), |
| 8033 | arguments: input.clone(), |
| 8034 | }, |
| 8035 | timeout, |
| 8036 | final_attempt, |
| 8037 | }))), |
| 8038 | Ok((_, Err(lane))) => Ok(McpToolCallStep::Wait(McpCallQueue { |
| 8039 | lane, |
| 8040 | retry: final_attempt.then(|| Box::new(route)), |
| 8041 | })), |
| 8042 | Err(error) if final_attempt => { |
| 8043 | Err(self.note_live_call_failure(&route.server_name, error)) |
| 8044 | } |
| 8045 | Err(error) => Err(error), |
| 8046 | } |
| 8047 | } |
| 8048 | |
| 8049 | async fn finish_tool_call( |
| 8050 | &mut self, |
| 8051 | outcome: McpToolCallOutcome, |
| 8052 | input: &serde_json::Value, |
| 8053 | decision: Option<&crate::core::engine::HumanDecision>, |
| 8054 | ) -> Result<McpToolCallStep> { |
| 8055 | let McpToolCallOutcome { |
| 8056 | result, |
| 8057 | lane, |
| 8058 | target, |
| 8059 | final_attempt, |
| 8060 | } = outcome; |
| 8061 | let err = match result { |
| 8062 | Ok(result) => return Ok(McpToolCallStep::Done(result)), |
| 8063 | Err(err) => err, |
| 8064 | }; |
| 8065 | let route = match target { |
| 8066 | McpCallTarget::Tool(route) => *route, |
| 8067 | McpCallTarget::Helper { server_name, .. } => { |
| 8068 | return Err(self.note_live_call_failure(&server_name, err)); |
| 8069 | } |
| 8070 | }; |
| 8071 | let server_name = route.server_name.clone(); |
| 8072 | let tool_name = route.tool.name.clone(); |
| 8073 | if final_attempt { |
| 8074 | return Err(self.note_live_call_failure(&server_name, err)); |
| 8075 | } |
| 8076 | if is_mcp_session_rejected_error(&err) && !oauth::error_looks_auth_required(&err) { |
| 8077 | tracing::debug!( |
| 8078 | target: "mcp", |
| 8079 | server = server_name, |
| 8080 | tool = tool_name, |
| 8081 | error = %err, |
| 8082 | "retrying MCP tool call after stale session" |
| 8083 | ); |
| 8084 | if self |
| 8085 | .connections |
| 8086 | .get(&server_name) |
| 8087 | .is_some_and(|connection| connection.holds_call_lane(&lane)) |
| 8088 | { |
| 8089 | self.drop_connection(&server_name, "stale session retry"); |
| 8090 | } |
| 8091 | let reconnect = self.get_or_connect(&server_name).await.map(|_| ()); |
| 8092 | if let Err(reconnect_err) = reconnect { |
| 8093 | let error = anyhow::anyhow!("{err:#}; reconnect failed: {reconnect_err:#}"); |
| 8094 | return Err(self.note_live_call_failure(&server_name, error)); |
| 8095 | } |
| 8096 | return self.lease_route(route, input, decision, None, true).await; |
| 8097 | } |
| 8098 | if is_mcp_connection_lost_error(&err) && !oauth::error_looks_auth_required(&err) { |
| 8099 | tracing::debug!( |
| 8100 | target: "mcp", |
| 8101 | server = server_name, |
| 8102 | tool = tool_name, |
| 8103 | error = %err, |
| 8104 | "MCP connection lost during tool call; not retrying" |
| 8105 | ); |
| 8106 | if let Some(connection) = self.connections.get_mut(&server_name) |
| 8107 | && connection.holds_call_lane(&lane) |
| 8108 | { |
| 8109 | connection.transport.shutdown().await; |
| 8110 | connection.close(); |
| 8111 | } |
| 8112 | let err = err.context(format!( |
| 8113 | "MCP server '{server_name}' connection closed during tool call \ |
| 8114 | '{tool_name}'; outcome unknown, not retried" |
| 8115 | )); |
| 8116 | return Err(self.note_live_call_failure(&server_name, err)); |
| 8117 | } |
| 8118 | Err(self.note_live_call_failure(&server_name, err)) |
| 8119 | } |
| 8120 | |
| 8121 | /// Get list of configured server names (static + dynamic) |
| 8122 | #[must_use] |
| 8123 | pub fn subagent_unavailable_tool_reason(&self, model_tool: &str) -> String { |
| 8124 | let routes = self.resolved_tool_servers(); |
| 8125 | let server = routes.get(model_tool).cloned().or_else(|| { |
| 8126 | let dynamic = self.dynamic_servers.read(); |
| 8127 | self.config |
| 8128 | .servers |
| 8129 | .keys() |
| 8130 | .chain(dynamic.keys()) |
| 8131 | .filter(|server| model_tool.starts_with(&Self::mcp_model_tool_name(server, ""))) |
| 8132 | .max_by_key(|server| server.len()) |
| 8133 | .cloned() |
| 8134 | }); |
| 8135 | let Some(server) = server else { |
| 8136 | return format!( |
| 8137 | "MCP tool '{model_tool}' is unavailable to this sub-agent: no MCP server configured for this session owns that name. List this sub-agent's MCP tools before calling one." |
| 8138 | ); |
| 8139 | }; |
| 8140 | let reason = if !self.server_allowed(&server) { |
| 8141 | "is denied by this session's MCP policy".to_string() |
| 8142 | } else if self.needs_auth_servers.contains(&server) { |
| 8143 | format!("needs authorization; run /mcp login {server} in the parent session") |
| 8144 | } else if self.connecting.contains(&server) { |
| 8145 | "was still connecting when this sub-agent's tools were built".to_string() |
| 8146 | } else if routes.contains_key(model_tool) { |
| 8147 | "is connected, but this tool is outside this sub-agent's role or tool scope".to_string() |
| 8148 | } else if self |
| 8149 | .connections |
| 8150 | .get(&server) |
| 8151 | .is_some_and(McpConnection::is_ready) |
| 8152 | { |
| 8153 | "is connected but does not offer this tool (disabled, denied, or not in its catalog)" |
| 8154 | .to_string() |
| 8155 | } else if let Some(backoff) = self.connect_backoff.get(&server) { |
| 8156 | format!("failed to connect: {}", backoff.last_error) |
| 8157 | } else { |
| 8158 | "is configured but not connected in this session".to_string() |
| 8159 | }; |
| 8160 | format!( |
| 8161 | "MCP tool '{model_tool}' is unavailable to this sub-agent: server '{server}' {reason}." |
| 8162 | ) |
| 8163 | } |
| 8164 | |
| 8165 | pub fn server_names(&self) -> Vec<String> { |
| 8166 | let mut names: Vec<String> = self |
| 8167 | .config |
| 8168 | .servers |
| 8169 | .keys() |
| 8170 | .filter(|name| self.server_allowed(name)) |
| 8171 | .cloned() |
| 8172 | .collect(); |
| 8173 | let dynamic = self.dynamic_servers.read(); |
| 8174 | for name in dynamic.keys() { |
| 8175 | if self.server_allowed(name) && !names.contains(name) { |
| 8176 | names.push(name.clone()); |
| 8177 | } |
| 8178 | } |
| 8179 | names |
| 8180 | } |
| 8181 | |
| 8182 | /// Add a runtime server configuration (in-memory only, not persisted). |
| 8183 | /// |
| 8184 | /// This is used for dynamically started MCP servers from chat context. |
| 8185 | /// Stored in `dynamic_servers` so it doesn't interfere with file-based config reload. |
| 8186 | /// |
| 8187 | /// Returns `Err` if a server with the same name already exists as a static config |
| 8188 | /// or a dynamic config. The caller should surface the error to the LLM/user. |
| 8189 | pub fn add_runtime_server_config( |
| 8190 | &self, |
| 8191 | name: String, |
| 8192 | config: McpServerConfig, |
| 8193 | ) -> Result<(), String> { |
| 8194 | self.add_dynamic_server_config(name, config, true) |
| 8195 | } |
| 8196 | |
| 8197 | pub fn add_desktop_browser_server_config( |
| 8198 | &mut self, |
| 8199 | name: String, |
| 8200 | config: McpServerConfig, |
| 8201 | proof: Option<(&str, &str)>, |
| 8202 | ) -> Result<(), String> { |
| 8203 | let owner = self.auth_context.env("CODEWHALE_BROWSER_OWNER_PUBLIC_KEY"); |
| 8204 | self.add_desktop_browser_server_config_for_owner(name, config, proof, owner.as_deref()) |
| 8205 | } |
| 8206 | |
| 8207 | pub fn add_desktop_browser_server_config_for_owner( |
| 8208 | &mut self, |
| 8209 | name: String, |
| 8210 | mut config: McpServerConfig, |
| 8211 | proof: Option<(&str, &str)>, |
| 8212 | owner_public_key: Option<&str>, |
| 8213 | ) -> Result<(), String> { |
| 8214 | use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; |
| 8215 | if !is_desktop_browser_server(&name, &config) { |
| 8216 | return Err("Invalid desktop browser configuration".to_string()); |
| 8217 | } |
| 8218 | let url = config |
| 8219 | .url |
| 8220 | .as_deref() |
| 8221 | .and_then(|url| url::Url::parse(url).ok()) |
| 8222 | .ok_or_else(|| "Invalid desktop browser endpoint".to_string())?; |
| 8223 | match proof { |
| 8224 | Some((bearer, signature)) if url.path() != "/mcp" => { |
| 8225 | let public_key = owner_public_key |
| 8226 | .and_then(|key| URL_SAFE_NO_PAD.decode(key).ok()) |
| 8227 | .filter(|bytes| bytes.len() == 32) |
| 8228 | .ok_or_else(|| "Desktop browser owner is unavailable".to_string())?; |
| 8229 | let signature = URL_SAFE_NO_PAD |
| 8230 | .decode(signature) |
| 8231 | .map_err(|_| "Invalid desktop browser signature".to_string())?; |
| 8232 | if bearer.len() != 43 || URL_SAFE_NO_PAD.decode(bearer).is_err() { |
| 8233 | return Err("Invalid desktop browser credential".to_string()); |
| 8234 | } |
| 8235 | let workspace = self |
| 8236 | .workspace |
| 8237 | .as_deref() |
| 8238 | .and_then(Path::to_str) |
| 8239 | .ok_or_else(|| "Desktop browser workspace is unavailable".to_string())?; |
| 8240 | let workspace = workspace |
| 8241 | .strip_prefix(r"\\?\UNC\") |
| 8242 | .map(|tail| format!(r"\\{tail}")) |
| 8243 | .unwrap_or_else(|| { |
| 8244 | workspace |
| 8245 | .strip_prefix(r"\\?\") |
| 8246 | .unwrap_or(workspace) |
| 8247 | .to_owned() |
| 8248 | }); |
| 8249 | let data = format!("codewhale-browser-v2\0{workspace}\0{url}\0{bearer}"); |
| 8250 | ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key) |
| 8251 | .verify(data.as_bytes(), &signature) |
| 8252 | .map_err(|_| { |
| 8253 | "Desktop browser registration does not match this workspace and endpoint" |
| 8254 | .to_string() |
| 8255 | })?; |
| 8256 | config.bearer_token_env_var = None; |
| 8257 | config |
| 8258 | .headers |
| 8259 | .insert("Authorization".to_string(), format!("Bearer {bearer}")); |
| 8260 | } |
| 8261 | None if url.path() == "/mcp" |
| 8262 | && mcp_secret_available( |
| 8263 | &config, |
| 8264 | "CODEWHALE_BROWSER_TOOLS_TOKEN", |
| 8265 | self.auth_context.as_ref(), |
| 8266 | ) => {} |
| 8267 | _ => { |
| 8268 | return Err( |
| 8269 | "Desktop browser tools require their owning desktop process and credential" |
| 8270 | .to_string(), |
| 8271 | ); |
| 8272 | } |
| 8273 | } |
| 8274 | self.require_server(&name) |
| 8275 | .map_err(|error| error.to_string())?; |
| 8276 | if self.config.servers.contains_key(&name) { |
| 8277 | return Err("A configured MCP server already owns this name".to_string()); |
| 8278 | } |
| 8279 | { |
| 8280 | let mut dynamic = self.dynamic_servers.write(); |
| 8281 | if let Some(held) = dynamic.get(&name) { |
| 8282 | if held.runtime_added { |
| 8283 | return Err("A different runtime MCP server already owns this name".to_string()); |
| 8284 | } |
| 8285 | let old = serde_json::to_value(held) |
| 8286 | .map_err(|_| "Runtime MCP configuration unavailable")?; |
| 8287 | let new = serde_json::to_value(&config) |
| 8288 | .map_err(|_| "Runtime MCP configuration unavailable")?; |
| 8289 | if old == new { |
| 8290 | return Ok(()); |
| 8291 | } |
| 8292 | if proof.is_none() { |
| 8293 | return Err("A different runtime MCP server already owns this name".to_string()); |
| 8294 | } |
| 8295 | } |
| 8296 | dynamic.insert(name.clone(), config); |
| 8297 | } |
| 8298 | self.drop_connection(&name, "desktop browser registered"); |
| 8299 | self.connect_backoff.remove(&name); |
| 8300 | self.catalog_generation.fetch_add(1, Ordering::SeqCst); |
| 8301 | Ok(()) |
| 8302 | } |
| 8303 | |
| 8304 | fn add_dynamic_server_config( |
| 8305 | &self, |
| 8306 | name: String, |
| 8307 | config: McpServerConfig, |
| 8308 | runtime_added: bool, |
| 8309 | ) -> Result<(), String> { |
| 8310 | if name.trim().is_empty() { |
| 8311 | return Err("MCP server name must not be empty".to_string()); |
| 8312 | } |
| 8313 | self.require_server(&name) |
| 8314 | .map_err(|error| error.to_string())?; |
| 8315 | if self.config.servers.contains_key(&name) { |
| 8316 | return Err(format!( |
| 8317 | "MCP server '{}' already exists in the config file. \ |
| 8318 | Reconnect with start_mcp_server using only its exact name (omit server), \ |
| 8319 | or run /mcp retry with that name. This preserves its stored credentials.", |
| 8320 | name |
| 8321 | )); |
| 8322 | } |
| 8323 | let mut dynamic = self.dynamic_servers.write(); |
| 8324 | if dynamic.contains_key(&name) { |
| 8325 | return Err(format!( |
| 8326 | "MCP server '{}' was already started earlier in this session. \ |
| 8327 | Reconnect with start_mcp_server using only its exact name (omit server).", |
| 8328 | name |
| 8329 | )); |
| 8330 | } |
| 8331 | let mut config = config; |
| 8332 | config.runtime_added = runtime_added; |
| 8333 | config.always_allow_tools.clear(); |
| 8334 | dynamic.insert(name, config); |
| 8335 | self.catalog_generation.fetch_add(1, Ordering::SeqCst); |
| 8336 | Ok(()) |
| 8337 | } |
| 8338 | |
| 8339 | /// Remove an in-memory runtime server after a failed start attempt. |
| 8340 | /// This makes dynamic registration transactional: callers may retry the |
| 8341 | /// same deterministic name after correcting an argument or install issue. |
| 8342 | pub fn remove_runtime_server_config(&mut self, name: &str) { |
| 8343 | self.drop_connection(name, "runtime server start rolled back"); |
| 8344 | if self.dynamic_servers.write().remove(name).is_some() { |
| 8345 | self.catalog_generation.fetch_add(1, Ordering::SeqCst); |
| 8346 | } |
| 8347 | } |
| 8348 | |
| 8349 | /// Get list of connected server names |
| 8350 | pub fn connected_servers(&self) -> Vec<&str> { |
| 8351 | self.connections |
| 8352 | .iter() |
| 8353 | .filter(|(name, c)| self.server_allowed(name) && c.is_ready()) |
| 8354 | .map(|(n, _)| n.as_str()) |
| 8355 | .collect() |
| 8356 | } |
| 8357 | |
| 8358 | /// Names of every *enabled* server this pool would connect on the next |
| 8359 | /// turn (static config + dynamic runtime entries). |
| 8360 | /// |
| 8361 | /// Read-only: unlike [`Self::connect_all`], it neither reloads the config |
| 8362 | /// sources nor starts a process. `/preview-request` uses it, together |
| 8363 | /// with [`Self::connected_servers`] and |
| 8364 | /// [`Self::config_sources_unchanged`], to decide whether the currently |
| 8365 | /// connected tool set is *exactly* what the next turn would send — and to |
| 8366 | /// report the tool surface as unavailable when it is not (#1004). |
| 8367 | pub fn enabled_server_names(&self) -> Vec<String> { |
| 8368 | let mut names: Vec<String> = self |
| 8369 | .config |
| 8370 | .servers |
| 8371 | .iter() |
| 8372 | .filter(|(name, server)| server.is_enabled() && self.server_allowed(name)) |
| 8373 | .map(|(name, _)| name.clone()) |
| 8374 | .collect(); |
| 8375 | let dynamic = self.dynamic_servers.read(); |
| 8376 | for (name, server) in dynamic.iter() { |
| 8377 | if self.server_allowed(name) && server.is_enabled() && !names.contains(name) { |
| 8378 | names.push(name.clone()); |
| 8379 | } |
| 8380 | } |
| 8381 | names |
| 8382 | } |
| 8383 | |
| 8384 | /// Compare against the freshly authorized merged configuration without |
| 8385 | /// reloading or disconnecting any sibling transport. |
| 8386 | pub fn config_matches(&self, config: &McpConfig) -> bool { |
| 8387 | hash_mcp_config(config) == self.config_hash |
| 8388 | } |
| 8389 | |
| 8390 | /// Whether every configured MCP source still has the mtime this pool last |
| 8391 | /// read, i.e. whether `connect_all` would find anything new. |
| 8392 | /// |
| 8393 | /// Stats files; never reads, parses, reloads, or drops a connection. A |
| 8394 | /// pool with no configured source is trivially unchanged. |
| 8395 | pub fn config_sources_unchanged(&self) -> bool { |
| 8396 | if self.config_sources.is_empty() { |
| 8397 | return true; |
| 8398 | } |
| 8399 | let current: Vec<_> = self |
| 8400 | .config_sources |
| 8401 | .iter() |
| 8402 | .map(|path| mcp_config_mtime(path)) |
| 8403 | .collect(); |
| 8404 | current == self.last_mtimes |
| 8405 | } |
| 8406 | |
| 8407 | /// Graceful shutdown of every connection in the pool: send SIGTERM to |
| 8408 | /// each stdio child and give them a short grace period before drop |
| 8409 | /// fires SIGKILL. Whalescale#420. |
| 8410 | /// |
| 8411 | /// Call from the TUI exit path *before* dropping the pool to give |
| 8412 | /// MCP servers a chance to flush state. The fallback Drop on |
| 8413 | /// `StdioTransport` still sends SIGTERM if this never runs, so even |
| 8414 | /// abnormal exits avoid leaking PIDs without a signal. |
| 8415 | pub async fn shutdown_all(&mut self) { |
| 8416 | let names: Vec<String> = self.connections.keys().cloned().collect(); |
| 8417 | for name in names { |
| 8418 | if let Some(conn) = self.connections.get_mut(&name) { |
| 8419 | conn.transport.shutdown().await; |
| 8420 | } |
| 8421 | } |
| 8422 | self.connections.clear(); |
| 8423 | } |
| 8424 | |
| 8425 | /// Check if a tool name is an MCP tool |
| 8426 | pub fn is_mcp_tool(name: &str) -> bool { |
| 8427 | name.starts_with("mcp_") |
| 8428 | || matches!( |
| 8429 | name, |
| 8430 | "list_mcp_resources" | "list_mcp_resource_templates" | "read_mcp_resource" |
| 8431 | ) |
| 8432 | } |
| 8433 | } |
| 8434 | |
| 8435 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 8436 | pub enum McpWriteStatus { |
| 8437 | Created, |
| 8438 | Overwritten, |
| 8439 | SkippedExists, |
| 8440 | } |
| 8441 | |
| 8442 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 8443 | pub struct McpDiscoveredItem { |
| 8444 | pub name: String, |
| 8445 | pub model_name: String, |
| 8446 | pub description: Option<String>, |
| 8447 | } |
| 8448 | |
| 8449 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 8450 | pub struct McpServerSnapshot { |
| 8451 | pub name: String, |
| 8452 | pub enabled: bool, |
| 8453 | pub required: bool, |
| 8454 | pub transport: String, |
| 8455 | pub command_or_url: String, |
| 8456 | pub connect_timeout: u64, |
| 8457 | pub execute_timeout: u64, |
| 8458 | pub read_timeout: u64, |
| 8459 | pub connected: bool, |
| 8460 | pub error: Option<String>, |
| 8461 | /// Typed `◆ auth required` state: the server's most recent connect |
| 8462 | /// attempt failed because a login is missing, expired, or revoked |
| 8463 | /// (401 / OAuth not logged in / `invalid_grant`). Derived from the pool's |
| 8464 | /// needs-auth set — the same source that decides whether the model gets |
| 8465 | /// the synthetic `mcp_<server>_authenticate` tool — so every surface |
| 8466 | /// (session boot row, `/mcp` manager, Extensions, model catalog) agrees. |
| 8467 | pub auth_required: bool, |
| 8468 | pub capability_metadata: McpServerCapabilityMetadata, |
| 8469 | pub tools: Vec<McpDiscoveredItem>, |
| 8470 | pub resources: Vec<McpDiscoveredItem>, |
| 8471 | pub prompts: Vec<McpDiscoveredItem>, |
| 8472 | } |
| 8473 | |
| 8474 | impl McpServerSnapshot { |
| 8475 | /// Recovery for this observed server. The typed auth-required state wins |
| 8476 | /// over error-text sniffing so a needs-auth server routes to |
| 8477 | /// `/mcp login <name>` whenever that login can run, and diagnoses when it |
| 8478 | /// cannot (not OAuth-capable, or no usable client registration). |
| 8479 | #[must_use] |
| 8480 | pub fn recovery_kind(&self, oauth_capable: bool) -> Option<McpRecoveryKind> { |
| 8481 | let dynamic_registration_hint = oauth::dynamic_registration_unavailable_hint(&self.name); |
| 8482 | let oauth_login = oauth_capable |
| 8483 | && !self |
| 8484 | .error |
| 8485 | .as_deref() |
| 8486 | .is_some_and(|error| error.contains(&dynamic_registration_hint)); |
| 8487 | if self.enabled && !self.connected && self.auth_required && oauth_login { |
| 8488 | return Some(McpRecoveryKind::Reauth); |
| 8489 | } |
| 8490 | match mcp_recovery_kind( |
| 8491 | self.enabled, |
| 8492 | self.started(), |
| 8493 | self.connected, |
| 8494 | self.error.as_deref(), |
| 8495 | oauth_capable, |
| 8496 | ) { |
| 8497 | Some(McpRecoveryKind::Reauth) if !oauth_login => Some(McpRecoveryKind::Diagnose), |
| 8498 | recovery => recovery, |
| 8499 | } |
| 8500 | } |
| 8501 | |
| 8502 | /// Whether this session ever attempted the server. A `lazy = true` server |
| 8503 | /// nobody asked for (#6033) has no connection, no recorded failure, and |
| 8504 | /// no observed capabilities — it was never started, so its recovery is |
| 8505 | /// `connect`, not `reconnect`, and an OAuth-capable one is not yet known |
| 8506 | /// to need a login. |
| 8507 | #[must_use] |
| 8508 | pub fn started(&self) -> bool { |
| 8509 | self.connected |
| 8510 | || self.auth_required |
| 8511 | || self.error.is_some() |
| 8512 | || !matches!( |
| 8513 | self.capability_metadata, |
| 8514 | McpServerCapabilityMetadata::NotObserved |
| 8515 | ) |
| 8516 | } |
| 8517 | } |
| 8518 | |
| 8519 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 8520 | pub struct McpManagerSnapshot { |
| 8521 | pub config_path: std::path::PathBuf, |
| 8522 | pub config_exists: bool, |
| 8523 | pub reload_required: bool, |
| 8524 | pub servers: Vec<McpServerSnapshot>, |
| 8525 | } |
| 8526 | |
| 8527 | /// First-class recovery for a configured MCP server. Commands named here exist: |
| 8528 | /// `/mcp login`, `/mcp reload`, `/mcp validate`, `/mcp enable`. There is no |
| 8529 | /// `/mcp auth`. |
| 8530 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 8531 | pub enum McpRecoveryKind { |
| 8532 | Enable, |
| 8533 | Connect, |
| 8534 | Reconnect, |
| 8535 | Reauth, |
| 8536 | Diagnose, |
| 8537 | /// The server's AWS credentials (an SSO session or a temporary token) |
| 8538 | /// expired. The fix is outside Codewhale — `aws sso login` in a terminal |
| 8539 | /// (see [`aws_login_hint`]) — and `/mcp login` cannot help: it is an |
| 8540 | /// OAuth flow for HTTP servers, and a stdio AWS proxy is not one. The row |
| 8541 | /// action is the single-server retry to run once the login is done. |
| 8542 | AwsLogin, |
| 8543 | } |
| 8544 | |
| 8545 | impl McpRecoveryKind { |
| 8546 | #[must_use] |
| 8547 | pub fn slash_command(self, name: &str) -> String { |
| 8548 | match self { |
| 8549 | Self::Enable => format!("/mcp enable {name}"), |
| 8550 | // Reconnect one server, not all of them. A row that reads |
| 8551 | // `[reconnect] aws` and then reloads all 23 configured servers is |
| 8552 | // not the action it advertised: it takes ~40 s, it disturbs every |
| 8553 | // healthy connection, and the row the user aimed at is still |
| 8554 | // pending when the list comes back. `/mcp retry <name>` reaches |
| 8555 | // `retry_mcp_server`, which reconnects exactly that server. |
| 8556 | Self::Connect | Self::Reconnect | Self::AwsLogin if mcp_name_is_command_safe(name) => { |
| 8557 | format!("/mcp retry {name}") |
| 8558 | } |
| 8559 | // A name the command line cannot carry safely still gets the |
| 8560 | // blunt instrument rather than a quoted-argument hazard. |
| 8561 | Self::Connect | Self::Reconnect | Self::AwsLogin => "/mcp reload".to_string(), |
| 8562 | Self::Reauth => format!("/mcp login {name}"), |
| 8563 | Self::Diagnose if mcp_name_is_command_safe(name) => format!("/mcp validate {name}"), |
| 8564 | Self::Diagnose => "/mcp validate".to_string(), |
| 8565 | } |
| 8566 | } |
| 8567 | |
| 8568 | #[must_use] |
| 8569 | pub fn label_key(self) -> codewhale_localization::MessageId { |
| 8570 | match self { |
| 8571 | Self::Enable => codewhale_localization::MessageId::ExtensionsActionEnable, |
| 8572 | Self::Connect => codewhale_localization::MessageId::ExtensionsActionConnect, |
| 8573 | Self::Reconnect => codewhale_localization::MessageId::ExtensionsActionReconnect, |
| 8574 | Self::Reauth => codewhale_localization::MessageId::ExtensionsActionReauth, |
| 8575 | // The row action is `/mcp retry <name>` in place, not a login |
| 8576 | // flow, so it is labelled for what it runs. The why (run |
| 8577 | // `aws login` first) is carried in the row detail, which the |
| 8578 | // snapshot guarantees names the command (see |
| 8579 | // `snapshot_from_config`). |
| 8580 | Self::AwsLogin => codewhale_localization::MessageId::ExtensionsActionReconnect, |
| 8581 | Self::Diagnose => codewhale_localization::MessageId::ExtensionsActionDiagnose, |
| 8582 | } |
| 8583 | } |
| 8584 | } |
| 8585 | |
| 8586 | #[must_use] |
| 8587 | pub fn mcp_name_is_command_safe(name: &str) -> bool { |
| 8588 | !name.is_empty() |
| 8589 | && name |
| 8590 | .chars() |
| 8591 | .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.')) |
| 8592 | } |
| 8593 | |
| 8594 | /// Display target for an MCP server row: stdio servers show the command |
| 8595 | /// name only — no `./…` relative-path prefix, no directories, no args — |
| 8596 | /// while URL servers keep their full URL, which is the identity. The |
| 8597 | /// snapshot's `command_or_url` keeps full fidelity for the engine and the |
| 8598 | /// wire; this is presentation only. |
| 8599 | #[must_use] |
| 8600 | pub fn mcp_display_target(transport: &str, command_or_url: &str) -> String { |
| 8601 | if transport != "stdio" { |
| 8602 | return command_or_url.to_string(); |
| 8603 | } |
| 8604 | let command = command_or_url |
| 8605 | .split_whitespace() |
| 8606 | .next() |
| 8607 | .unwrap_or(command_or_url); |
| 8608 | let name = command.rsplit(['/', '\\']).next().unwrap_or(command); |
| 8609 | if name.is_empty() { |
| 8610 | command_or_url.to_string() |
| 8611 | } else { |
| 8612 | name.to_string() |
| 8613 | } |
| 8614 | } |
| 8615 | |
| 8616 | #[must_use] |
| 8617 | pub fn mcp_server_oauth_capable(config: &McpServerConfig) -> bool { |
| 8618 | // Use the login path's own authority, including discovery-only HTTP |
| 8619 | // servers, manual Authorization and the reviewed-plugin restriction. |
| 8620 | oauth::server_supports_oauth_login(config) |
| 8621 | } |
| 8622 | |
| 8623 | #[must_use] |
| 8624 | pub fn mcp_recovery_kind( |
| 8625 | enabled: bool, |
| 8626 | inspected: bool, |
| 8627 | connected: bool, |
| 8628 | error: Option<&str>, |
| 8629 | oauth_capable: bool, |
| 8630 | ) -> Option<McpRecoveryKind> { |
| 8631 | if !enabled { |
| 8632 | return Some(McpRecoveryKind::Enable); |
| 8633 | } |
| 8634 | if let Some(error) = error { |
| 8635 | if error |
| 8636 | .to_ascii_lowercase() |
| 8637 | .contains(&MCP_CREDENTIAL_CONFIGURATION_ERROR_PREFIX.to_ascii_lowercase()) |
| 8638 | { |
| 8639 | return Some(McpRecoveryKind::Diagnose); |
| 8640 | } |
| 8641 | // Before the OAuth classifier: an expired AWS token often surfaces as |
| 8642 | // `UnauthorizedException`/`401`, and `/mcp login` — an OAuth flow — |
| 8643 | // cannot renew an AWS session. |
| 8644 | // Gated on the server not being OAuth-capable: an OAuth server |
| 8645 | // fronted by corporate SSO saying "SSO token expired" needs its own |
| 8646 | // login, not `aws sso login`. |
| 8647 | if mcp_error_is_aws_login(error, oauth_capable) { |
| 8648 | return Some(McpRecoveryKind::AwsLogin); |
| 8649 | } |
| 8650 | if oauth_capable && oauth::error_text_looks_auth_required(error) { |
| 8651 | return Some(McpRecoveryKind::Reauth); |
| 8652 | } |
| 8653 | return Some(McpRecoveryKind::Diagnose); |
| 8654 | } |
| 8655 | if !inspected { |
| 8656 | return Some(McpRecoveryKind::Connect); |
| 8657 | } |
| 8658 | if connected { |
| 8659 | // A server that is enabled, inspected, connected and erroring on |
| 8660 | // nothing needs no recovery. It used to be labelled `diagnose`, so |
| 8661 | // every healthy row advertised a repair it did not need — founder |
| 8662 | // live-test: "even the ones that are connected say diagnose lol". |
| 8663 | return None; |
| 8664 | } |
| 8665 | if oauth_capable { |
| 8666 | return Some(McpRecoveryKind::Reauth); |
| 8667 | } |
| 8668 | Some(McpRecoveryKind::Reconnect) |
| 8669 | } |
| 8670 | |
| 8671 | /// Whether an MCP server's error (usually its forwarded stderr line) says the |
| 8672 | /// AWS credentials it launched with have expired. The founder's `aws` server |
| 8673 | /// failed `initialize` with -32602 whose only real cause was an expired SSO |
| 8674 | /// login; the generic "diagnose" gave no way forward. Every pattern is |
| 8675 | /// anchored to AWS CLI / SDK wording so an unrelated "token expired" from an |
| 8676 | /// OAuth server still reaches the OAuth classifier. |
| 8677 | #[must_use] |
| 8678 | pub fn error_text_looks_aws_credentials_expired(text: &str) -> bool { |
| 8679 | let text = text.to_ascii_lowercase(); |
| 8680 | let expired = text.contains("expired") || text.contains("invalid"); |
| 8681 | // botocore / AWS CLI v2 SSO wording ("The SSO session associated with |
| 8682 | // this profile has expired or is otherwise invalid", "Error loading SSO |
| 8683 | // Token: Token for … does not exist"). |
| 8684 | let sso = ["sso session", "sso token", "sso login", "sso oidc"] |
| 8685 | .iter() |
| 8686 | .any(|phrase| text.contains(phrase)); |
| 8687 | let mentions_aws = text |
| 8688 | .split(|ch: char| !ch.is_ascii_alphanumeric()) |
| 8689 | .any(|word| word == "aws"); |
| 8690 | (sso && (expired || text.contains("does not exist"))) |
| 8691 | // AWS CLI 2.32+ `aws login` sessions: "LoginRefreshRequired: Please |
| 8692 | // reauthenticate using aws login" (the founder's -32602 case). |
| 8693 | || text.contains("loginrefreshrequired") |
| 8694 | // Our own hint, so a reviewed plugin's suppressed error (which keeps |
| 8695 | // only this fixed text) still classifies on every later surface. |
| 8696 | || text.contains("aws credentials expired:") |
| 8697 | || text.contains("reauthenticate using aws login") |
| 8698 | // STS / service error codes for expired temporary credentials. |
| 8699 | || text.contains("expiredtoken") |
| 8700 | || text.contains("security token included in the request is expired") |
| 8701 | || text.contains("tokenrefreshrequired") |
| 8702 | || (mentions_aws && text.contains("token") && text.contains("expired")) |
| 8703 | } |
| 8704 | |
| 8705 | /// Whether an MCP error means "renew the AWS login in a terminal". Only a |
| 8706 | /// server that is not OAuth-capable qualifies: an OAuth server's expired |
| 8707 | /// token is renewed by `/mcp login`, whatever words its SSO front uses. |
| 8708 | #[must_use] |
| 8709 | pub fn mcp_error_is_aws_login(text: &str, oauth_capable: bool) -> bool { |
| 8710 | !oauth_capable && error_text_looks_aws_credentials_expired(text) |
| 8711 | } |
| 8712 | |
| 8713 | /// The terminal command that renews an expired AWS login for `config`, with |
| 8714 | /// the follow-up retry. `error_text` picks the command: a CLI 2.32+ |
| 8715 | /// `aws login` session (`LoginRefreshRequired`) renews with `aws login`, |
| 8716 | /// everything else with `aws sso login`. The profile comes from the server's |
| 8717 | /// own `--profile` argument, else its `AWS_PROFILE` env entry (not for a |
| 8718 | /// reviewed plugin, whose env stays out of every surface); with neither the |
| 8719 | /// plain command uses the default profile, which is what the server does. |
| 8720 | #[must_use] |
| 8721 | pub fn aws_login_hint(config: &McpServerConfig, server: &str, error_text: &str) -> String { |
| 8722 | let profile = config |
| 8723 | .args |
| 8724 | .iter() |
| 8725 | .position(|arg| arg == "--profile") |
| 8726 | .and_then(|index| config.args.get(index + 1)) |
| 8727 | .map(String::as_str) |
| 8728 | .or_else(|| { |
| 8729 | config |
| 8730 | .args |
| 8731 | .iter() |
| 8732 | .find_map(|arg| arg.strip_prefix("--profile=")) |
| 8733 | }) |
| 8734 | .or_else(|| { |
| 8735 | config |
| 8736 | .reviewed_plugin |
| 8737 | .is_none() |
| 8738 | .then(|| config.env.get("AWS_PROFILE").map(String::as_str)) |
| 8739 | .flatten() |
| 8740 | }) |
| 8741 | .filter(|profile| !profile.starts_with('-') && mcp_name_is_command_safe(profile)); |
| 8742 | let lower = error_text.to_ascii_lowercase(); |
| 8743 | let command = if lower.contains("loginrefreshrequired") |
| 8744 | || lower.contains("using aws login") |
| 8745 | || lower.contains("run `aws login") |
| 8746 | { |
| 8747 | "aws login" |
| 8748 | } else { |
| 8749 | "aws sso login" |
| 8750 | }; |
| 8751 | let login = match profile { |
| 8752 | Some(profile) => format!("{command} --profile {profile}"), |
| 8753 | None => command.to_string(), |
| 8754 | }; |
| 8755 | let retry = McpRecoveryKind::AwsLogin.slash_command(server); |
| 8756 | format!("AWS credentials expired: run `{login}` in a terminal, then `{retry}`") |
| 8757 | } |
| 8758 | |
| 8759 | pub fn load_config(path: &Path) -> Result<McpConfig> { |
| 8760 | validate_mcp_config_path(path)?; |
| 8761 | let Some(contents) = read_mcp_config_file(path)? else { |
| 8762 | return Ok(McpConfig::default()); |
| 8763 | }; |
| 8764 | serde_json::from_str(&contents).map_err(|_| { |
| 8765 | anyhow::anyhow!( |
| 8766 | "Failed to parse MCP config {}; file contents were omitted", |
| 8767 | codewhale_config::quote_os_path(path) |
| 8768 | ) |
| 8769 | }) |
| 8770 | } |
| 8771 | |
| 8772 | /// Maximum bytes read from an MCP config file. Configs are kilobytes. |
| 8773 | pub const MAX_MCP_CONFIG_BYTES: u64 = 1024 * 1024; |
| 8774 | |
| 8775 | fn read_mcp_config_file(path: &Path) -> Result<Option<String>> { |
| 8776 | read_bounded_mcp_config_file(path, MAX_MCP_CONFIG_BYTES) |
| 8777 | } |
| 8778 | |
| 8779 | /// [`read_mcp_config_file`] with a caller-chosen size bound, for foreign files |
| 8780 | /// such as `~/.claude.json` that carry far more than an MCP server map. |
| 8781 | pub fn read_bounded_mcp_config_file(path: &Path, max_bytes: u64) -> Result<Option<String>> { |
| 8782 | let metadata = match fs::symlink_metadata(path) { |
| 8783 | Ok(metadata) => metadata, |
| 8784 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None), |
| 8785 | Err(err) => { |
| 8786 | return Err(err) |
| 8787 | .with_context(|| format!("Failed to inspect MCP config {}", path.display())); |
| 8788 | } |
| 8789 | }; |
| 8790 | let file_type = metadata.file_type(); |
| 8791 | if file_type.is_symlink() || !file_type.is_file() { |
| 8792 | anyhow::bail!("MCP config path must be a regular file: {}", path.display()); |
| 8793 | } |
| 8794 | if metadata.len() > max_bytes { |
| 8795 | anyhow::bail!( |
| 8796 | "MCP config {} exceeds the {} MiB limit", |
| 8797 | path.display(), |
| 8798 | max_bytes / (1024 * 1024) |
| 8799 | ); |
| 8800 | } |
| 8801 | |
| 8802 | let file = open_mcp_config_file(path) |
| 8803 | .with_context(|| format!("Failed to read MCP config {}", path.display()))?; |
| 8804 | let mut contents = String::new(); |
| 8805 | file.take(max_bytes + 1) |
| 8806 | .read_to_string(&mut contents) |
| 8807 | .with_context(|| format!("Failed to read MCP config {}", path.display()))?; |
| 8808 | if contents.len() as u64 > max_bytes { |
| 8809 | anyhow::bail!( |
| 8810 | "MCP config {} exceeds the {} MiB limit", |
| 8811 | path.display(), |
| 8812 | max_bytes / (1024 * 1024) |
| 8813 | ); |
| 8814 | } |
| 8815 | Ok(Some(contents)) |
| 8816 | } |
| 8817 | |
| 8818 | #[cfg(unix)] |
| 8819 | fn open_mcp_config_file(path: &Path) -> std::io::Result<fs::File> { |
| 8820 | use std::os::unix::fs::OpenOptionsExt; |
| 8821 | |
| 8822 | fs::OpenOptions::new() |
| 8823 | .read(true) |
| 8824 | .custom_flags(libc::O_NOFOLLOW) |
| 8825 | .open(path) |
| 8826 | } |
| 8827 | |
| 8828 | #[cfg(not(unix))] |
| 8829 | fn open_mcp_config_file(path: &Path) -> std::io::Result<fs::File> { |
| 8830 | fs::File::open(path) |
| 8831 | } |
| 8832 | |
| 8833 | pub fn workspace_mcp_config_path(workspace: &Path) -> PathBuf { |
| 8834 | normalize_workspace_path(workspace) |
| 8835 | .join(".codewhale") |
| 8836 | .join("mcp.json") |
| 8837 | } |
| 8838 | |
| 8839 | /// Which configuration file declares an MCP server. |
| 8840 | /// |
| 8841 | /// The rows in `/mcp` are the union of the user's global file, the trusted |
| 8842 | /// workspace's own file, and every installed plugin's contribution. Until |
| 8843 | /// this existed the panel offered `e` and `d` on all three and then wrote to |
| 8844 | /// the global file regardless, so toggling or removing a project server |
| 8845 | /// failed with "MCP server `'<name>'` not found" — the row looked mutable and |
| 8846 | /// was not. |
| 8847 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 8848 | pub enum McpServerScope { |
| 8849 | /// The user's own config file, shared by every workspace. |
| 8850 | Global, |
| 8851 | /// `<workspace>/.codewhale/mcp.json`, honoured only once the workspace |
| 8852 | /// is trusted in user-owned config (#417) and its exact contents are approved. |
| 8853 | Project(PathBuf), |
| 8854 | /// Contributed by an installed plugin bundle. It lives in no config |
| 8855 | /// file, so it is switched off by disabling the plugin that owns it. |
| 8856 | Plugin, |
| 8857 | } |
| 8858 | |
| 8859 | impl McpServerScope { |
| 8860 | /// The file a mutation for this server must write, or `None` when the |
| 8861 | /// server has no config file of its own. |
| 8862 | #[must_use] |
| 8863 | pub fn config_path(&self, global_path: &Path) -> Option<PathBuf> { |
| 8864 | match self { |
| 8865 | Self::Global => Some(global_path.to_path_buf()), |
| 8866 | Self::Project(path) => Some(path.clone()), |
| 8867 | Self::Plugin => None, |
| 8868 | } |
| 8869 | } |
| 8870 | } |
| 8871 | |
| 8872 | /// Resolve the file that declares `name`. |
| 8873 | /// |
| 8874 | /// Project entries are checked first because |
| 8875 | /// [`load_config_with_workspace_and_plugins`] lets them override a |
| 8876 | /// same-named global server, so the project file is the one a mutation has |
| 8877 | /// to edit for the change to be observable. |
| 8878 | /// Every server name declared by the trusted workspace's own config file. |
| 8879 | /// |
| 8880 | /// Resolved once per panel snapshot so the row rendering can label scope |
| 8881 | /// without a file read per row. |
| 8882 | #[must_use] |
| 8883 | pub fn project_server_names(global_path: &Path, workspace: &Path) -> BTreeSet<String> { |
| 8884 | let Ok(workspace) = checked_workspace_path(workspace) else { |
| 8885 | return BTreeSet::new(); |
| 8886 | }; |
| 8887 | let Ok(project_path) = checked_workspace_mcp_config_path(&workspace) else { |
| 8888 | return BTreeSet::new(); |
| 8889 | }; |
| 8890 | if !project_path.exists() || paths_refer_to_same_config(global_path, &project_path) { |
| 8891 | return BTreeSet::new(); |
| 8892 | } |
| 8893 | project_authority::approved_project_mcp(&workspace) |
| 8894 | .ok() |
| 8895 | .and_then(|reviewed| serde_json::from_str::<McpConfig>(&reviewed.contents).ok()) |
| 8896 | .map(|config| config.servers.into_keys().collect()) |
| 8897 | .unwrap_or_default() |
| 8898 | } |
| 8899 | |
| 8900 | #[must_use] |
| 8901 | pub fn resolve_server_scope(global_path: &Path, workspace: &Path, name: &str) -> McpServerScope { |
| 8902 | if let Ok(workspace) = checked_workspace_path(workspace) |
| 8903 | && let Ok(project_path) = checked_workspace_mcp_config_path(&workspace) |
| 8904 | && project_path.exists() |
| 8905 | && !paths_refer_to_same_config(global_path, &project_path) |
| 8906 | && project_authority::approved_project_mcp(&workspace) |
| 8907 | .ok() |
| 8908 | .and_then(|reviewed| serde_json::from_str::<McpConfig>(&reviewed.contents).ok()) |
| 8909 | .is_some_and(|config| config.servers.contains_key(name)) |
| 8910 | { |
| 8911 | return McpServerScope::Project(project_path); |
| 8912 | } |
| 8913 | if load_config(global_path).is_ok_and(|config| config.servers.contains_key(name)) { |
| 8914 | return McpServerScope::Global; |
| 8915 | } |
| 8916 | McpServerScope::Plugin |
| 8917 | } |
| 8918 | |
| 8919 | /// Plugin name of the built-in Computer Use bundle. |
| 8920 | pub const COMPUTER_USE_PLUGIN_NAME: &str = "computer-use"; |
| 8921 | |
| 8922 | /// First message the host sends the reviewed Computer Use plugin: its |
| 8923 | /// per-connection decision key and the persisted-ledger key. |
| 8924 | pub const COMPUTER_USE_HOST_KEYS_METHOD: &str = "codewhale/host_keys"; |
| 8925 | |
| 8926 | /// `_meta` key carrying an attested person's decision on a `tools/call`. |
| 8927 | pub const COMPUTER_USE_DECISION_META: &str = "codewhale/user_decision"; |
| 8928 | |
| 8929 | /// Secret-store slot of the key that signs remembered Computer Use grants. |
| 8930 | const COMPUTER_USE_LEDGER_KEY_SLOT: &str = "codewhale_cu_ledger_key"; |
| 8931 | |
| 8932 | pub fn random_key() -> Result<[u8; 32]> { |
| 8933 | use ring::rand::SecureRandom as _; |
| 8934 | let mut key = [0_u8; 32]; |
| 8935 | ring::rand::SystemRandom::new() |
| 8936 | .fill(&mut key) |
| 8937 | .map_err(|_| { |
| 8938 | anyhow::anyhow!("System randomness is unavailable for Computer Use approval") |
| 8939 | })?; |
| 8940 | Ok(key) |
| 8941 | } |
| 8942 | |
| 8943 | pub fn hex_encode(bytes: &[u8]) -> String { |
| 8944 | use std::fmt::Write as _; |
| 8945 | bytes |
| 8946 | .iter() |
| 8947 | .fold(String::with_capacity(bytes.len() * 2), |mut out, byte| { |
| 8948 | let _ = write!(out, "{byte:02x}"); |
| 8949 | out |
| 8950 | }) |
| 8951 | } |
| 8952 | |
| 8953 | /// `{nonce, args_json, mac}` for one call: `mac` is HMAC-SHA256 over |
| 8954 | /// `tool \0 args_json \0 nonce`, and the plugin checks that `args_json` |
| 8955 | /// parses to the arguments it received. |
| 8956 | pub fn attest_decision( |
| 8957 | key: &[u8; 32], |
| 8958 | tool_name: &str, |
| 8959 | arguments: &serde_json::Value, |
| 8960 | ) -> Result<serde_json::Value> { |
| 8961 | let nonce = hex_encode(&random_key()?[..16]); |
| 8962 | let args_json = serde_json::to_string(arguments)?; |
| 8963 | let message = [ |
| 8964 | tool_name.as_bytes(), |
| 8965 | b"\0", |
| 8966 | args_json.as_bytes(), |
| 8967 | b"\0", |
| 8968 | nonce.as_bytes(), |
| 8969 | ] |
| 8970 | .concat(); |
| 8971 | let tag = ring::hmac::sign( |
| 8972 | &ring::hmac::Key::new(ring::hmac::HMAC_SHA256, key), |
| 8973 | &message, |
| 8974 | ); |
| 8975 | Ok(serde_json::json!({ |
| 8976 | "nonce": nonce, |
| 8977 | "args_json": args_json, |
| 8978 | "mac": hex_encode(tag.as_ref()), |
| 8979 | })) |
| 8980 | } |
| 8981 | |
| 8982 | /// The key that signs remembered Computer Use grants, created once in the |
| 8983 | /// secret store. `None` when the store is unavailable: remembered grants |
| 8984 | /// then do not survive the session. |
| 8985 | pub async fn computer_use_ledger_key() -> Option<String> { |
| 8986 | if cfg!(any(test, feature = "test-support")) { |
| 8987 | return None; |
| 8988 | } |
| 8989 | tokio::task::spawn_blocking(|| { |
| 8990 | let secrets = codewhale_secrets::Secrets::auto_detect(); |
| 8991 | // Concurrent connection starts must use the same persisted key; |
| 8992 | // reading and replacing it share the secret store's entry authority. |
| 8993 | secrets |
| 8994 | .with_entry_transaction(COMPUTER_USE_LEDGER_KEY_SLOT, |stored| { |
| 8995 | if let Some(key) = stored.as_ref() |
| 8996 | && key.len() == 64 |
| 8997 | && key.bytes().all(|b| b.is_ascii_hexdigit()) |
| 8998 | { |
| 8999 | return Ok(Some(key.clone())); |
| 9000 | } |
| 9001 | let Ok(bytes) = random_key() else { |
| 9002 | return Ok(None); |
| 9003 | }; |
| 9004 | let key = hex_encode(&bytes); |
| 9005 | *stored = Some(key.clone()); |
| 9006 | Ok(Some(key)) |
| 9007 | }) |
| 9008 | .ok() |
| 9009 | .flatten() |
| 9010 | }) |
| 9011 | .await |
| 9012 | .ok() |
| 9013 | .flatten() |
| 9014 | } |
| 9015 | |
| 9016 | /// User-configured servers that launch the same Computer Use plugin as the |
| 9017 | /// enabled built-in `computer-use` bundle, with the argument that gave each |
| 9018 | /// one away. Two copies advertise every Computer Use schema twice (about |
| 9019 | /// 2.5k tokens on every request) and keep two consent ledgers. Diagnostic |
| 9020 | /// only: callers warn and never remove the user's entry. |
| 9021 | pub fn duplicate_computer_use_servers(config: &McpConfig) -> Vec<(String, String)> { |
| 9022 | let builtin_enabled = config.servers.values().any(|server| { |
| 9023 | server.is_enabled() |
| 9024 | && server |
| 9025 | .reviewed_plugin_source() |
| 9026 | .is_some_and(|source| source.plugin_name() == COMPUTER_USE_PLUGIN_NAME) |
| 9027 | }); |
| 9028 | if !builtin_enabled { |
| 9029 | return Vec::new(); |
| 9030 | } |
| 9031 | let mut duplicates = config |
| 9032 | .servers |
| 9033 | .iter() |
| 9034 | .filter(|(_, server)| server.reviewed_plugin.is_none() && server.is_enabled()) |
| 9035 | .filter_map(|(name, server)| { |
| 9036 | launches_computer_use_plugin(server).map(|arg| (name.clone(), arg)) |
| 9037 | }) |
| 9038 | .collect::<Vec<_>>(); |
| 9039 | duplicates.sort(); |
| 9040 | duplicates |
| 9041 | } |
| 9042 | |
| 9043 | /// The argument naming a Computer Use `mcp/server.mjs`, when this server |
| 9044 | /// runs one: the `plugin.json` next to its `mcp/` directory says |
| 9045 | /// `"name": "computer-use"`, or — when no manifest is readable — the path |
| 9046 | /// has the bundle's shape (`.../computer-use/.../mcp/server.mjs`, any case |
| 9047 | /// or separator). |
| 9048 | fn launches_computer_use_plugin(server: &McpServerConfig) -> Option<String> { |
| 9049 | server.command.as_ref()?; |
| 9050 | server.args.iter().find_map(|arg| { |
| 9051 | let normalized = arg.replace('\\', "/"); |
| 9052 | if !normalized.ends_with("mcp/server.mjs") { |
| 9053 | return None; |
| 9054 | } |
| 9055 | let script = Path::new(arg); |
| 9056 | let script = if script.is_relative() { |
| 9057 | server |
| 9058 | .cwd |
| 9059 | .as_ref() |
| 9060 | .map_or_else(|| script.to_path_buf(), |cwd| cwd.join(script)) |
| 9061 | } else { |
| 9062 | script.to_path_buf() |
| 9063 | }; |
| 9064 | let root = script.parent().and_then(Path::parent); |
| 9065 | if let Some(root) = root |
| 9066 | && let Ok(text) = std::fs::read_to_string(root.join("plugin.json")) |
| 9067 | { |
| 9068 | let name = serde_json::from_str::<serde_json::Value>(&text) |
| 9069 | .ok() |
| 9070 | .and_then(|manifest| manifest.get("name")?.as_str().map(str::to_string)); |
| 9071 | return (name.as_deref() == Some(COMPUTER_USE_PLUGIN_NAME)).then(|| arg.clone()); |
| 9072 | } |
| 9073 | let squashed = normalized.to_ascii_lowercase().replace([' ', '-', '_'], ""); |
| 9074 | squashed.contains("computeruse").then(|| arg.clone()) |
| 9075 | }) |
| 9076 | } |
| 9077 | |
| 9078 | #[cfg(any(test, feature = "test-support"))] |
| 9079 | pub fn generate_desktop_browser_owner_keypair_for_test() -> Vec<u8> { |
| 9080 | ring::signature::Ed25519KeyPair::generate_pkcs8(&ring::rand::SystemRandom::new()) |
| 9081 | .expect("ed25519 pkcs8") |
| 9082 | .as_ref() |
| 9083 | .to_vec() |
| 9084 | } |
| 9085 | |
| 9086 | #[cfg(any(test, feature = "test-support"))] |
| 9087 | pub fn desktop_browser_owner_public_key_for_test(pkcs8: &[u8]) -> String { |
| 9088 | use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; |
| 9089 | use ring::signature::KeyPair as _; |
| 9090 | let pair = ring::signature::Ed25519KeyPair::from_pkcs8(pkcs8).expect("ed25519 pair"); |
| 9091 | URL_SAFE_NO_PAD.encode(pair.public_key().as_ref()) |
| 9092 | } |
| 9093 | |
| 9094 | #[cfg(any(test, feature = "test-support"))] |
| 9095 | pub fn sign_desktop_browser_registration_for_test( |
| 9096 | pkcs8: &[u8], |
| 9097 | workspace: &Path, |
| 9098 | url: &str, |
| 9099 | bearer: &str, |
| 9100 | ) -> String { |
| 9101 | use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; |
| 9102 | let pair = ring::signature::Ed25519KeyPair::from_pkcs8(pkcs8).expect("ed25519 pair"); |
| 9103 | let raw_ws = workspace.to_str().expect("utf8 workspace"); |
| 9104 | let normalized_ws = raw_ws |
| 9105 | .strip_prefix(r"\\?\UNC\") |
| 9106 | .map(|tail| format!(r"\\{tail}")) |
| 9107 | .unwrap_or_else(|| raw_ws.strip_prefix(r"\\?\").unwrap_or(raw_ws).to_owned()); |
| 9108 | let data = format!("codewhale-browser-v2\0{normalized_ws}\0{url}\0{bearer}"); |
| 9109 | URL_SAFE_NO_PAD.encode(pair.sign(data.as_bytes()).as_ref()) |
| 9110 | } |
| 9111 | |
| 9112 | pub fn is_desktop_browser_server(name: &str, server: &McpServerConfig) -> bool { |
| 9113 | name == "codewhale-browser" |
| 9114 | && server.is_enabled() |
| 9115 | && !server.required |
| 9116 | && !server.lazy |
| 9117 | && server.command.is_none() |
| 9118 | && server.args.is_empty() |
| 9119 | && server.env.is_empty() |
| 9120 | && server.cwd.is_none() |
| 9121 | && server.transport.is_none() |
| 9122 | && server.connect_timeout.is_none() |
| 9123 | && server.execute_timeout.is_none() |
| 9124 | && server.read_timeout.is_none() |
| 9125 | && server.enabled_tools.is_empty() |
| 9126 | && server.disabled_tools.is_empty() |
| 9127 | && server.always_allow_tools.is_empty() |
| 9128 | && server.headers.is_empty() |
| 9129 | && server.env_headers.is_empty() |
| 9130 | && server.bearer_token_env_var.as_deref() == Some("CODEWHALE_BROWSER_TOOLS_TOKEN") |
| 9131 | && server.scopes.is_empty() |
| 9132 | && server.oauth.is_none() |
| 9133 | && server.oauth_resource.is_none() |
| 9134 | && server.reviewed_plugin.is_none() |
| 9135 | && !server.allow_private_network |
| 9136 | && server |
| 9137 | .url |
| 9138 | .as_deref() |
| 9139 | .and_then(|url| reqwest::Url::parse(url).ok()) |
| 9140 | .is_some_and(|url| { |
| 9141 | url.scheme() == "http" |
| 9142 | && url.host_str() == Some("127.0.0.1") |
| 9143 | && url.port().is_some_and(|port| port != 0) |
| 9144 | && (url.path() == "/mcp" |
| 9145 | || url.path().strip_prefix("/mcp/").is_some_and(|tag| { |
| 9146 | tag.len() == 43 |
| 9147 | && tag.bytes().all(|byte| { |
| 9148 | byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-' |
| 9149 | }) |
| 9150 | })) |
| 9151 | && url.query().is_none() |
| 9152 | && url.fragment().is_none() |
| 9153 | && url.username().is_empty() |
| 9154 | && url.password().is_none() |
| 9155 | }) |
| 9156 | } |
| 9157 | |
| 9158 | pub fn load_config_with_workspace(global_path: &Path, workspace: &Path) -> Result<McpConfig> { |
| 9159 | let plugins = codewhale_plugins::PluginRegistry::empty(workspace); |
| 9160 | load_config_with_workspace_and_plugins(global_path, workspace, &plugins) |
| 9161 | } |
| 9162 | |
| 9163 | pub fn load_config_with_workspace_and_plugins( |
| 9164 | global_path: &Path, |
| 9165 | workspace: &Path, |
| 9166 | plugins: &codewhale_plugins::PluginRegistry, |
| 9167 | ) -> Result<McpConfig> { |
| 9168 | let mut merged = load_config(global_path)?; |
| 9169 | merged |
| 9170 | .servers |
| 9171 | .retain(|name, server| !is_desktop_browser_server(name, server)); |
| 9172 | let workspace = checked_workspace_path(workspace)?; |
| 9173 | let project_path = checked_workspace_mcp_config_path(&workspace)?; |
| 9174 | if global_path |
| 9175 | .canonicalize() |
| 9176 | .is_ok_and(|path| path.starts_with(&workspace)) |
| 9177 | || paths_refer_to_same_config(global_path, &project_path) |
| 9178 | { |
| 9179 | merged.delegated_operations.clear(); |
| 9180 | } |
| 9181 | if !project_path.exists() || paths_refer_to_same_config(global_path, &project_path) { |
| 9182 | return merge_plugin_mcp_servers(merged, plugins); |
| 9183 | } |
| 9184 | // Workspace-local MCP can spawn stdio servers, so it is only honored after |
| 9185 | // the user has trusted this workspace and approved the exact file contents |
| 9186 | // in user-owned config. Do not accept project-local legacy trust markers |
| 9187 | // here: a repository could carry those files itself and silently |
| 9188 | // reintroduce the project-scope `mcp_config_path` risk denied in #417. |
| 9189 | let Ok(reviewed) = project_authority::approved_project_mcp(&workspace) else { |
| 9190 | return merge_plugin_mcp_servers(merged, plugins); |
| 9191 | }; |
| 9192 | |
| 9193 | let mut project: McpConfig = serde_json::from_str(&reviewed.contents).map_err(|_| { |
| 9194 | anyhow::anyhow!( |
| 9195 | "Failed to parse MCP config {}; file contents were omitted", |
| 9196 | codewhale_config::quote_os_path(&project_path) |
| 9197 | ) |
| 9198 | })?; |
| 9199 | for server in project.servers.values_mut() { |
| 9200 | server.always_allow_tools.clear(); |
| 9201 | if server.command.is_some() && server.url.is_none() { |
| 9202 | server.cwd = Some(resolve_project_mcp_cwd(&workspace, server.cwd.as_deref())?); |
| 9203 | } |
| 9204 | } |
| 9205 | merged |
| 9206 | .delegated_operations |
| 9207 | .retain(|name, _| !project.servers.contains_key(name)); |
| 9208 | merged.servers.extend(project.servers); |
| 9209 | |
| 9210 | merge_plugin_mcp_servers(merged, plugins) |
| 9211 | } |
| 9212 | |
| 9213 | fn merge_plugin_mcp_servers( |
| 9214 | config: McpConfig, |
| 9215 | registry: &codewhale_plugins::PluginRegistry, |
| 9216 | ) -> Result<McpConfig> { |
| 9217 | if registry.state_path().is_none() { |
| 9218 | return Ok(config); |
| 9219 | } |
| 9220 | let plugins = registry |
| 9221 | .active_plugins() |
| 9222 | .into_iter() |
| 9223 | .filter_map(|plugin| { |
| 9224 | registry |
| 9225 | .authority_for(plugin.id.as_str()) |
| 9226 | .map(|authority| (plugin.name().to_string(), plugin.clone(), authority)) |
| 9227 | }) |
| 9228 | .collect::<Vec<_>>(); |
| 9229 | |
| 9230 | let host_environment = registry.host_environment().ok_or_else(|| { |
| 9231 | anyhow::anyhow!("active plugin registry is missing its pre-dotenv environment snapshot") |
| 9232 | })?; |
| 9233 | let mut config = merge_plugin_mcp_servers_from_plugins_with_environment( |
| 9234 | config, |
| 9235 | plugins, |
| 9236 | Arc::clone(&host_environment), |
| 9237 | )?; |
| 9238 | for (name, mut server, authority, receipt) in |
| 9239 | crate::extension_host::native_mcp::for_plugins(registry).map_err(anyhow::Error::msg)? |
| 9240 | { |
| 9241 | let qualified = qualified_plugin_server_name(&authority.plugin_name, &name); |
| 9242 | anyhow::ensure!( |
| 9243 | !config.servers.contains_key(&qualified), |
| 9244 | "Native MCP namespace collides with an existing reviewed or explicit server" |
| 9245 | ); |
| 9246 | if server.command.is_some() { |
| 9247 | let root = codewhale_plugins::agent_plugin::plugin_root_for_manifest( |
| 9248 | &authority.staged_manifest, |
| 9249 | ) |
| 9250 | .context("Native stage has no root")?; |
| 9251 | server.cwd = Some(resolve_plugin_mcp_cwd(root, server.cwd.as_deref())?); |
| 9252 | freeze_plugin_stdio_paths(&mut server, root)?; |
| 9253 | } |
| 9254 | let mut source = ReviewedPluginMcpSource::from_authority( |
| 9255 | authority, |
| 9256 | server.url.as_deref(), |
| 9257 | Arc::clone(&host_environment), |
| 9258 | )?; |
| 9259 | source.native_mcp = Some(receipt); |
| 9260 | server.reviewed_plugin = provenance_of(source); |
| 9261 | config.servers.insert(qualified, server); |
| 9262 | } |
| 9263 | Ok(config) |
| 9264 | } |
| 9265 | |
| 9266 | fn merge_plugin_mcp_servers_from_plugins_with_environment( |
| 9267 | mut config: McpConfig, |
| 9268 | plugins: impl IntoIterator< |
| 9269 | Item = ( |
| 9270 | String, |
| 9271 | codewhale_plugins::types::LoadedPlugin, |
| 9272 | codewhale_config::PluginAuthority, |
| 9273 | ), |
| 9274 | >, |
| 9275 | host_environment: Arc<codewhale_plugins::HostEnvironment>, |
| 9276 | ) -> Result<McpConfig> { |
| 9277 | for (plugin_name, plugin, authority) in plugins { |
| 9278 | // Adapter-level denial keeps headless paths fail-closed even if a |
| 9279 | // future caller accidentally passes the full inventory instead of the |
| 9280 | // registry's active-only view. |
| 9281 | if !plugin.active() { |
| 9282 | continue; |
| 9283 | } |
| 9284 | if let Some(mcp_servers) = &plugin.manifest.mcp_servers { |
| 9285 | let mut mcp_servers = mcp_servers.iter().collect::<Vec<_>>(); |
| 9286 | mcp_servers.sort_by_key(|(name, _)| *name); |
| 9287 | for (server_name, server_config) in mcp_servers { |
| 9288 | let required_capability = if server_config.command.is_some() |
| 9289 | && server_config.url.is_none() |
| 9290 | { |
| 9291 | codewhale_plugins::activation::PluginActivationCapability::McpStdio |
| 9292 | } else if server_config.url.is_some() && server_config.command.is_none() { |
| 9293 | codewhale_plugins::activation::PluginActivationCapability::McpRemote |
| 9294 | } else { |
| 9295 | tracing::warn!( |
| 9296 | target: "mcp", |
| 9297 | plugin = %plugin_name, |
| 9298 | server = %server_name, |
| 9299 | "plugin MCP server is neither a reviewed stdio nor remote transport; denying it" |
| 9300 | ); |
| 9301 | continue; |
| 9302 | }; |
| 9303 | if !plugin.component_active(required_capability) |
| 9304 | || codewhale_plugins::registry::verify_plugin_component_authority( |
| 9305 | &authority, |
| 9306 | required_capability, |
| 9307 | ) |
| 9308 | .is_err() |
| 9309 | { |
| 9310 | tracing::warn!( |
| 9311 | target: "mcp", |
| 9312 | plugin = %plugin_name, |
| 9313 | server = %server_name, |
| 9314 | capability = required_capability.as_str(), |
| 9315 | "plugin bundle changed after review or this transport is inactive; denying the MCP server until reload and re-review" |
| 9316 | ); |
| 9317 | continue; |
| 9318 | } |
| 9319 | let qualified_name = qualified_plugin_server_name(&plugin_name, server_name); |
| 9320 | if config.servers.contains_key(&qualified_name) { |
| 9321 | tracing::warn!( |
| 9322 | target: "mcp", |
| 9323 | plugin = %plugin_name, |
| 9324 | server = %server_name, |
| 9325 | qualified_name = %qualified_name, |
| 9326 | "explicit MCP configuration keeps precedence over a colliding plugin server" |
| 9327 | ); |
| 9328 | continue; |
| 9329 | } |
| 9330 | let mut server_config = server_config.clone(); |
| 9331 | |
| 9332 | if server_config.command.is_some() && server_config.url.is_none() { |
| 9333 | let staged_root = plugin |
| 9334 | .staged_root |
| 9335 | .as_deref() |
| 9336 | .context("active plugin is missing its runtime snapshot")?; |
| 9337 | server_config.cwd = Some(resolve_plugin_mcp_cwd( |
| 9338 | staged_root, |
| 9339 | server_config.cwd.as_deref(), |
| 9340 | )?); |
| 9341 | freeze_plugin_stdio_paths(&mut server_config, staged_root)?; |
| 9342 | } |
| 9343 | server_config.reviewed_plugin = |
| 9344 | provenance_of(ReviewedPluginMcpSource::from_authority( |
| 9345 | authority.clone(), |
| 9346 | server_config.url.as_deref(), |
| 9347 | Arc::clone(&host_environment), |
| 9348 | )?); |
| 9349 | |
| 9350 | config.servers.insert(qualified_name, server_config); |
| 9351 | } |
| 9352 | } |
| 9353 | } |
| 9354 | |
| 9355 | Ok(config) |
| 9356 | } |
| 9357 | |
| 9358 | #[cfg(test)] |
| 9359 | fn merge_plugin_mcp_servers_from_plugins( |
| 9360 | config: McpConfig, |
| 9361 | plugins: impl IntoIterator< |
| 9362 | Item = ( |
| 9363 | String, |
| 9364 | codewhale_plugins::types::LoadedPlugin, |
| 9365 | codewhale_config::PluginAuthority, |
| 9366 | ), |
| 9367 | >, |
| 9368 | ) -> Result<McpConfig> { |
| 9369 | merge_plugin_mcp_servers_from_plugins_with_environment( |
| 9370 | config, |
| 9371 | plugins, |
| 9372 | Arc::new(codewhale_plugins::HostEnvironment::capture()), |
| 9373 | ) |
| 9374 | } |
| 9375 | |
| 9376 | /// Split a qualified plugin server key back into `(plugin, server)`. |
| 9377 | /// |
| 9378 | /// The length prefix written by [`qualified_plugin_server_name`] exists so |
| 9379 | /// this split is unambiguous even when a plugin or server name contains `-`. |
| 9380 | /// Display surfaces use it to show `codewhale-account-plugins/codewhale-plugins` |
| 9381 | /// instead of the wire key `plugin-25-codewhale-account-plugins-codewhale-plugins`, |
| 9382 | /// which reads as noise in a list and tells a person nothing. |
| 9383 | #[must_use] |
| 9384 | pub fn split_qualified_plugin_server_name(qualified: &str) -> Option<(&str, &str)> { |
| 9385 | let rest = qualified.strip_prefix("plugin-")?; |
| 9386 | let (len, rest) = rest.split_once('-')?; |
| 9387 | let len: usize = len.parse().ok()?; |
| 9388 | if !rest.is_char_boundary(len) { |
| 9389 | return None; |
| 9390 | } |
| 9391 | let (plugin, server) = rest.split_at(len); |
| 9392 | Some((plugin, server.strip_prefix('-')?)) |
| 9393 | } |
| 9394 | |
| 9395 | pub fn qualified_plugin_server_name(plugin_name: &str, server_name: &str) -> String { |
| 9396 | format!( |
| 9397 | "plugin-{}-{}-{}", |
| 9398 | plugin_name.len(), |
| 9399 | plugin_name, |
| 9400 | server_name |
| 9401 | ) |
| 9402 | } |
| 9403 | |
| 9404 | fn freeze_plugin_stdio_paths(config: &mut McpServerConfig, staged_root: &Path) -> Result<()> { |
| 9405 | if let Some(command) = config.command.as_mut() |
| 9406 | && (command.contains('/') || command.contains('\\')) |
| 9407 | { |
| 9408 | let frozen = resolve_plugin_mcp_cwd(staged_root, Some(Path::new(command)))?; |
| 9409 | *command = frozen.display().to_string(); |
| 9410 | } |
| 9411 | let runtime_cwd = config.cwd.as_deref().unwrap_or(staged_root).to_path_buf(); |
| 9412 | for argument in &mut config.args { |
| 9413 | if argument.starts_with('-') || Path::new(argument).is_absolute() { |
| 9414 | continue; |
| 9415 | } |
| 9416 | let candidate = normalize_path_components(&runtime_cwd.join(argument.as_str())); |
| 9417 | if candidate.exists() { |
| 9418 | let frozen = candidate |
| 9419 | .canonicalize() |
| 9420 | .context("failed to freeze reviewed plugin MCP argument path")?; |
| 9421 | if !frozen.starts_with(staged_root) { |
| 9422 | anyhow::bail!("reviewed plugin MCP argument path escaped its staged root"); |
| 9423 | } |
| 9424 | *argument = frozen.display().to_string(); |
| 9425 | } |
| 9426 | } |
| 9427 | Ok(()) |
| 9428 | } |
| 9429 | |
| 9430 | fn resolve_plugin_mcp_cwd(plugin_path: &Path, cwd: Option<&Path>) -> Result<PathBuf> { |
| 9431 | let cwd = match cwd { |
| 9432 | Some(cwd) if cwd.is_relative() => normalize_path_components(&plugin_path.join(cwd)), |
| 9433 | Some(cwd) => normalize_path_components(cwd), |
| 9434 | None => plugin_path.to_path_buf(), |
| 9435 | }; |
| 9436 | let resolved = cwd |
| 9437 | .canonicalize() |
| 9438 | .unwrap_or_else(|_| normalize_path_components(&cwd)); |
| 9439 | if !resolved.starts_with(plugin_path) { |
| 9440 | anyhow::bail!("reviewed plugin MCP path escaped its staged root"); |
| 9441 | } |
| 9442 | Ok(resolved) |
| 9443 | } |
| 9444 | |
| 9445 | fn checked_workspace_mcp_config_path(workspace: &Path) -> Result<PathBuf> { |
| 9446 | Ok(checked_workspace_path(workspace)? |
| 9447 | .join(".codewhale") |
| 9448 | .join("mcp.json")) |
| 9449 | } |
| 9450 | |
| 9451 | fn checked_workspace_path(workspace: &Path) -> Result<PathBuf> { |
| 9452 | if workspace.as_os_str().is_empty() { |
| 9453 | anyhow::bail!("workspace path cannot be empty"); |
| 9454 | } |
| 9455 | if workspace |
| 9456 | .components() |
| 9457 | .any(|component| matches!(component, Component::ParentDir)) |
| 9458 | { |
| 9459 | anyhow::bail!("workspace path cannot contain '..' components"); |
| 9460 | } |
| 9461 | let absolute = if workspace.is_absolute() { |
| 9462 | workspace.to_path_buf() |
| 9463 | } else { |
| 9464 | std::env::current_dir() |
| 9465 | .context("failed to resolve current directory for workspace")? |
| 9466 | .join(workspace) |
| 9467 | }; |
| 9468 | match absolute.canonicalize() { |
| 9469 | Ok(path) => Ok(path), |
| 9470 | Err(err) if err.kind() == std::io::ErrorKind::NotFound => { |
| 9471 | Ok(normalize_path_components(&absolute)) |
| 9472 | } |
| 9473 | Err(err) => { |
| 9474 | Err(err).with_context(|| format!("failed to resolve workspace {}", workspace.display())) |
| 9475 | } |
| 9476 | } |
| 9477 | } |
| 9478 | |
| 9479 | fn normalize_workspace_path(workspace: &Path) -> PathBuf { |
| 9480 | if let Ok(canonical) = workspace.canonicalize() { |
| 9481 | return canonical; |
| 9482 | } |
| 9483 | let absolute = if workspace.is_absolute() { |
| 9484 | workspace.to_path_buf() |
| 9485 | } else { |
| 9486 | std::env::current_dir() |
| 9487 | .unwrap_or_else(|_| PathBuf::from(".")) |
| 9488 | .join(workspace) |
| 9489 | }; |
| 9490 | normalize_path_components(&absolute) |
| 9491 | } |
| 9492 | |
| 9493 | fn resolve_project_mcp_cwd(workspace: &Path, cwd: Option<&Path>) -> Result<PathBuf> { |
| 9494 | let cwd = match cwd { |
| 9495 | Some(cwd) if cwd.is_relative() => normalize_path_components(&workspace.join(cwd)), |
| 9496 | Some(cwd) => normalize_path_components(cwd), |
| 9497 | None => workspace.to_path_buf(), |
| 9498 | }; |
| 9499 | let resolved = cwd |
| 9500 | .canonicalize() |
| 9501 | .unwrap_or_else(|_| normalize_path_components(&cwd)); |
| 9502 | if !resolved.starts_with(workspace) { |
| 9503 | anyhow::bail!( |
| 9504 | "Project MCP server cwd must stay within workspace: {}", |
| 9505 | resolved.display() |
| 9506 | ); |
| 9507 | } |
| 9508 | Ok(resolved) |
| 9509 | } |
| 9510 | |
| 9511 | /// Drop the Win32 verbatim prefix before handing a path to an external child |
| 9512 | /// (Node MCP peers, etc.). `Path::canonicalize` returns `\\?\C:\...`; Node's |
| 9513 | /// ESM loader and several Windows tools refuse or mis-handle that spelling for |
| 9514 | /// ordinary paths under MAX_PATH. Containment checks keep the prefixed form; |
| 9515 | /// only argv and current_dir are rewritten. Same rule as runtime_api job cwd |
| 9516 | /// and Git for Windows. |
| 9517 | #[cfg(any(windows, test))] |
| 9518 | fn plain_windows_child_path(path: &str) -> String { |
| 9519 | if let Some(rest) = path.strip_prefix(r"\\?\UNC\") { |
| 9520 | return format!(r"\\{rest}"); |
| 9521 | } |
| 9522 | match path.strip_prefix(r"\\?\") { |
| 9523 | Some(rest) |
| 9524 | if rest.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) |
| 9525 | && rest.as_bytes().get(1) == Some(&b':') => |
| 9526 | { |
| 9527 | rest.to_string() |
| 9528 | } |
| 9529 | _ => path.to_string(), |
| 9530 | } |
| 9531 | } |
| 9532 | |
| 9533 | #[cfg(windows)] |
| 9534 | pub fn strip_windows_verbatim_for_child(path: impl AsRef<std::ffi::OsStr>) -> std::ffi::OsString { |
| 9535 | let raw = path.as_ref().to_string_lossy(); |
| 9536 | std::ffi::OsString::from(plain_windows_child_path(&raw)) |
| 9537 | } |
| 9538 | |
| 9539 | #[cfg(not(windows))] |
| 9540 | pub fn strip_windows_verbatim_for_child(path: impl AsRef<std::ffi::OsStr>) -> std::ffi::OsString { |
| 9541 | path.as_ref().to_os_string() |
| 9542 | } |
| 9543 | |
| 9544 | fn normalize_path_components(path: &Path) -> PathBuf { |
| 9545 | let mut normalized = PathBuf::new(); |
| 9546 | for component in path.components() { |
| 9547 | match component { |
| 9548 | Component::Prefix(_) | Component::RootDir => { |
| 9549 | normalized.push(component.as_os_str()); |
| 9550 | } |
| 9551 | Component::CurDir => {} |
| 9552 | Component::ParentDir => { |
| 9553 | normalized.pop(); |
| 9554 | } |
| 9555 | Component::Normal(part) => normalized.push(part), |
| 9556 | } |
| 9557 | } |
| 9558 | if normalized.as_os_str().is_empty() { |
| 9559 | PathBuf::from(".") |
| 9560 | } else { |
| 9561 | normalized |
| 9562 | } |
| 9563 | } |
| 9564 | |
| 9565 | fn paths_refer_to_same_config(left: &Path, right: &Path) -> bool { |
| 9566 | match (left.canonicalize(), right.canonicalize()) { |
| 9567 | (Ok(left), Ok(right)) => left == right, |
| 9568 | _ => normalize_workspace_path(left) == normalize_workspace_path(right), |
| 9569 | } |
| 9570 | } |
| 9571 | |
| 9572 | /// Rebuild a JSON value with every object's keys in sorted order. |
| 9573 | /// |
| 9574 | /// [`McpConfig`] is full of `HashMap`s (`servers`, and per-server `env`, |
| 9575 | /// `headers`, `env_headers`), and `serde_json` is built here with |
| 9576 | /// `preserve_order`, so a serialization inherits whatever order the source |
| 9577 | /// `HashMap` happened to iterate in. Two `HashMap`s built separately in one |
| 9578 | /// process do *not* share an iteration order — `RandomState` re-seeds per map |
| 9579 | /// — so the raw serialization of two structurally identical configs differs. |
| 9580 | /// Sorting first makes the byte form depend only on content. The value tree |
| 9581 | /// here is the fixed `McpConfig` shape, so the recursion depth is bounded by |
| 9582 | /// that struct, not by untrusted input. |
| 9583 | fn canonicalize_json_keys(value: serde_json::Value) -> serde_json::Value { |
| 9584 | match value { |
| 9585 | serde_json::Value::Object(map) => { |
| 9586 | let mut entries: Vec<(String, serde_json::Value)> = map.into_iter().collect(); |
| 9587 | entries.sort_by(|(left, _), (right, _)| left.cmp(right)); |
| 9588 | serde_json::Value::Object( |
| 9589 | entries |
| 9590 | .into_iter() |
| 9591 | .map(|(key, value)| (key, canonicalize_json_keys(value))) |
| 9592 | .collect(), |
| 9593 | ) |
| 9594 | } |
| 9595 | serde_json::Value::Array(items) => { |
| 9596 | serde_json::Value::Array(items.into_iter().map(canonicalize_json_keys).collect()) |
| 9597 | } |
| 9598 | other => other, |
| 9599 | } |
| 9600 | } |
| 9601 | |
| 9602 | /// 64-bit content hash of an [`McpConfig`]. Used by [`McpPool`] to decide |
| 9603 | /// whether a freshly-read config differs from the one currently driving the |
| 9604 | /// live connections. Hashing the JSON serialization avoids forcing every |
| 9605 | /// nested config type to derive `Hash` (the timeouts struct, network policy |
| 9606 | /// stubs, etc.); the serialization is key-sorted first so the hash depends on |
| 9607 | /// content alone and not on per-`HashMap` iteration order. The hash is stable |
| 9608 | /// within a process for structurally identical configs, and across runs of the |
| 9609 | /// same Rust toolchain for byte-identical input. |
| 9610 | fn hash_mcp_config(config: &McpConfig) -> u64 { |
| 9611 | use std::hash::{Hash, Hasher}; |
| 9612 | let canonical = serde_json::to_value(config) |
| 9613 | .map(canonicalize_json_keys) |
| 9614 | .unwrap_or(serde_json::Value::Null); |
| 9615 | let bytes = serde_json::to_vec(&canonical).unwrap_or_default(); |
| 9616 | let mut hasher = std::collections::hash_map::DefaultHasher::new(); |
| 9617 | bytes.hash(&mut hasher); |
| 9618 | let mut native = config |
| 9619 | .servers |
| 9620 | .iter() |
| 9621 | .filter_map(|(name, server)| { |
| 9622 | Some(( |
| 9623 | name, |
| 9624 | server |
| 9625 | .reviewed_plugin_source()? |
| 9626 | .native_mcp |
| 9627 | .as_ref()? |
| 9628 | .catalog_identity(), |
| 9629 | )) |
| 9630 | }) |
| 9631 | .collect::<Vec<_>>(); |
| 9632 | native.sort_by_key(|(name, _)| *name); |
| 9633 | native.hash(&mut hasher); |
| 9634 | hasher.finish() |
| 9635 | } |
| 9636 | |
| 9637 | /// Best-effort fetch of the MCP config file's last-modified time. Returns |
| 9638 | /// `None` when the file is missing, when stat fails, when the platform |
| 9639 | /// doesn't expose mtime, or when the path fails the same allow-list check |
| 9640 | /// that MCP configuration reads and mutations apply. The lazy-reload check in |
| 9641 | /// `McpPool::get_or_connect` treats `None` as "skip the check this turn", |
| 9642 | /// so a rejected path simply degrades to "no auto-reload" rather than an |
| 9643 | /// error path. Callers already validate via `validate_mcp_config_path` at |
| 9644 | /// construction time; the redundant validation here keeps this helper |
| 9645 | /// safe-by-construction for any future caller and ties the validation to |
| 9646 | /// the call site rather than relying on cross-function reasoning. |
| 9647 | fn mcp_config_mtime(path: &Path) -> Option<std::time::SystemTime> { |
| 9648 | validate_mcp_config_path(path).ok()?; |
| 9649 | fs::metadata(path).ok()?.modified().ok() |
| 9650 | } |
| 9651 | |
| 9652 | /// A stale caller must reload instead of overwriting another process's edit. |
| 9653 | #[derive(Debug)] |
| 9654 | pub struct McpRevisionConflict; |
| 9655 | impl std::fmt::Display for McpRevisionConflict { |
| 9656 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 9657 | f.write_str("MCP configuration changed; reload it before saving") |
| 9658 | } |
| 9659 | } |
| 9660 | impl std::error::Error for McpRevisionConflict {} |
| 9661 | |
| 9662 | fn config_revision(raw: Option<&str>) -> String { |
| 9663 | raw.map_or_else( |
| 9664 | || "mcp-v1-absent".to_owned(), |
| 9665 | |raw| { |
| 9666 | format!( |
| 9667 | "mcp-v1-{}", |
| 9668 | codewhale_runtime::hashing::sha256_hex(raw.as_bytes()) |
| 9669 | ) |
| 9670 | }, |
| 9671 | ) |
| 9672 | } |
| 9673 | |
| 9674 | pub fn read_config_revision(path: &Path) -> Result<String> { |
| 9675 | validate_mcp_config_path(path)?; |
| 9676 | let raw = read_mcp_config_file(path)?; |
| 9677 | Ok(config_revision(raw.as_deref())) |
| 9678 | } |
| 9679 | |
| 9680 | /// Apply only changed known fields to the original JSON. Unknown fields in |
| 9681 | /// unrelated objects and in edited server entries remain operator-owned. |
| 9682 | fn apply_json_delta( |
| 9683 | raw: &mut serde_json::Value, |
| 9684 | before: &serde_json::Value, |
| 9685 | after: &serde_json::Value, |
| 9686 | ) { |
| 9687 | if before == after { |
| 9688 | return; |
| 9689 | } |
| 9690 | if let (Some(raw), Some(before), Some(after)) = |
| 9691 | (raw.as_object_mut(), before.as_object(), after.as_object()) |
| 9692 | { |
| 9693 | for key in before.keys().chain(after.keys()).collect::<BTreeSet<_>>() { |
| 9694 | match (before.get(key), after.get(key)) { |
| 9695 | (Some(old), Some(new)) if old != new => { |
| 9696 | apply_json_delta(raw.entry(key.clone()).or_insert(old.clone()), old, new); |
| 9697 | } |
| 9698 | (None, Some(new)) => { |
| 9699 | raw.insert(key.clone(), new.clone()); |
| 9700 | } |
| 9701 | (Some(_), None) => { |
| 9702 | raw.remove(key); |
| 9703 | } |
| 9704 | _ => {} |
| 9705 | } |
| 9706 | } |
| 9707 | } else { |
| 9708 | *raw = after.clone(); |
| 9709 | } |
| 9710 | } |
| 9711 | |
| 9712 | /// Every managed MCP writer rereads under the same OS-process lock. This is |
| 9713 | /// a delta operation, not a save of a previously loaded typed snapshot. |
| 9714 | pub fn mutate_config<T>( |
| 9715 | path: &Path, |
| 9716 | expected_revision: Option<&str>, |
| 9717 | mutate: impl FnOnce(&mut McpConfig) -> Result<T>, |
| 9718 | ) -> Result<(T, String)> { |
| 9719 | validate_mcp_config_path(path)?; |
| 9720 | reject_linked_workspace_state_path(path)?; |
| 9721 | codewhale_config::with_config_write_lock(path, |path| { |
| 9722 | let original = read_mcp_config_file(path)?; |
| 9723 | let revision = config_revision(original.as_deref()); |
| 9724 | if expected_revision.is_some_and(|expected| expected != revision) { |
| 9725 | return Err(McpRevisionConflict.into()); |
| 9726 | } |
| 9727 | let mut raw: serde_json::Value = match original.as_deref() { |
| 9728 | Some(raw) => serde_json::from_str(raw).map_err(|_| { |
| 9729 | anyhow::anyhow!("Failed to parse MCP config; file contents were omitted") |
| 9730 | })?, |
| 9731 | None => serde_json::json!({}), |
| 9732 | }; |
| 9733 | anyhow::ensure!(raw.is_object(), "MCP config must be an object"); |
| 9734 | let mut config: McpConfig = serde_json::from_value(raw.clone()) |
| 9735 | .map_err(|_| anyhow::anyhow!("Invalid MCP config; file contents were omitted"))?; |
| 9736 | let before = serde_json::to_value(&config)?; |
| 9737 | let result = mutate(&mut config)?; |
| 9738 | let after = serde_json::to_value(&config)?; |
| 9739 | if before == after { |
| 9740 | return Ok((result, revision)); |
| 9741 | } |
| 9742 | // Preserve legacy spelling while applying the canonical typed delta. |
| 9743 | let legacy = raw.get("mcpServers").is_some(); |
| 9744 | if legacy { |
| 9745 | let object = raw |
| 9746 | .as_object_mut() |
| 9747 | .context("MCP config must be an object")?; |
| 9748 | let servers = object.remove("mcpServers").expect("checked above"); |
| 9749 | object.insert("servers".into(), servers); |
| 9750 | } |
| 9751 | apply_json_delta(&mut raw, &before, &after); |
| 9752 | if legacy { |
| 9753 | let object = raw |
| 9754 | .as_object_mut() |
| 9755 | .context("MCP config must be an object")?; |
| 9756 | if let Some(servers) = object.remove("servers") { |
| 9757 | object.insert("mcpServers".into(), servers); |
| 9758 | } |
| 9759 | } |
| 9760 | let rendered = serde_json::to_string_pretty(&raw)?; |
| 9761 | if rendered.len() as u64 > MAX_MCP_CONFIG_BYTES { |
| 9762 | anyhow::bail!("MCP config exceeds the 1 MiB limit"); |
| 9763 | } |
| 9764 | write_atomic(path, rendered.as_bytes()) |
| 9765 | .with_context(|| format!("Failed to write MCP config {}", path.display()))?; |
| 9766 | project_authority::carry_approval_across_product_edit( |
| 9767 | path, |
| 9768 | original.as_deref(), |
| 9769 | &rendered, |
| 9770 | )?; |
| 9771 | Ok((result, config_revision(Some(&rendered)))) |
| 9772 | }) |
| 9773 | } |
| 9774 | |
| 9775 | fn mcp_template_json() -> Result<String> { |
| 9776 | let mut cfg = McpConfig::default(); |
| 9777 | cfg.servers.insert( |
| 9778 | "example".to_string(), |
| 9779 | McpServerConfig { |
| 9780 | command: Some("node".to_string()), |
| 9781 | args: vec!["./path/to/your-mcp-server.js".to_string()], |
| 9782 | env: HashMap::new(), |
| 9783 | cwd: None, |
| 9784 | url: None, |
| 9785 | transport: None, |
| 9786 | connect_timeout: None, |
| 9787 | execute_timeout: None, |
| 9788 | read_timeout: None, |
| 9789 | disabled: true, |
| 9790 | enabled: true, |
| 9791 | required: false, |
| 9792 | lazy: false, |
| 9793 | enabled_tools: Vec::new(), |
| 9794 | disabled_tools: Vec::new(), |
| 9795 | always_allow_tools: Vec::new(), |
| 9796 | headers: HashMap::new(), |
| 9797 | env_headers: HashMap::new(), |
| 9798 | bearer_token_env_var: None, |
| 9799 | scopes: Vec::new(), |
| 9800 | oauth: None, |
| 9801 | oauth_resource: None, |
| 9802 | reviewed_plugin: None, |
| 9803 | runtime_added: false, |
| 9804 | allow_private_network: false, |
| 9805 | }, |
| 9806 | ); |
| 9807 | serde_json::to_string_pretty(&cfg).context("Failed to render MCP template JSON") |
| 9808 | } |
| 9809 | |
| 9810 | pub fn init_config(path: &Path, force: bool) -> Result<McpWriteStatus> { |
| 9811 | validate_mcp_config_path(path)?; |
| 9812 | reject_linked_workspace_state_path(path)?; |
| 9813 | codewhale_config::with_config_write_lock(path, |path| { |
| 9814 | let original = read_mcp_config_file(path)?; |
| 9815 | if let Some(raw) = original.as_deref() { |
| 9816 | let _: McpConfig = serde_json::from_str(raw) |
| 9817 | .map_err(|_| anyhow::anyhow!("Invalid MCP config; file contents were omitted"))?; |
| 9818 | if !force { |
| 9819 | return Ok(McpWriteStatus::SkippedExists); |
| 9820 | } |
| 9821 | } |
| 9822 | let template = mcp_template_json()?; |
| 9823 | write_atomic(path, template.as_bytes())?; |
| 9824 | Ok(if original.is_some() { |
| 9825 | McpWriteStatus::Overwritten |
| 9826 | } else { |
| 9827 | McpWriteStatus::Created |
| 9828 | }) |
| 9829 | }) |
| 9830 | } |
| 9831 | |
| 9832 | pub fn add_server_config( |
| 9833 | path: &Path, |
| 9834 | name: String, |
| 9835 | command: Option<String>, |
| 9836 | url: Option<String>, |
| 9837 | args: Vec<String>, |
| 9838 | transport: Option<String>, |
| 9839 | ) -> Result<()> { |
| 9840 | if command.is_none() && url.is_none() { |
| 9841 | anyhow::bail!("Provide either a command or URL for MCP server '{name}'."); |
| 9842 | } |
| 9843 | validate_mcp_transport(transport.as_deref())?; |
| 9844 | mutate_config(path, None, |cfg| { |
| 9845 | cfg.servers.insert( |
| 9846 | name, |
| 9847 | McpServerConfig { |
| 9848 | command, |
| 9849 | args, |
| 9850 | env: HashMap::new(), |
| 9851 | cwd: None, |
| 9852 | url, |
| 9853 | transport, |
| 9854 | connect_timeout: None, |
| 9855 | execute_timeout: None, |
| 9856 | read_timeout: None, |
| 9857 | disabled: false, |
| 9858 | enabled: true, |
| 9859 | required: false, |
| 9860 | lazy: false, |
| 9861 | enabled_tools: Vec::new(), |
| 9862 | disabled_tools: Vec::new(), |
| 9863 | always_allow_tools: Vec::new(), |
| 9864 | headers: HashMap::new(), |
| 9865 | env_headers: HashMap::new(), |
| 9866 | bearer_token_env_var: None, |
| 9867 | scopes: Vec::new(), |
| 9868 | oauth: None, |
| 9869 | oauth_resource: None, |
| 9870 | reviewed_plugin: None, |
| 9871 | runtime_added: false, |
| 9872 | allow_private_network: false, |
| 9873 | }, |
| 9874 | ); |
| 9875 | Ok(()) |
| 9876 | }) |
| 9877 | .map(|_| ()) |
| 9878 | } |
| 9879 | |
| 9880 | pub fn remove_server_config(path: &Path, name: &str) -> Result<()> { |
| 9881 | mutate_config(path, None, |cfg| { |
| 9882 | if cfg.servers.remove(name).is_none() { |
| 9883 | anyhow::bail!("MCP server '{name}' not found"); |
| 9884 | } |
| 9885 | Ok(()) |
| 9886 | }) |
| 9887 | .map(|_| ()) |
| 9888 | } |
| 9889 | |
| 9890 | pub fn set_server_enabled(path: &Path, name: &str, enabled: bool) -> Result<()> { |
| 9891 | mutate_config(path, None, |cfg| { |
| 9892 | let server = cfg |
| 9893 | .servers |
| 9894 | .get_mut(name) |
| 9895 | .ok_or_else(|| anyhow::anyhow!("MCP server '{name}' not found"))?; |
| 9896 | server.enabled = enabled; |
| 9897 | server.disabled = !enabled; |
| 9898 | Ok(()) |
| 9899 | }) |
| 9900 | .map(|_| ()) |
| 9901 | } |
| 9902 | |
| 9903 | #[cfg(any(test, feature = "test-support"))] |
| 9904 | pub fn manager_snapshot_from_config( |
| 9905 | path: &Path, |
| 9906 | reload_required: bool, |
| 9907 | ) -> Result<McpManagerSnapshot> { |
| 9908 | let cfg = load_config(path)?; |
| 9909 | Ok(snapshot_from_config( |
| 9910 | path, |
| 9911 | path.exists(), |
| 9912 | reload_required, |
| 9913 | &cfg, |
| 9914 | None, |
| 9915 | )) |
| 9916 | } |
| 9917 | |
| 9918 | #[cfg(any(test, feature = "test-support"))] |
| 9919 | pub fn manager_snapshot_from_config_with_workspace( |
| 9920 | path: &Path, |
| 9921 | workspace: &Path, |
| 9922 | reload_required: bool, |
| 9923 | ) -> Result<McpManagerSnapshot> { |
| 9924 | let plugins = codewhale_plugins::PluginRegistry::empty(workspace); |
| 9925 | manager_snapshot_from_config_with_workspace_and_plugins( |
| 9926 | path, |
| 9927 | workspace, |
| 9928 | reload_required, |
| 9929 | &plugins, |
| 9930 | ) |
| 9931 | } |
| 9932 | |
| 9933 | pub fn manager_snapshot_from_config_with_workspace_and_plugins( |
| 9934 | path: &Path, |
| 9935 | workspace: &Path, |
| 9936 | reload_required: bool, |
| 9937 | plugins: &codewhale_plugins::PluginRegistry, |
| 9938 | ) -> Result<McpManagerSnapshot> { |
| 9939 | let cfg = load_config_with_workspace_and_plugins(path, workspace, plugins)?; |
| 9940 | Ok(snapshot_from_config( |
| 9941 | path, |
| 9942 | path.exists(), |
| 9943 | reload_required, |
| 9944 | &cfg, |
| 9945 | None, |
| 9946 | )) |
| 9947 | } |
| 9948 | |
| 9949 | #[cfg(any(test, feature = "test-support"))] |
| 9950 | pub async fn discover_manager_snapshot( |
| 9951 | path: &Path, |
| 9952 | network_policy: Option<NetworkPolicyDecider>, |
| 9953 | reload_required: bool, |
| 9954 | ) -> Result<McpManagerSnapshot> { |
| 9955 | let cfg = load_config(path)?; |
| 9956 | let mut pool = McpPool::new(cfg.clone()).with_backend(McpBackend::Rust); |
| 9957 | if let Some(policy) = network_policy { |
| 9958 | pool = pool.with_network_policy(policy); |
| 9959 | } |
| 9960 | let errors = pool |
| 9961 | .connect_all() |
| 9962 | .await |
| 9963 | .into_iter() |
| 9964 | .map(|(name, err)| (name, format_mcp_error_for_display(&err))) |
| 9965 | .collect::<HashMap<_, _>>(); |
| 9966 | Ok(snapshot_from_config( |
| 9967 | path, |
| 9968 | path.exists(), |
| 9969 | reload_required, |
| 9970 | &cfg, |
| 9971 | Some((&pool, &errors)), |
| 9972 | )) |
| 9973 | } |
| 9974 | |
| 9975 | pub async fn discover_manager_snapshot_with_workspace_and_plugins( |
| 9976 | path: &Path, |
| 9977 | workspace: &Path, |
| 9978 | network_policy: Option<NetworkPolicyDecider>, |
| 9979 | reload_required: bool, |
| 9980 | plugins: Arc<codewhale_plugins::PluginRegistry>, |
| 9981 | backend: McpBackend, |
| 9982 | ) -> Result<McpManagerSnapshot> { |
| 9983 | let cfg = load_config_with_workspace_and_plugins(path, workspace, plugins.as_ref())?; |
| 9984 | let mut pool = McpPool::new(cfg.clone()).with_backend(backend); |
| 9985 | pool.workspace = Some(checked_workspace_path(workspace)?); |
| 9986 | pool.plugin_registry = Some(plugins); |
| 9987 | if let Some(policy) = network_policy { |
| 9988 | pool = pool.with_network_policy(policy); |
| 9989 | } |
| 9990 | let errors = pool |
| 9991 | .connect_all() |
| 9992 | .await |
| 9993 | .into_iter() |
| 9994 | .map(|(name, err)| (name, format_mcp_error_for_display(&err))) |
| 9995 | .collect::<HashMap<_, _>>(); |
| 9996 | Ok(snapshot_from_config( |
| 9997 | path, |
| 9998 | path.exists(), |
| 9999 | reload_required, |
| 10000 | &cfg, |
| 10001 | Some((&pool, &errors)), |
| 10002 | )) |
| 10003 | } |
| 10004 | |
| 10005 | pub fn format_mcp_error_for_display(error: &anyhow::Error) -> String { |
| 10006 | codewhale_config::persistence::redact_secrets(&format!("{error:#}")) |
| 10007 | } |
| 10008 | |
| 10009 | impl McpPool { |
| 10010 | /// Snapshot the live pool rather than starting a second discovery pool. |
| 10011 | /// This keeps the manager, hotbar, and next model turn aligned on one |
| 10012 | /// exact config/catalog generation. |
| 10013 | pub fn manager_snapshot( |
| 10014 | &self, |
| 10015 | path: &Path, |
| 10016 | reload_required: bool, |
| 10017 | errors: &HashMap<String, String>, |
| 10018 | ) -> McpManagerSnapshot { |
| 10019 | let mut config = self.config.clone(); |
| 10020 | for (name, server) in self.dynamic_servers.read().iter() { |
| 10021 | config |
| 10022 | .servers |
| 10023 | .entry(name.clone()) |
| 10024 | .or_insert_with(|| server.clone()); |
| 10025 | } |
| 10026 | snapshot_from_config( |
| 10027 | path, |
| 10028 | path.exists(), |
| 10029 | reload_required, |
| 10030 | &config, |
| 10031 | Some((self, errors)), |
| 10032 | ) |
| 10033 | } |
| 10034 | } |
| 10035 | |
| 10036 | fn snapshot_from_config( |
| 10037 | path: &Path, |
| 10038 | config_exists: bool, |
| 10039 | reload_required: bool, |
| 10040 | cfg: &McpConfig, |
| 10041 | discovery: Option<(&McpPool, &HashMap<String, String>)>, |
| 10042 | ) -> McpManagerSnapshot { |
| 10043 | let mut servers = cfg |
| 10044 | .servers |
| 10045 | .iter() |
| 10046 | .filter(|(name, _)| discovery.is_none_or(|(pool, _)| pool.server_allowed(name))) |
| 10047 | .map(|(name, server)| { |
| 10048 | let transport = if server.url.is_some() { |
| 10049 | if is_legacy_sse_transport(server) { |
| 10050 | "sse" |
| 10051 | } else { |
| 10052 | "http/sse" |
| 10053 | } |
| 10054 | } else { |
| 10055 | "stdio" |
| 10056 | }; |
| 10057 | let command_or_url = server.url.clone().unwrap_or_else(|| { |
| 10058 | let mut command = server |
| 10059 | .command |
| 10060 | .clone() |
| 10061 | .unwrap_or_else(|| "(missing)".to_string()); |
| 10062 | if !server.args.is_empty() { |
| 10063 | command.push(' '); |
| 10064 | command.push_str(&server.args.join(" ")); |
| 10065 | } |
| 10066 | command |
| 10067 | }); |
| 10068 | let mut snapshot = McpServerSnapshot { |
| 10069 | name: name.clone(), |
| 10070 | enabled: server.is_enabled(), |
| 10071 | required: server.required, |
| 10072 | transport: transport.to_string(), |
| 10073 | command_or_url, |
| 10074 | connect_timeout: server.effective_connect_timeout(&cfg.timeouts), |
| 10075 | execute_timeout: server.effective_execute_timeout(&cfg.timeouts), |
| 10076 | read_timeout: server.effective_read_timeout(&cfg.timeouts), |
| 10077 | connected: false, |
| 10078 | error: if server.is_enabled() { |
| 10079 | None |
| 10080 | } else { |
| 10081 | Some("disabled".to_string()) |
| 10082 | }, |
| 10083 | auth_required: false, |
| 10084 | capability_metadata: McpServerCapabilityMetadata::NotObserved, |
| 10085 | tools: Vec::new(), |
| 10086 | resources: Vec::new(), |
| 10087 | prompts: Vec::new(), |
| 10088 | }; |
| 10089 | |
| 10090 | if let Some((pool, errors)) = discovery { |
| 10091 | if let Some(error) = pool |
| 10092 | .connect_backoff |
| 10093 | .get(name) |
| 10094 | .map(|backoff| &backoff.last_error) |
| 10095 | .or_else(|| errors.get(name)) |
| 10096 | { |
| 10097 | snapshot.error = Some(error.clone()); |
| 10098 | } |
| 10099 | // The pool's needs-auth set is the authority; the error text |
| 10100 | // fallback keeps a boot-time error map (held by the engine |
| 10101 | // after the pool's live state was rebuilt) on the same |
| 10102 | // classification instead of downgrading to a plain failure. |
| 10103 | let oauth_capable = mcp_server_oauth_capable(server); |
| 10104 | let aws_login = snapshot |
| 10105 | .error |
| 10106 | .as_deref() |
| 10107 | .is_some_and(|error| mcp_error_is_aws_login(error, oauth_capable)); |
| 10108 | // An expired AWS login is never `◆ auth required`: the |
| 10109 | // needs-auth set already excludes it, and the text fallback |
| 10110 | // must too, or a `401`-worded AWS error reaches `/mcp login`. |
| 10111 | snapshot.auth_required = server.is_enabled() |
| 10112 | && (pool.server_needs_auth(name) |
| 10113 | || (!aws_login |
| 10114 | && snapshot |
| 10115 | .error |
| 10116 | .as_deref() |
| 10117 | .is_some_and(oauth::error_text_looks_auth_required))); |
| 10118 | // The row's retry is only useful once the user has run the |
| 10119 | // AWS login. Errors from paths other than `initialize` (child |
| 10120 | // exit, EOF, tools/list) carry no hint, so name it here or |
| 10121 | // the retry fails the same way and says nothing. |
| 10122 | if aws_login |
| 10123 | && let Some(error) = snapshot.error.as_mut() |
| 10124 | && !error.contains("AWS credentials expired:") |
| 10125 | { |
| 10126 | let hint = aws_login_hint(server, name, error); |
| 10127 | error.push_str("; "); |
| 10128 | error.push_str(&hint); |
| 10129 | } |
| 10130 | if snapshot.auth_required |
| 10131 | && oauth_capable |
| 10132 | && server |
| 10133 | .oauth_client_id() |
| 10134 | .is_none_or(|client_id| client_id.trim().is_empty()) |
| 10135 | && server |
| 10136 | .oauth |
| 10137 | .as_ref() |
| 10138 | .and_then(|oauth| oauth.client_metadata_url.as_deref()) |
| 10139 | .is_none_or(|url| url.trim().is_empty()) |
| 10140 | && server |
| 10141 | .url |
| 10142 | .as_deref() |
| 10143 | .is_some_and(|url| oauth::dynamic_registration_unavailable(name, url)) |
| 10144 | { |
| 10145 | let hint = oauth::dynamic_registration_unavailable_hint(name); |
| 10146 | match snapshot.error.as_mut() { |
| 10147 | Some(error) => { |
| 10148 | if !error.contains(&hint) { |
| 10149 | error.push_str("; "); |
| 10150 | error.push_str(&hint); |
| 10151 | } |
| 10152 | } |
| 10153 | None => snapshot.error = Some(hint), |
| 10154 | } |
| 10155 | } |
| 10156 | if let Some(conn) = pool.connections.get(name) { |
| 10157 | snapshot.connected = conn.is_ready(); |
| 10158 | snapshot.capability_metadata = conn.server_capabilities.map_or( |
| 10159 | McpServerCapabilityMetadata::LegacyFallback, |
| 10160 | McpServerCapabilityMetadata::Advertised, |
| 10161 | ); |
| 10162 | if snapshot.connected { |
| 10163 | // A count of connected servers and nothing else. The |
| 10164 | // name, the command or URL, and the error string are |
| 10165 | // user-chosen and routinely name internal infra. |
| 10166 | codewhale_telemetry::session_counters() |
| 10167 | .bump(codewhale_telemetry::Counter::McpServerConnected); |
| 10168 | } |
| 10169 | snapshot.tools = conn |
| 10170 | .tools() |
| 10171 | .iter() |
| 10172 | .filter(|tool| { |
| 10173 | conn.config().is_tool_enabled(&tool.name) |
| 10174 | && pool |
| 10175 | .tool_allowed(&McpPool::mcp_model_tool_name(name, &tool.name)) |
| 10176 | }) |
| 10177 | .map(|tool| McpDiscoveredItem { |
| 10178 | name: tool.name.clone(), |
| 10179 | model_name: format!("mcp_{}_{}", name, tool.name), |
| 10180 | description: tool.description.clone(), |
| 10181 | }) |
| 10182 | .collect(); |
| 10183 | snapshot.resources = |
| 10184 | conn.resources() |
| 10185 | .iter() |
| 10186 | .map(|resource| McpDiscoveredItem { |
| 10187 | name: resource.name.clone(), |
| 10188 | model_name: format!( |
| 10189 | "mcp_{}_{}", |
| 10190 | name, |
| 10191 | resource.name.replace(' ', "_").to_lowercase() |
| 10192 | ), |
| 10193 | description: resource.description.clone(), |
| 10194 | }) |
| 10195 | .chain(conn.resource_templates().iter().map(|template| { |
| 10196 | McpDiscoveredItem { |
| 10197 | name: template.name.clone(), |
| 10198 | model_name: format!( |
| 10199 | "mcp_{}_{}", |
| 10200 | name, |
| 10201 | template.name.replace(' ', "_").to_lowercase() |
| 10202 | ), |
| 10203 | description: template.description.clone(), |
| 10204 | } |
| 10205 | })) |
| 10206 | .collect(); |
| 10207 | snapshot.prompts = conn |
| 10208 | .prompts() |
| 10209 | .iter() |
| 10210 | .map(|prompt| McpDiscoveredItem { |
| 10211 | name: prompt.name.clone(), |
| 10212 | model_name: format!("mcp_{}_{}", name, prompt.name), |
| 10213 | description: prompt.description.clone(), |
| 10214 | }) |
| 10215 | .collect(); |
| 10216 | } |
| 10217 | } |
| 10218 | |
| 10219 | snapshot |
| 10220 | }) |
| 10221 | .collect::<Vec<_>>(); |
| 10222 | servers.sort_by(|a, b| a.name.cmp(&b.name)); |
| 10223 | McpManagerSnapshot { |
| 10224 | config_path: path.to_path_buf(), |
| 10225 | config_exists, |
| 10226 | reload_required, |
| 10227 | servers, |
| 10228 | } |
| 10229 | } |
| 10230 | |
| 10231 | #[cfg(test)] |
| 10232 | mod windows_child_path_tests { |
| 10233 | use super::plain_windows_child_path; |
| 10234 | |
| 10235 | #[test] |
| 10236 | fn plain_windows_child_path_drops_only_the_verbatim_prefix() { |
| 10237 | assert_eq!( |
| 10238 | plain_windows_child_path(r"\\?\C:\ws\peer.mjs"), |
| 10239 | r"C:\ws\peer.mjs" |
| 10240 | ); |
| 10241 | assert_eq!( |
| 10242 | plain_windows_child_path(r"\\?\UNC\host\share\peer.mjs"), |
| 10243 | r"\\host\share\peer.mjs" |
| 10244 | ); |
| 10245 | for unchanged in [ |
| 10246 | r"C:\ws\peer.mjs", |
| 10247 | r"\\host\share", |
| 10248 | r"\\?\Volume{0}\ws", |
| 10249 | "/tmp/peer.mjs", |
| 10250 | "peer.mjs", |
| 10251 | ] { |
| 10252 | assert_eq!(plain_windows_child_path(unchanged), unchanged); |
| 10253 | } |
| 10254 | } |
| 10255 | } |
| 10256 | |
| 10257 | #[cfg(test)] |
| 10258 | mod qualified_plugin_server_name_tests { |
| 10259 | use super::{qualified_plugin_server_name, split_qualified_plugin_server_name}; |
| 10260 | |
| 10261 | /// The wire key round-trips even when both halves contain `-`, which is |
| 10262 | /// what the length prefix is for. The Extensions panel relies on this to |
| 10263 | /// show `plugin/server` instead of `plugin-25-plugin-server`. |
| 10264 | #[test] |
| 10265 | fn a_qualified_plugin_server_name_round_trips_through_its_split() { |
| 10266 | for (plugin, server) in [ |
| 10267 | ("codewhale-account-plugins", "codewhale-plugins"), |
| 10268 | ("kimi-datasource", "data"), |
| 10269 | ("a", "b"), |
| 10270 | ("dash-heavy-name-here", "server-with-dashes"), |
| 10271 | ] { |
| 10272 | let qualified = qualified_plugin_server_name(plugin, server); |
| 10273 | assert_eq!( |
| 10274 | split_qualified_plugin_server_name(&qualified), |
| 10275 | Some((plugin, server)), |
| 10276 | "round trip failed for {qualified}" |
| 10277 | ); |
| 10278 | } |
| 10279 | } |
| 10280 | |
| 10281 | #[test] |
| 10282 | fn a_name_that_is_not_a_plugin_key_does_not_split() { |
| 10283 | for plain in [ |
| 10284 | "aws", |
| 10285 | "github", |
| 10286 | "plugin-", |
| 10287 | "plugin-x-a-b", |
| 10288 | "plugin-99-short", |
| 10289 | ] { |
| 10290 | assert_eq!(split_qualified_plugin_server_name(plain), None, "{plain}"); |
| 10291 | } |
| 10292 | } |
| 10293 | } |
| 10294 | |
| 10295 | // === Unit Tests === |
| 10296 | |
| 10297 | #[cfg(test)] |
| 10298 | mod tests; |
| 10299 | #[cfg(test)] |
| 10300 | pub use tests::computer_use_test_fixture; |
| 10301 |