Skip to main content

oi_kit_agent/mcp/
mod.rs

1//! The MCP extension runtime: scoped slots, leases, tool catalogs, dispatch and
2//! transports. Everything application-specific comes from an [`ExtensionHost`].
3//!
4//! Acquire a lease from the current session's [`ExtensionSet`] at point of use.
5//! Leases keep resources alive for one logical operation, not across inference
6//! and approval. The manager owns process reuse and reconnection; session changes
7//! made while approval is pending therefore apply when execution acquires its lease.
8
9use futures::Stream;
10use indexmap::IndexMap;
11use std::collections::HashMap;
12use std::path::{Path, PathBuf};
13use std::pin::Pin;
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::sync::{Arc, Weak};
16use std::task::{Context, Poll};
17use std::time::Duration;
18use tokio::sync::{Mutex, OnceCell};
19use tokio_stream::wrappers::ReceiverStream;
20use tokio_util::sync::CancellationToken;
21use tracing::warn;
22
23use crate::action_required_manager::ActionRequiredManager;
24use crate::extension::ExtensionConfig as TransportConfig;
25use crate::extension::{name_to_key, ExtensionError, ExtensionResult};
26use crate::mcp::client::{ConnectContext, GooseMcpClientCapabilities, McpClientTrait};
27pub use container::Container;
28use oi_kit_provider_types::conversation::message::Message;
29use rmcp::model::{CallToolResult, MetaObject, ServerConfig, Tool};
30use serde_json::Value;
31
32mod batch;
33mod call;
34pub mod client;
35pub mod container;
36mod host;
37mod lease;
38pub mod malware_check;
39mod operation;
40mod stdio;
41mod streamable_http;
42pub mod tool_schema_normalize;
43
44pub use batch::{ResultNotification, ToolCallBatch};
45pub use call::{ToolCallNotificationEmitter, ToolCallResult, ToolResult};
46pub use host::{
47    ExtensionAuth, ExtensionHost, ExtensionSpec, StaticOAuthClientConfig, TraceContextInjector,
48};
49pub use lease::{CallRequest, ExtensionLease, ExtensionSet, LeaseId};
50pub use operation::{ExtensionOperation, ExtensionSource};
51pub use stdio::{docker_exec, spawn as spawn_stdio};
52
53type McpClientBox = Arc<dyn McpClientTrait>;
54
55const TOOL_CALL_NOTIFICATION_CHANNEL_CAPACITY: usize = 32;
56
57struct ActionRequiredStream {
58    inner: ReceiverStream<Message>,
59    manager: Arc<ActionRequiredManager>,
60    session_id: String,
61    tool_call_request_id: String,
62}
63
64impl ActionRequiredStream {
65    fn new(
66        receiver: tokio::sync::mpsc::Receiver<Message>,
67        manager: Arc<ActionRequiredManager>,
68        session_id: String,
69        tool_call_request_id: String,
70    ) -> Self {
71        Self {
72            inner: ReceiverStream::new(receiver),
73            manager,
74            session_id,
75            tool_call_request_id,
76        }
77    }
78}
79
80impl Stream for ActionRequiredStream {
81    type Item = Message;
82
83    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
84        Pin::new(&mut self.inner).poll_next(cx)
85    }
86}
87
88impl Drop for ActionRequiredStream {
89    fn drop(&mut self) {
90        let manager = self.manager.clone();
91        let session_id = self.session_id.clone();
92        let tool_call_request_id = self.tool_call_request_id.clone();
93        let Ok(handle) = tokio::runtime::Handle::try_current() else {
94            return;
95        };
96        handle.spawn(async move {
97            manager
98                .unregister_action_required_stream(&session_id, &tool_call_request_id)
99                .await;
100        });
101    }
102}
103
104struct Extension<C> {
105    key: String,
106    config: C,
107    /// The transport config with secrets substituted; `None` for host-connected configs.
108    resolved_config: Option<TransportConfig>,
109    client: McpClientBox,
110    server_info: Option<ServerConfig>,
111    /// Bumped by the client on tools/list_changed; a cached list is only valid
112    /// for the version it was fetched under.
113    tools_version: Arc<AtomicU64>,
114    /// Servers may publish different tools to different sessions (extension
115    /// management hides itself from subagents), so the scope is part of the
116    /// cache key.
117    tools: Mutex<Option<CachedTools>>,
118}
119
120struct CachedTools {
121    scope_id: String,
122    version: u64,
123    tools: Arc<Vec<Tool>>,
124}
125
126struct Placement {
127    working_dir: PathBuf,
128    container: Option<Container>,
129}
130
131impl Placement {
132    fn new(working_dir: PathBuf, container: Option<&Container>) -> Self {
133        Self {
134            working_dir,
135            container: container.cloned(),
136        }
137    }
138}
139
140enum Runtime<C> {
141    Running(Arc<Extension<C>>),
142    Failed(String),
143}
144
145pub struct ExtensionSlot<C: ExtensionSpec> {
146    key: String,
147    config: C,
148    placement: Option<Placement>,
149    scope_id: String,
150    manager: Weak<ExtensionManager<C>>,
151    client: Arc<ClientContext>,
152    config_generation: AtomicU64,
153    runtime: OnceCell<Runtime<C>>,
154}
155
156impl<C: ExtensionSpec> ExtensionSlot<C> {
157    fn reusable_for(
158        &self,
159        config: &C,
160        working_dir: Option<&Path>,
161        container: Option<&Container>,
162        client: &ClientContext,
163    ) -> bool {
164        if self.config != *config {
165            return false;
166        }
167        self.placement.as_ref().is_none_or(|placement| {
168            working_dir.is_none_or(|working_dir| placement.working_dir == working_dir)
169                && placement.container.as_ref() == container
170                && self.client.negotiates_like(client)
171        })
172    }
173
174    /// Whether the secrets and environment the extension started with still hold. Only
175    /// checked after this process wrote config, so a lease does not read the keyring.
176    async fn config_is_current(&self) -> bool {
177        let Some(manager) = self.manager.upgrade() else {
178            return false;
179        };
180        let generation = manager.host.config_generation();
181        if self.config_generation.load(Ordering::SeqCst) == generation {
182            return true;
183        }
184        let current = match self.runtime.get() {
185            None => true,
186            Some(Runtime::Failed(_)) => false,
187            Some(Runtime::Running(extension)) => {
188                extension.resolved_config.is_some()
189                    && manager
190                        .resolve_transport(&self.config)
191                        .await
192                        .is_ok_and(|config| config == extension.resolved_config)
193            }
194        };
195        if current {
196            self.config_generation.store(generation, Ordering::SeqCst);
197        }
198        current
199    }
200
201    async fn runtime(&self) -> &Runtime<C> {
202        self.runtime
203            .get_or_init(|| async {
204                let Some(manager) = self.manager.upgrade() else {
205                    return Runtime::Failed("the extension manager is gone".to_string());
206                };
207                match manager
208                    .start(
209                        &self.config,
210                        self.placement.as_ref(),
211                        &self.scope_id,
212                        &self.client,
213                    )
214                    .await
215                {
216                    Ok(extension) => Runtime::Running(Arc::new(extension)),
217                    Err(error) => {
218                        warn!(extension = %self.key, %error, "failed to start extension");
219                        Runtime::Failed(error.to_string())
220                    }
221                }
222            })
223            .await
224    }
225
226    async fn start(&self) -> Option<&Arc<Extension<C>>> {
227        match self.runtime().await {
228            Runtime::Running(extension) => Some(extension),
229            Runtime::Failed(_) => None,
230        }
231    }
232
233    async fn load_result(&self) -> ExtensionLoadResult {
234        let error = match self.runtime().await {
235            Runtime::Failed(error) => Some(error.clone()),
236            Runtime::Running(_) => None,
237        };
238        ExtensionLoadResult {
239            name: self.config.name(),
240            success: error.is_none(),
241            error,
242        }
243    }
244}
245
246#[derive(Debug, Clone, serde::Serialize)]
247pub struct ExtensionLoadResult {
248    pub name: String,
249    pub success: bool,
250    #[serde(skip_serializing_if = "Option::is_none")]
251    pub error: Option<String>,
252}
253
254impl<C: ExtensionSpec> Extension<C> {
255    fn supports_resources(&self) -> bool {
256        self.server_info
257            .as_ref()
258            .and_then(|info| info.capabilities.resources.as_ref())
259            .is_some()
260    }
261
262    /// The extension's tools as the model sees them: filtered by
263    /// `available_tools`, prefixed unless first-class, tagged with the owner,
264    /// schema-normalized.
265    async fn public_tools(&self, scope_id: &str) -> Arc<Vec<Tool>> {
266        let version;
267        {
268            let cache = self.tools.lock().await;
269            version = self.tools_version.load(Ordering::SeqCst);
270            if let Some(cached) = &*cache {
271                if cached.version == version && cached.scope_id == scope_id {
272                    let tools = Arc::clone(&cached.tools);
273                    if self.tools_version.load(Ordering::SeqCst) == version {
274                        return tools;
275                    }
276                }
277            }
278        }
279
280        let tools = Arc::new(self.fetch_public_tools(scope_id).await);
281
282        let mut cache = self.tools.lock().await;
283        if self.tools_version.load(Ordering::SeqCst) == version {
284            *cache = Some(CachedTools {
285                scope_id: scope_id.to_string(),
286                version,
287                tools: Arc::clone(&tools),
288            });
289        }
290        tools
291    }
292
293    async fn fetch_public_tools(&self, session_id: &str) -> Vec<Tool> {
294        let cancel_token = CancellationToken::default();
295        let mut tools = Vec::new();
296        let mut cursor = None;
297        loop {
298            let page = match self
299                .client
300                .list_tools(session_id, cursor, cancel_token.clone())
301                .await
302            {
303                Ok(page) => page,
304                Err(e) => {
305                    warn!(extension = %self.key, error = %e, "Failed to list tools");
306                    break;
307                }
308            };
309            for mut tool in page.tools {
310                if !self.config.is_tool_available(&tool.name) {
311                    continue;
312                }
313                tool.name = format!("{}__{}", self.key, tool.name).into();
314                let mut meta = tool.meta.as_ref().map(|m| m.0.clone()).unwrap_or_default();
315                meta.insert(
316                    TOOL_EXTENSION_META_KEY.to_string(),
317                    Value::String(self.key.clone()),
318                );
319                tool.meta = Some(MetaObject(meta));
320                let mut schema = (*tool.input_schema).clone();
321                if crate::mcp::tool_schema_normalize::normalize_input_schema(&mut schema) {
322                    tool.input_schema = Arc::new(schema);
323                }
324                tools.push(tool);
325            }
326            cursor = page.next_cursor;
327            if cursor.is_none() {
328                break;
329            }
330        }
331        tools
332    }
333}
334
335/// The client identity and capabilities used to negotiate with MCP servers.
336#[derive(Clone)]
337pub struct ClientContext {
338    pub name: String,
339    pub version: String,
340    pub capabilities: GooseMcpClientCapabilities,
341}
342
343impl ClientContext {
344    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
345        Self {
346            name: name.into(),
347            version: version.into(),
348            capabilities: GooseMcpClientCapabilities::default(),
349        }
350    }
351
352    fn hydrates_mcp_apps(&self) -> bool {
353        match &self.capabilities.host_info {
354            Some(host_info) if host_info.explicit_extensions => host_info.mcpui_enabled(),
355            _ => self.capabilities.mcpui,
356        }
357    }
358
359    fn negotiates_like(&self, other: &ClientContext) -> bool {
360        let (a, b) = (&self.capabilities, &other.capabilities);
361        self.name == other.name
362            && self.version == other.version
363            && a.mcpui == b.mcpui
364            && a.host_info == b.host_info
365            && a.protocol_version == b.protocol_version
366            && match (&a.elicitation_handler, &b.elicitation_handler) {
367                (Some(a), Some(b)) => Arc::ptr_eq(a, b),
368                (None, None) => true,
369                _ => false,
370            }
371    }
372}
373
374#[derive(Debug, Clone, serde::Serialize)]
375#[serde(rename_all = "camelCase")]
376pub struct GooseMcpAppToolAttachment {
377    pub tool_name: String,
378    pub tool_name_is_actual: bool,
379    pub extension_name: String,
380    pub resource_uri: String,
381    #[serde(skip_serializing_if = "Option::is_none")]
382    pub tool_meta: Option<Value>,
383    #[serde(skip_serializing_if = "Option::is_none")]
384    pub resource_result: Option<Value>,
385    #[serde(skip_serializing_if = "Option::is_none")]
386    pub read_error: Option<String>,
387}
388
389pub const TRUSTED_TOOL_UPDATE_META_KEY: &str = "__goose_tool_update_meta";
390
391type Slots<C> = IndexMap<String, Arc<ExtensionSlot<C>>>;
392type ScopeKey = (String, String);
393
394/// Owns MCP connections, scoped slots, and their advertised leases.
395pub struct ExtensionManager<C: ExtensionSpec> {
396    scopes: Mutex<HashMap<String, Slots<C>>>,
397    /// Slots `enable` has started but not yet selected. A lease resolved from
398    /// the old selection in the meantime must not lose them, or the next
399    /// lease would start a second process.
400    enabling: Mutex<HashMap<ScopeKey, Arc<ExtensionSlot<C>>>>,
401    host: Arc<dyn ExtensionHost<C>>,
402    action_required: Arc<ActionRequiredManager>,
403    default_client: Arc<ClientContext>,
404    clients: std::sync::Mutex<HashMap<String, Arc<ClientContext>>>,
405}
406
407const TOOL_EXTENSION_META_KEY: &str = "goose_extension";
408
409pub fn get_tool_owner(tool: &Tool) -> Option<String> {
410    tool.meta
411        .as_ref()
412        .and_then(|m| m.0.get(TOOL_EXTENSION_META_KEY))
413        .and_then(|v| v.as_str())
414        .map(|s| s.to_string())
415}
416
417pub fn is_tool_owned_by_extension(tool: &Tool, extension_name: &str) -> bool {
418    let expected_owner = name_to_key(extension_name);
419    get_tool_owner(tool).is_some_and(|owner| name_to_key(&owner) == expected_owner)
420}
421
422/// `tools` pairs each advertised public tool name with its owning extension's
423/// key, when known (`None` for tools with no owner metadata, e.g. those
424/// appended outside the extension manager).
425pub fn recover_mangled_tool_name<'a>(
426    emitted: &str,
427    tools: impl Iterator<Item = (&'a str, Option<&'a str>)>,
428) -> Option<String> {
429    let trimmed = emitted.trim();
430    let stripped = trimmed
431        .strip_prefix("functions.")
432        .or_else(|| trimmed.strip_prefix("functions:"))
433        .unwrap_or(trimmed);
434
435    let mut matched: Option<&str> = None;
436    for (name, owner) in tools {
437        // Prefixed tools: the model turns Goose's "__" separator into a dot
438        // ("developer__shell" -> "developer.shell").
439        let separator_mangled = name
440            .split_once("__")
441            .map(|(extension, tool)| format!("{extension}.{tool}"));
442
443        // Unprefixed tools (e.g. platform extensions like "developer" with
444        // unprefixed_tools=true) carry no "__" in their public name at all —
445        // the owner is only in metadata — so the model's "developer.shell"
446        // has to be checked against "{owner}.{name}" instead (see #9486).
447        let owner_mangled = owner.map(|o| format!("{o}.{name}"));
448        let owner_prefixed = owner.map(|o| format!("{o}__{name}"));
449
450        let matches = stripped == name
451            || separator_mangled.as_deref() == Some(stripped)
452            || owner_mangled.as_deref() == Some(stripped)
453            || owner_prefixed.as_deref() == Some(stripped);
454        if name == emitted || !matches {
455            continue;
456        }
457
458        match matched {
459            None => matched = Some(name),
460            Some(prev) if prev == name => {}
461            Some(_) => return None,
462        }
463    }
464    matched.map(|s| s.to_string())
465}
466
467fn get_tool_meta_value(tool: &Tool) -> Option<Value> {
468    tool.meta.as_ref().map(|meta| Value::Object(meta.0.clone()))
469}
470
471pub fn get_tool_resource_uri(tool: &Tool) -> Option<String> {
472    tool.meta
473        .as_ref()
474        .and_then(|meta| meta.0.get("ui"))
475        .and_then(Value::as_object)
476        .and_then(|ui| ui.get("resourceUri"))
477        .and_then(Value::as_str)
478        .map(ToString::to_string)
479}
480
481fn remove_untrusted_mcp_app_meta(result: &mut CallToolResult) {
482    let Some(meta) = result.meta.as_mut() else {
483        return;
484    };
485
486    meta.0.remove(TRUSTED_TOOL_UPDATE_META_KEY);
487
488    let remove_goose = meta
489        .0
490        .get_mut("goose")
491        .and_then(Value::as_object_mut)
492        .map(|goose_meta| {
493            goose_meta.remove("mcpApp");
494            goose_meta.is_empty()
495        })
496        .unwrap_or(false);
497
498    if remove_goose {
499        meta.0.remove("goose");
500    }
501
502    if meta.0.is_empty() {
503        result.meta = None;
504    }
505}
506
507fn insert_trusted_tool_update_meta(
508    result: &mut CallToolResult,
509    attachment: &GooseMcpAppToolAttachment,
510) {
511    let Ok(attachment_value) = serde_json::to_value(attachment) else {
512        return;
513    };
514
515    let mut meta_map = result
516        .meta
517        .as_ref()
518        .map(|meta| meta.0.clone())
519        .unwrap_or_default();
520    let mut trusted_meta = serde_json::Map::new();
521    trusted_meta.insert("mcpApp".to_string(), attachment_value);
522    meta_map.insert(
523        TRUSTED_TOOL_UPDATE_META_KEY.to_string(),
524        Value::Object(trusted_meta),
525    );
526    result.meta = Some(MetaObject(meta_map));
527}
528
529impl<C: ExtensionSpec> ExtensionManager<C> {
530    pub fn new(
531        host: Arc<dyn ExtensionHost<C>>,
532        action_required: Arc<ActionRequiredManager>,
533        default_client: ClientContext,
534    ) -> Self {
535        Self {
536            scopes: Mutex::new(HashMap::new()),
537            enabling: Mutex::new(HashMap::new()),
538            host,
539            action_required,
540            default_client: Arc::new(default_client),
541            clients: std::sync::Mutex::new(HashMap::new()),
542        }
543    }
544
545    /// The latest client to attach to a session is the one its extensions start for from
546    /// then on.
547    pub fn attach_client(&self, session_id: &str, client: ClientContext) {
548        self.clients
549            .lock()
550            .expect("clients mutex poisoned")
551            .insert(session_id.to_string(), Arc::new(client));
552    }
553
554    pub fn client(&self, session_id: &str) -> Arc<ClientContext> {
555        self.clients
556            .lock()
557            .expect("clients mutex poisoned")
558            .get(session_id)
559            .cloned()
560            .unwrap_or_else(|| Arc::clone(&self.default_client))
561    }
562
563    fn lease(
564        &self,
565        scope_id: &str,
566        working_dir: Option<PathBuf>,
567        slots: Vec<Arc<ExtensionSlot<C>>>,
568        client: &ClientContext,
569    ) -> ExtensionLease<C> {
570        ExtensionLease::new(
571            scope_id,
572            working_dir,
573            slots,
574            Arc::clone(&self.host),
575            Arc::clone(&self.action_required),
576            client.hydrates_mcp_apps(),
577        )
578    }
579
580    fn new_slot(
581        self: &Arc<Self>,
582        scope_id: &str,
583        config: &C,
584        working_dir: Option<&Path>,
585        container: Option<&Container>,
586        client: Arc<ClientContext>,
587    ) -> ExtensionSlot<C> {
588        ExtensionSlot {
589            key: config.key(),
590            config: config.clone(),
591            placement: Some(Placement::new(
592                working_dir
593                    .map(Path::to_path_buf)
594                    .unwrap_or_else(|| self.host.default_working_dir()),
595                container,
596            )),
597            scope_id: scope_id.to_string(),
598            manager: Arc::downgrade(self),
599            client,
600            config_generation: AtomicU64::new(self.host.config_generation()),
601            runtime: OnceCell::new(),
602        }
603    }
604
605    pub async fn resolve(self: &Arc<Self>, set: &ExtensionSet<C>) -> ExtensionLease<C> {
606        let client = self.client(set.scope_id());
607        let slots = {
608            let mut scopes = self.scopes.lock().await;
609            let enabling = self.enabling.lock().await;
610            let mut current = scopes.remove(set.scope_id()).unwrap_or_default();
611            let mut selected = IndexMap::new();
612            for config in set.extensions() {
613                let key = config.key();
614                let pending = enabling
615                    .get(&(set.scope_id().to_string(), key.clone()))
616                    .cloned();
617                let mut reusable = None;
618                for slot in current.swap_remove(&key).into_iter().chain(pending) {
619                    if slot.reusable_for(config, set.working_dir(), set.container(), &client)
620                        && slot.config_is_current().await
621                    {
622                        reusable = Some(slot);
623                        break;
624                    }
625                }
626                let slot = reusable.unwrap_or_else(|| {
627                    Arc::new(self.new_slot(
628                        set.scope_id(),
629                        config,
630                        set.working_dir(),
631                        set.container(),
632                        Arc::clone(&client),
633                    ))
634                });
635                selected.insert(key, slot);
636            }
637            let slots = selected.values().cloned().collect();
638            scopes.insert(set.scope_id().to_string(), selected);
639            slots
640        };
641        self.lease(
642            set.scope_id(),
643            set.working_dir().map(Path::to_path_buf),
644            slots,
645            &client,
646        )
647    }
648
649    async fn resolve_transport(&self, config: &C) -> ExtensionResult<Option<TransportConfig>> {
650        match config.transport() {
651            Some(transport) => Ok(Some(
652                transport
653                    .clone()
654                    .resolve(&host::Secrets(self.host.as_ref()))
655                    .await?,
656            )),
657            None => Ok(None),
658        }
659    }
660
661    fn timeout(&self, timeout: Option<u64>) -> Duration {
662        Duration::from_secs(timeout.unwrap_or_else(|| self.host.default_timeout()))
663    }
664
665    async fn start(
666        self: &Arc<Self>,
667        config: &C,
668        placement: Option<&Placement>,
669        session_id: &str,
670        client: &ClientContext,
671    ) -> ExtensionResult<Extension<C>> {
672        let resolved_config = self.resolve_transport(config).await?;
673        let client_working_dir = match &resolved_config {
674            Some(TransportConfig::Stdio { cwd: Some(cwd), .. }) => PathBuf::from(cwd),
675            _ => placement
676                .map(|placement| placement.working_dir.clone())
677                .unwrap_or_default(),
678        };
679        let container = placement.and_then(|placement| placement.container.as_ref());
680
681        let tools_version = Arc::new(AtomicU64::new(0));
682        let ctx = |timeout: Option<u64>, working_dir: PathBuf| ConnectContext {
683            timeout: self.timeout(timeout),
684            client_name: client.name.clone(),
685            client_version: client.version.clone(),
686            capabilities: client.capabilities.clone(),
687            working_dir,
688            docker_container: None,
689            action_required: Arc::clone(&self.action_required),
690            tools_version: Arc::clone(&tools_version),
691            trace_context: self.host.trace_context(),
692        };
693
694        let mcp_client: Box<dyn McpClientTrait> = match &resolved_config {
695            Some(TransportConfig::StreamableHttp {
696                uri,
697                timeout,
698                headers,
699                name,
700                envs,
701                socket,
702                client_id,
703                client_secret_key,
704                scopes,
705                ..
706            }) => {
707                let static_oauth_client = streamable_http::resolve_static_oauth_client(
708                    client_id.as_deref(),
709                    client_secret_key.as_deref(),
710                    scopes,
711                    &envs.get_env(),
712                )?;
713                let params = streamable_http::ConnectParams {
714                    uri: uri.clone(),
715                    name: name.clone(),
716                    headers: headers.clone(),
717                    static_oauth_client,
718                    auth: self.host.auth(),
719                    ctx: ctx(*timeout, client_working_dir),
720                };
721                streamable_http::connect(params, socket.as_deref()).await?
722            }
723            Some(TransportConfig::Stdio {
724                cmd,
725                args,
726                envs,
727                timeout,
728                ..
729            }) => {
730                let mut envs = envs.get_env();
731                envs.insert("AGENT_SESSION_ID".to_string(), session_id.to_string());
732                Box::new(
733                    stdio::connect(
734                        self.host.as_ref(),
735                        cmd,
736                        args,
737                        envs,
738                        container,
739                        ctx(*timeout, client_working_dir),
740                    )
741                    .await?,
742                )
743            }
744            None => {
745                self.host
746                    .connect(config, container, ctx(None, client_working_dir))
747                    .await?
748            }
749        };
750
751        let server_info = mcp_client.get_info().cloned();
752        Ok(Extension {
753            key: config.key(),
754            config: config.clone(),
755            resolved_config,
756            client: Arc::from(mcp_client),
757            server_info,
758            tools_version,
759            tools: Mutex::new(None),
760        })
761    }
762
763    /// Start the extension and keep it pending until `commit` selects it, so a
764    /// failure reaches whoever asked and the selection is only changed when it
765    /// starts. A concurrent enable of the same config waits on the same start.
766    pub async fn enable(
767        self: &Arc<Self>,
768        scope_id: &str,
769        config: C,
770        working_dir: &Path,
771        container: Option<&Container>,
772        commit: impl std::future::Future<Output = ExtensionResult<()>>,
773    ) -> ExtensionResult<()> {
774        let client = self.client(scope_id);
775        let pending_key = (scope_id.to_string(), config.key());
776        let slot = {
777            let scopes = self.scopes.lock().await;
778            let mut enabling = self.enabling.lock().await;
779            let selected = scopes
780                .get(scope_id)
781                .and_then(|slots| slots.get(&pending_key.1))
782                .cloned();
783            let mut reusable = None;
784            for slot in enabling
785                .get(&pending_key)
786                .cloned()
787                .into_iter()
788                .chain(selected)
789            {
790                if slot.reusable_for(&config, Some(working_dir), container, &client)
791                    && slot.config_is_current().await
792                    && !matches!(slot.runtime.get(), Some(Runtime::Failed(_)))
793                {
794                    reusable = Some(slot);
795                    break;
796                }
797            }
798            let slot = reusable.unwrap_or_else(|| {
799                Arc::new(self.new_slot(scope_id, &config, Some(working_dir), container, client))
800            });
801            enabling.insert(pending_key.clone(), Arc::clone(&slot));
802            slot
803        };
804        let result = match slot.runtime().await {
805            Runtime::Failed(error) => Err(ExtensionError::StartFailed(error.clone())),
806            Runtime::Running(_) => commit.await,
807        };
808        let mut scopes = self.scopes.lock().await;
809        let mut enabling = self.enabling.lock().await;
810        if enabling
811            .get(&pending_key)
812            .is_some_and(|pending| Arc::ptr_eq(pending, &slot))
813        {
814            enabling.remove(&pending_key);
815            if result.is_ok() {
816                scopes
817                    .entry(pending_key.0)
818                    .or_default()
819                    .insert(pending_key.1, slot);
820            }
821        }
822        result
823    }
824
825    /// Processes stop once no lease holds them.
826    pub async fn release(&self, session_id: &str) {
827        let mut scopes = self.scopes.lock().await;
828        let mut enabling = self.enabling.lock().await;
829        scopes.remove(session_id);
830        enabling.retain(|(scope_id, _), _| scope_id != session_id);
831        self.clients
832            .lock()
833            .expect("clients mutex poisoned")
834            .remove(session_id);
835    }
836}
837
838#[cfg(any(test, feature = "test-support"))]
839impl<C: ExtensionSpec> ExtensionManager<C> {
840    pub async fn scope_lease(&self, scope_id: &str) -> ExtensionLease<C> {
841        let slots = self
842            .scopes
843            .lock()
844            .await
845            .get(scope_id)
846            .into_iter()
847            .flat_map(IndexMap::values)
848            .cloned()
849            .collect();
850        self.lease(scope_id, None, slots, &self.client(scope_id))
851    }
852
853    /// Select an already-running client without starting anything.
854    pub async fn install_client(
855        self: &Arc<Self>,
856        scope_id: &str,
857        config: C,
858        client: Arc<dyn McpClientTrait>,
859        info: Option<ServerConfig>,
860    ) {
861        let mut slot = self.new_slot(scope_id, &config, None, None, self.client(scope_id));
862        slot.placement = None;
863        slot.runtime = OnceCell::new_with(Some(Runtime::Running(Arc::new(Extension {
864            key: config.key(),
865            resolved_config: config.transport().cloned(),
866            config,
867            client,
868            server_info: info,
869            tools_version: Arc::new(AtomicU64::new(0)),
870            tools: Mutex::new(None),
871        }))));
872        self.scopes
873            .lock()
874            .await
875            .entry(scope_id.to_string())
876            .or_default()
877            .insert(slot.key.clone(), Arc::new(slot));
878    }
879
880    pub async fn slots(&self, scope_id: &str) -> Slots<C> {
881        self.scopes
882            .lock()
883            .await
884            .get(scope_id)
885            .cloned()
886            .unwrap_or_default()
887    }
888
889    /// Hold the slot table, blocking resolves until the guard drops.
890    pub async fn lock_slots(&self) -> impl Drop + '_ {
891        self.scopes.lock().await
892    }
893}
894
895#[cfg(any(test, feature = "test-support"))]
896impl<C: ExtensionSpec> ExtensionSlot<C> {
897    pub async fn tools_version(&self) -> Option<Arc<AtomicU64>> {
898        self.start()
899            .await
900            .map(|extension| Arc::clone(&extension.tools_version))
901    }
902}