| 1 | //! Native definition admission joins Rust's existing MCP pool; no transport here. |
| 2 | use super::ManagerShared; |
| 3 | use super::protocol::{RegisterKind, RegisterParams, RegisterResult}; |
| 4 | use super::supervisor::HostRequestContext; |
| 5 | use super::tier::{HostCohort, HostTier}; |
| 6 | use codewhale_config::PluginAuthority; |
| 7 | use codewhale_config::{EntryRef, OwnerRef}; |
| 8 | use codewhale_mcp::config::McpServerConfig; |
| 9 | use codewhale_plugins::composition_scope::SelectionRevision; |
| 10 | use codewhale_plugins::{PluginRegistry, activation::PluginActivationCapability}; |
| 11 | use std::sync::atomic::{AtomicU64, Ordering}; |
| 12 | use std::sync::{Arc, Weak}; |
| 13 | |
| 14 | pub(super) const MAX_PER_OWNER: usize = 64; |
| 15 | pub(super) const MAX_PER_HOST: usize = 256; |
| 16 | pub(super) const MAX_DEFINITION_BYTES: usize = 64 * 1024; |
| 17 | static EPOCH: AtomicU64 = AtomicU64::new(1); |
| 18 | pub fn epoch() -> u64 { |
| 19 | EPOCH.load(Ordering::SeqCst) |
| 20 | } |
| 21 | pub(super) fn changed() { |
| 22 | EPOCH.fetch_add(1, Ordering::SeqCst); |
| 23 | } |
| 24 | |
| 25 | #[derive(Debug, Clone)] |
| 26 | pub(super) struct McpRegistration { |
| 27 | pub handle: u64, |
| 28 | pub owner: OwnerRef, |
| 29 | pub scope: EntryRef, |
| 30 | pub content_hash: String, |
| 31 | pub host_generation: u64, |
| 32 | pub name: String, |
| 33 | pub config: McpServerConfig, |
| 34 | pub cancel: tokio_util::sync::CancellationToken, |
| 35 | } |
| 36 | /// In-memory only: exact generation/handle/caller receipt. No host token is persisted. |
| 37 | #[derive(Debug, Clone)] |
| 38 | pub struct NativeMcpRef { |
| 39 | shared: Weak<dyn NativeMcpAuthority>, |
| 40 | registration: Arc<McpRegistration>, |
| 41 | selection: SelectionRevision, |
| 42 | caller_cancel: tokio_util::sync::CancellationToken, |
| 43 | } |
| 44 | // Keep MCP configs independent of the concrete manager's Engine/task graph. |
| 45 | // The weak port still targets the original manager and owns no runtime state. |
| 46 | trait NativeMcpAuthority: Send + Sync { |
| 47 | fn validate_mcp( |
| 48 | &self, |
| 49 | selection: SelectionRevision, |
| 50 | registration: &McpRegistration, |
| 51 | ) -> Result<(), String>; |
| 52 | } |
| 53 | impl NativeMcpAuthority for ManagerShared { |
| 54 | fn validate_mcp( |
| 55 | &self, |
| 56 | selection: SelectionRevision, |
| 57 | registration: &McpRegistration, |
| 58 | ) -> Result<(), String> { |
| 59 | if !codewhale_plugins::activation::extension_host_policy_enabled() { |
| 60 | return Err("Native MCP is disabled by current policy".into()); |
| 61 | } |
| 62 | let cohort = self |
| 63 | .registry |
| 64 | .lock() |
| 65 | .expect("registry lock") |
| 66 | .cohort_of(®istration.owner) |
| 67 | .ok_or_else(|| "Native MCP owner has no cohort".to_string())?; |
| 68 | self.ready_host(&cohort) |
| 69 | .map_err(|status| status.to_string())?; |
| 70 | let runtime = self |
| 71 | .cohort_runtime(&cohort) |
| 72 | .ok_or_else(|| "cohort runtime gone".to_string())?; |
| 73 | if runtime.host_generation.load(Ordering::SeqCst) != registration.host_generation { |
| 74 | return Err("Native MCP host generation changed".into()); |
| 75 | } |
| 76 | if !self.selection_current( |
| 77 | selection, |
| 78 | ®istration.owner.plugin_id, |
| 79 | ®istration.content_hash, |
| 80 | Some(®istration.scope), |
| 81 | ) { |
| 82 | return Err("Native MCP entry is no longer selected for this caller".into()); |
| 83 | } |
| 84 | let registry = self.registry.lock().expect("registry lock"); |
| 85 | if !registry.is_live_mcp(registration) { |
| 86 | return Err("Native MCP definition was withdrawn".into()); |
| 87 | } |
| 88 | Ok(()) |
| 89 | } |
| 90 | } |
| 91 | impl NativeMcpRef { |
| 92 | pub fn validate(&self) -> Result<(), String> { |
| 93 | self.shared |
| 94 | .upgrade() |
| 95 | .ok_or("Native MCP manager exited")? |
| 96 | .validate_mcp(self.selection, &self.registration) |
| 97 | } |
| 98 | pub fn selection(&self) -> SelectionRevision { |
| 99 | self.selection |
| 100 | } |
| 101 | pub fn catalog_identity(&self) -> String { |
| 102 | format!( |
| 103 | "{}:{}:{}:{}:{}:{}", |
| 104 | self.registration.host_generation, |
| 105 | self.registration.owner.generation, |
| 106 | self.registration.handle, |
| 107 | self.selection.attachment_id, |
| 108 | self.selection.revision, |
| 109 | self.registration.scope.sha256 |
| 110 | ) |
| 111 | } |
| 112 | pub async fn withdrawn(&self) { |
| 113 | tokio::select! { |
| 114 | biased; |
| 115 | _ = self.caller_cancel.cancelled() => {}, |
| 116 | _ = self.registration.cancel.cancelled() => {}, |
| 117 | } |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | pub(super) async fn admit( |
| 122 | shared: &Arc<ManagerShared>, |
| 123 | cohort: &HostCohort, |
| 124 | generation: u64, |
| 125 | params: RegisterParams, |
| 126 | cx: &HostRequestContext, |
| 127 | ) -> RegisterResult { |
| 128 | let outcome = async { |
| 129 | params.check_spec()?; |
| 130 | if params.kind != RegisterKind::McpServer |
| 131 | || cohort.tier() != HostTier::Plugin |
| 132 | || params.scope.is_none() |
| 133 | { |
| 134 | return Err("MCP definitions require a reviewed Native entry scope".into()); |
| 135 | } |
| 136 | if params.spec.description.len() > MAX_DEFINITION_BYTES { |
| 137 | return Err("MCP definition exceeds 64 KiB".into()); |
| 138 | } |
| 139 | let authority = shared |
| 140 | .live_owner_authority(cohort, |registry| { |
| 141 | registry |
| 142 | .authority_for(¶ms.owner) |
| 143 | .ok_or_else(|| "stale MCP owner".to_string())?; |
| 144 | Ok(params.owner.clone()) |
| 145 | })? |
| 146 | .ok_or("MCP definition has no Native authority")?; |
| 147 | let proposal = params.clone(); |
| 148 | let config = super::skills::bounded_review_check( |
| 149 | Arc::clone(&shared.skill_admission), |
| 150 | &cx.cancel, |
| 151 | move || validate_definition(&authority, &proposal), |
| 152 | ) |
| 153 | .await?; |
| 154 | shared |
| 155 | .ready_host(cohort) |
| 156 | .map_err(|status| status.to_string())?; |
| 157 | let runtime = shared |
| 158 | .cohort_runtime(cohort) |
| 159 | .ok_or_else(|| "cohort runtime gone".to_string())?; |
| 160 | let _host = runtime.host.lock().expect("host lock"); |
| 161 | if cx.cancel.is_cancelled() || runtime.host_generation.load(Ordering::SeqCst) != generation |
| 162 | { |
| 163 | return Err("MCP admission cancelled or host changed".into()); |
| 164 | } |
| 165 | shared |
| 166 | .registry |
| 167 | .lock() |
| 168 | .expect("registry lock") |
| 169 | .register_mcp(¶ms, config, generation) |
| 170 | } |
| 171 | .await; |
| 172 | match outcome { |
| 173 | Ok(handle) => RegisterResult::Admitted { handle }, |
| 174 | Err(refused) => { |
| 175 | shared.plugin_diagnostic( |
| 176 | ¶ms.owner.plugin_id, |
| 177 | format!("MCP definition refused: {refused}"), |
| 178 | ); |
| 179 | RegisterResult::Refused { refused } |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | fn validate_definition( |
| 184 | authority: &PluginAuthority, |
| 185 | params: &RegisterParams, |
| 186 | ) -> Result<McpServerConfig, String> { |
| 187 | codewhale_plugins::registry::verify_plugin_component_authority( |
| 188 | authority, |
| 189 | PluginActivationCapability::Native, |
| 190 | )?; |
| 191 | let declaration: serde_json::Value = serde_json::from_str(¶ms.spec.description) |
| 192 | .map_err(|_| "MCP proposal is not a literal server definition")?; |
| 193 | let text = serde_json::to_string( |
| 194 | &serde_json::json!({"mcpServers":{(params.spec.name.clone()):declaration}}), |
| 195 | ) |
| 196 | .map_err(|_| "MCP definition encoding failed")?; |
| 197 | let mut servers = codewhale_plugins::agent_plugin::parse_mcp_json(&text) |
| 198 | .map_err(|_| "MCP proposal does not match the existing transport schema")?; |
| 199 | let config = servers |
| 200 | .remove(¶ms.spec.name) |
| 201 | .ok_or("MCP proposal omitted its server")?; |
| 202 | // Native rows cannot transport credential values to Core. Authentication |
| 203 | // remains the existing OAuth/environment-key authority at connection time. |
| 204 | if !config.env.is_empty() || !config.headers.is_empty() { |
| 205 | return Err("MCP credential values must remain under Core authentication authority".into()); |
| 206 | } |
| 207 | let mut validated = codewhale_plugins::manifest::PluginManifest::validate_from_path( |
| 208 | &authority.staged_manifest, |
| 209 | )?; |
| 210 | let root = &validated.canonical_root; |
| 211 | validated.manifest.mcp_servers = Some(servers); |
| 212 | validated |
| 213 | .manifest |
| 214 | .mcp_servers |
| 215 | .as_mut() |
| 216 | .expect("set servers") |
| 217 | .insert(params.spec.name.clone(), config.clone()); |
| 218 | validated.manifest.validate_mcp_servers(root)?; |
| 219 | codewhale_plugins::registry::verify_plugin_component_authority( |
| 220 | authority, |
| 221 | PluginActivationCapability::Native, |
| 222 | )?; |
| 223 | Ok(config) |
| 224 | } |
| 225 | |
| 226 | pub fn for_plugins( |
| 227 | plugins: &PluginRegistry, |
| 228 | ) -> Result<Vec<(String, McpServerConfig, PluginAuthority, NativeMcpRef)>, String> { |
| 229 | if !codewhale_plugins::activation::extension_host_policy_enabled() { |
| 230 | return Ok(Vec::new()); |
| 231 | } |
| 232 | let Some(selection) = plugins.caller_selection() else { |
| 233 | return Ok(Vec::new()); |
| 234 | }; |
| 235 | let manager = super::manager(); |
| 236 | let shared = &manager.shared; |
| 237 | let Some(caller_cancel) = shared.selection_cancellation(selection) else { |
| 238 | return Ok(Vec::new()); |
| 239 | }; |
| 240 | let live_authority: Arc<dyn NativeMcpAuthority> = shared.clone(); |
| 241 | let definitions = shared.registry.lock().expect("registry lock").live_mcp(); |
| 242 | let mut result = Vec::new(); |
| 243 | let mut names = std::collections::HashSet::new(); |
| 244 | for definition in definitions { |
| 245 | let cohort = shared |
| 246 | .registry |
| 247 | .lock() |
| 248 | .expect("registry lock") |
| 249 | .cohort_of(&definition.owner); |
| 250 | let Some(cohort) = cohort else { |
| 251 | continue; |
| 252 | }; |
| 253 | if shared.ready_host(&cohort).is_err() { |
| 254 | continue; |
| 255 | } |
| 256 | let Some(plugin) = plugins.get(&definition.owner.plugin_id) else { |
| 257 | continue; |
| 258 | }; |
| 259 | if !plugin.active() |
| 260 | || plugin.content_hash != definition.content_hash |
| 261 | || !shared.selection_current( |
| 262 | selection, |
| 263 | &definition.owner.plugin_id, |
| 264 | &definition.content_hash, |
| 265 | Some(&definition.scope), |
| 266 | ) |
| 267 | { |
| 268 | continue; |
| 269 | } |
| 270 | let Some(authority) = plugins.authority_for(&definition.owner.plugin_id) else { |
| 271 | continue; |
| 272 | }; |
| 273 | let receipt = NativeMcpRef { |
| 274 | shared: Arc::downgrade(&live_authority), |
| 275 | registration: Arc::new(definition.clone()), |
| 276 | selection, |
| 277 | caller_cancel: caller_cancel.clone(), |
| 278 | }; |
| 279 | if receipt.validate().is_err() |
| 280 | || codewhale_plugins::registry::verify_plugin_component_authority( |
| 281 | &authority, |
| 282 | PluginActivationCapability::Native, |
| 283 | ) |
| 284 | .is_err() |
| 285 | { |
| 286 | continue; |
| 287 | } |
| 288 | let qualified = |
| 289 | crate::mcp::qualified_plugin_server_name(&authority.plugin_name, &definition.name); |
| 290 | if !names.insert(qualified) { |
| 291 | return Err("Selected Native entries duplicate an MCP server namespace".into()); |
| 292 | } |
| 293 | result.push((definition.name, definition.config, authority, receipt)); |
| 294 | } |
| 295 | Ok(result) |
| 296 | } |
| 297 | |
| 298 | #[cfg(test)] |
| 299 | mod tests; |
| 300 |