| 1 | use std::collections::HashMap; |
| 2 | use std::path::PathBuf; |
| 3 | use std::sync::Arc; |
| 4 | |
| 5 | use serde::{Deserialize, Serialize}; |
| 6 | |
| 7 | #[derive(Clone)] |
| 8 | pub struct McpProvenance(Arc<dyn std::any::Any + Send + Sync>); |
| 9 | |
| 10 | impl McpProvenance { |
| 11 | pub fn new<T: std::any::Any + Send + Sync>(value: T) -> Self { |
| 12 | Self(Arc::new(value)) |
| 13 | } |
| 14 | |
| 15 | #[must_use] |
| 16 | pub fn downcast_ref<T: std::any::Any>(&self) -> Option<&T> { |
| 17 | self.0.downcast_ref::<T>() |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | impl std::fmt::Debug for McpProvenance { |
| 22 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 23 | f.write_str("McpProvenance(..)") |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | pub fn is_relative_stdio_path_arg(value: &str) -> bool { |
| 28 | if value.is_empty() || value.starts_with('-') || value.contains("://") || value.starts_with('~') |
| 29 | { |
| 30 | return false; |
| 31 | } |
| 32 | let looks_like_path = value.contains('/') || value.contains('\\'); |
| 33 | if !looks_like_path { |
| 34 | return false; |
| 35 | } |
| 36 | let bytes = value.as_bytes(); |
| 37 | let windows_absolute = value.starts_with("\\\\") |
| 38 | || (bytes.len() >= 3 && bytes[1] == b':' && (bytes[2] == b'\\' || bytes[2] == b'/')); |
| 39 | !std::path::Path::new(value).is_absolute() && !windows_absolute |
| 40 | } |
| 41 | |
| 42 | /// Full MCP configuration from mcp.json |
| 43 | #[derive(Debug, Clone, Default, Deserialize, Serialize)] |
| 44 | pub struct McpConfig { |
| 45 | #[serde(default)] |
| 46 | pub timeouts: McpTimeouts, |
| 47 | #[serde(default, alias = "mcpServers")] |
| 48 | pub servers: HashMap<String, McpServerConfig>, |
| 49 | #[serde(default, skip_serializing_if = "HashMap::is_empty")] |
| 50 | pub delegated_operations: HashMap<String, HashMap<String, DelegatedOperation>>, |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Clone, Deserialize, Serialize, PartialEq)] |
| 54 | #[serde(deny_unknown_fields)] |
| 55 | pub struct DelegatedOperation { |
| 56 | pub effect: McpOperationEffect, |
| 57 | pub binding_sha256: String, |
| 58 | pub input_schema: serde_json::Value, |
| 59 | #[serde(default)] |
| 60 | pub allowed_arguments: Vec<serde_json::Value>, |
| 61 | } |
| 62 | |
| 63 | #[derive(Debug, Clone, Copy, Deserialize, Serialize, PartialEq, Eq)] |
| 64 | #[serde(rename_all = "snake_case")] |
| 65 | pub enum McpOperationEffect { |
| 66 | Read, |
| 67 | Mutate, |
| 68 | Unknown, |
| 69 | } |
| 70 | |
| 71 | /// Global timeout configuration |
| 72 | #[derive(Debug, Clone, Copy, Deserialize, Serialize)] |
| 73 | #[allow(clippy::struct_field_names)] |
| 74 | pub struct McpTimeouts { |
| 75 | #[serde(default = "default_connect_timeout")] |
| 76 | pub connect_timeout: u64, |
| 77 | #[serde(default = "default_execute_timeout")] |
| 78 | pub execute_timeout: u64, |
| 79 | #[serde(default = "default_read_timeout")] |
| 80 | pub read_timeout: u64, |
| 81 | } |
| 82 | |
| 83 | /// Covers spawn, `initialize` and the first `tools/list` together. A cold |
| 84 | /// `uvx`/`npx` start resolves and downloads the package inside this window, |
| 85 | /// which routinely takes longer than 10 s; 30 s matches Codex, opencode, OMP |
| 86 | /// and Claude Code's `MCP_TIMEOUT` default. |
| 87 | pub fn default_connect_timeout() -> u64 { |
| 88 | 30 |
| 89 | } |
| 90 | // 30 minutes: an MCP tool call legitimately runs minutes — builds, test |
| 91 | // suites, scrapes, remote jobs. The old 60s default returned "timed out" to |
| 92 | // the model for healthy-but-slow tools, which then retried and compounded |
| 93 | // the cost. Per-server and global `execute_timeout` overrides still win. |
| 94 | // Scope note: `prompts/get` also routes through `effective_execute_timeout`, |
| 95 | // so it inherits this default; its server-side template work is normally |
| 96 | // fast, but the override knob is the intended way to keep it tight. |
| 97 | pub fn default_execute_timeout() -> u64 { |
| 98 | 1800 |
| 99 | } |
| 100 | pub fn default_read_timeout() -> u64 { |
| 101 | 120 |
| 102 | } |
| 103 | |
| 104 | impl Default for McpTimeouts { |
| 105 | fn default() -> Self { |
| 106 | Self { |
| 107 | connect_timeout: default_connect_timeout(), |
| 108 | execute_timeout: default_execute_timeout(), |
| 109 | read_timeout: default_read_timeout(), |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | /// Configuration for a single MCP server |
| 115 | #[derive(Debug, Clone, Deserialize, Serialize)] |
| 116 | pub struct McpServerConfig { |
| 117 | pub command: Option<String>, |
| 118 | #[serde(default)] |
| 119 | pub args: Vec<String>, |
| 120 | #[serde(default)] |
| 121 | pub env: HashMap<String, String>, |
| 122 | #[serde(default)] |
| 123 | #[serde(skip_serializing_if = "Option::is_none")] |
| 124 | pub cwd: Option<PathBuf>, |
| 125 | pub url: Option<String>, |
| 126 | /// Explicit operator authority for private DNS names at this exact origin. |
| 127 | /// Ignored for model-added runtime servers. |
| 128 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] |
| 129 | pub allow_private_network: bool, |
| 130 | /// Optional explicit HTTP transport override. |
| 131 | /// |
| 132 | /// By default URL-based MCP servers use Streamable HTTP first and fall |
| 133 | /// back to legacy SSE only when the server rejects Streamable HTTP with |
| 134 | /// a known incompatible status. Set this to `"sse"` for legacy SSE |
| 135 | /// endpoints that must start with a long-lived GET endpoint discovery |
| 136 | /// stream and cannot accept an initial POST to the configured URL. |
| 137 | #[serde(default)] |
| 138 | #[serde(skip_serializing_if = "Option::is_none")] |
| 139 | pub transport: Option<String>, |
| 140 | #[serde(default)] |
| 141 | pub connect_timeout: Option<u64>, |
| 142 | #[serde(default)] |
| 143 | pub execute_timeout: Option<u64>, |
| 144 | #[serde(default)] |
| 145 | pub read_timeout: Option<u64>, |
| 146 | #[serde(default)] |
| 147 | pub disabled: bool, |
| 148 | #[serde(default = "default_enabled")] |
| 149 | pub enabled: bool, |
| 150 | #[serde(default)] |
| 151 | pub required: bool, |
| 152 | #[serde(default, skip_serializing_if = "std::ops::Not::not")] |
| 153 | pub lazy: bool, |
| 154 | #[serde(default)] |
| 155 | pub enabled_tools: Vec<String>, |
| 156 | #[serde(default)] |
| 157 | pub disabled_tools: Vec<String>, |
| 158 | #[serde(default, skip_serializing_if = "Vec::is_empty")] |
| 159 | pub always_allow_tools: Vec<String>, |
| 160 | /// Extra HTTP headers sent with every request to this MCP server. |
| 161 | /// Only the HTTP transports (streamable HTTP today; SSE in a |
| 162 | /// follow-up) honor this — `command`-based stdio servers ignore it. |
| 163 | /// |
| 164 | /// Mirrors the `headers` field that Claude Code, Codex, and |
| 165 | /// OpenCode already accept in their MCP config formats. Use it to |
| 166 | /// authenticate against gateways that require a Bearer token or |
| 167 | /// API key, e.g.: |
| 168 | /// |
| 169 | /// ```jsonc |
| 170 | /// "huggingface": { |
| 171 | /// "url": "https://huggingface.co/api/mcp", |
| 172 | /// "headers": { "Authorization": "Bearer ${HF_TOKEN}" } |
| 173 | /// } |
| 174 | /// ``` |
| 175 | /// |
| 176 | /// Header keys and values are passed through as-is — we do not |
| 177 | /// substitute environment variables in v0.8.31. If you store a |
| 178 | /// real token here, the value lives in plain text in |
| 179 | /// `~/.deepseek/mcp.json`; treat that file with the same care |
| 180 | /// as any other secret-bearing config. |
| 181 | #[serde(default)] |
| 182 | #[serde(skip_serializing_if = "HashMap::is_empty")] |
| 183 | pub headers: HashMap<String, String>, |
| 184 | /// HTTP headers whose values are read from environment variables at request |
| 185 | /// time. This keeps common bearer/API-token integrations out of mcp.json. |
| 186 | #[serde(default, alias = "env_http_headers")] |
| 187 | #[serde(skip_serializing_if = "HashMap::is_empty")] |
| 188 | pub env_headers: HashMap<String, String>, |
| 189 | /// Environment variable containing a bearer token. When present and set, |
| 190 | /// CodeWhale sends `Authorization: Bearer <value>` for URL-based servers. |
| 191 | #[serde(default)] |
| 192 | #[serde(skip_serializing_if = "Option::is_none")] |
| 193 | pub bearer_token_env_var: Option<String>, |
| 194 | /// OAuth scopes requested during `codewhale mcp login`. |
| 195 | #[serde(default)] |
| 196 | #[serde(skip_serializing_if = "Vec::is_empty")] |
| 197 | pub scopes: Vec<String>, |
| 198 | /// OAuth client override for MCP servers that require a pre-registered |
| 199 | /// public client instead of dynamic registration. |
| 200 | #[serde(default)] |
| 201 | #[serde(skip_serializing_if = "Option::is_none")] |
| 202 | pub oauth: Option<McpServerOAuthConfig>, |
| 203 | /// Optional exact RFC 8707 resource pin, checked against SDK discovery. |
| 204 | #[serde(default)] |
| 205 | #[serde(skip_serializing_if = "Option::is_none")] |
| 206 | pub oauth_resource: Option<String>, |
| 207 | /// In-memory provenance for MCP servers contributed by a reviewed plugin |
| 208 | /// bundle. This is never deserialized from or serialized into user config: |
| 209 | /// only the trusted plugin merge adapter may attach it. |
| 210 | #[serde(skip)] |
| 211 | pub reviewed_plugin: Option<McpProvenance>, |
| 212 | /// Only the runtime registration boundary can attach this provenance. |
| 213 | #[serde(skip)] |
| 214 | pub runtime_added: bool, |
| 215 | } |
| 216 | |
| 217 | #[derive(Debug, Clone, Default, Deserialize, Serialize, PartialEq, Eq)] |
| 218 | pub struct McpServerOAuthConfig { |
| 219 | #[serde(default)] |
| 220 | #[serde(skip_serializing_if = "Option::is_none")] |
| 221 | pub client_id: Option<String>, |
| 222 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 223 | pub issuer: Option<String>, |
| 224 | #[serde(default, skip_serializing_if = "Option::is_none")] |
| 225 | pub client_metadata_url: Option<String>, |
| 226 | } |
| 227 | |
| 228 | const PACKAGE_RUNNER_CONNECT_TIMEOUT_SECS: u64 = 120; |
| 229 | |
| 230 | fn default_enabled() -> bool { |
| 231 | true |
| 232 | } |
| 233 | |
| 234 | impl McpServerConfig { |
| 235 | pub fn effective_connect_timeout(&self, global: &McpTimeouts) -> u64 { |
| 236 | self.connect_timeout.unwrap_or_else(|| { |
| 237 | if self.launches_package_runner() { |
| 238 | global |
| 239 | .connect_timeout |
| 240 | .max(PACKAGE_RUNNER_CONNECT_TIMEOUT_SECS) |
| 241 | } else { |
| 242 | global.connect_timeout |
| 243 | } |
| 244 | }) |
| 245 | } |
| 246 | |
| 247 | pub fn launches_package_runner(&self) -> bool { |
| 248 | self.url.is_none() |
| 249 | && self |
| 250 | .command |
| 251 | .as_deref() |
| 252 | .and_then(|command| std::path::Path::new(command).file_stem()) |
| 253 | .and_then(|stem| stem.to_str()) |
| 254 | .is_some_and(|stem| { |
| 255 | matches!( |
| 256 | stem.to_ascii_lowercase().as_str(), |
| 257 | "npx" | "pnpx" | "bunx" | "uvx" |
| 258 | ) |
| 259 | }) |
| 260 | } |
| 261 | |
| 262 | pub fn effective_execute_timeout(&self, global: &McpTimeouts) -> u64 { |
| 263 | self.execute_timeout.unwrap_or(global.execute_timeout) |
| 264 | } |
| 265 | |
| 266 | pub fn effective_read_timeout(&self, global: &McpTimeouts) -> u64 { |
| 267 | self.read_timeout.unwrap_or(global.read_timeout) |
| 268 | } |
| 269 | |
| 270 | pub fn is_enabled(&self) -> bool { |
| 271 | self.enabled && !self.disabled |
| 272 | } |
| 273 | |
| 274 | pub fn is_tool_always_allowed(&self, tool_name: &str) -> bool { |
| 275 | self.is_tool_enabled(tool_name) |
| 276 | && self.always_allow_tools.iter().any(|tool| tool == tool_name) |
| 277 | } |
| 278 | |
| 279 | pub fn is_tool_enabled(&self, tool_name: &str) -> bool { |
| 280 | let allowed = if self.enabled_tools.is_empty() { |
| 281 | true |
| 282 | } else { |
| 283 | self.enabled_tools.iter().any(|t| t == tool_name) |
| 284 | }; |
| 285 | if !allowed { |
| 286 | return false; |
| 287 | } |
| 288 | !self.disabled_tools.iter().any(|t| t == tool_name) |
| 289 | } |
| 290 | } |
| 291 |