Skip to main content

oi_kit_agent/mcp/
client.rs

1use crate::action_required_manager::{ActionRequiredManager, ElicitationOutcome};
2use crate::mcp::{ToolCallNotificationEmitter, TraceContextInjector};
3
4pub const SESSION_ID_HEADER: &str = "agent-session-id";
5pub const TOOL_CALL_REQUEST_ID_HEADER: &str = "agent-tool-call-request-id";
6pub const WORKING_DIR_HEADER: &str = "agent-working-dir";
7
8#[expect(deprecated)]
9use rmcp::model::{
10    ElicitRequestParams, ElicitResult, ListRootsResult, LoggingMessageNotification, Root,
11};
12use rmcp::model::{
13    ElicitationAction, ElicitationCapability, ErrorCode, ExtensionCapabilities, Extensions,
14    FormElicitationCapability, JsonObject, MetaObject,
15};
16use rmcp::{
17    model::{
18        CallToolRequestParams, CallToolResult, CancelledNotificationParam, ClientCapabilities,
19        ClientConfig, ClientRequest, GetPromptRequestParams, GetPromptResult, Implementation,
20        InitializeRequestParams, InitializeResult, ListPromptsResult, ListResourcesResult,
21        ListToolsResult, Notification, PaginatedRequestParams, ProtocolVersion,
22        ReadResourceRequestParams, ReadResourceResult, Request, RequestId, RequestOptionalParam,
23        ServerNotification, ServerResult,
24    },
25    service::{
26        ClientInitializeError, ClientLifecycleMode, ClientServiceExt, PeerRequestOptions,
27        RequestContext, RequestHandle, RunningService, ServiceRole,
28    },
29    transport::IntoTransport,
30    ClientHandler, ErrorData, Peer, RoleClient, ServiceError,
31};
32use serde_json::Value;
33use std::{
34    collections::HashMap,
35    path::PathBuf,
36    sync::{
37        atomic::{AtomicU64, Ordering},
38        Arc, Mutex as StdMutex,
39    },
40    time::Duration,
41};
42use tokio::sync::{
43    mpsc::{self, Sender},
44    Mutex,
45};
46use tokio_util::sync::CancellationToken;
47
48pub type BoxError = Box<dyn std::error::Error + Sync + Send>;
49
50pub type Error = rmcp::ServiceError;
51
52const MCP_APPS_UI_EXTENSION_ID: &str = "io.modelcontextprotocol/ui";
53const MCP_APPS_UI_MIME_TYPE: &str = "text/html;profile=mcp-app";
54
55fn default_mcp_apps_ui_extensions() -> ExtensionCapabilities {
56    let mut extensions = ExtensionCapabilities::new();
57    let mut ui_extension_settings = JsonObject::new();
58    ui_extension_settings.insert(
59        "mimeTypes".to_string(),
60        serde_json::json!([MCP_APPS_UI_MIME_TYPE]),
61    );
62    extensions.insert(MCP_APPS_UI_EXTENSION_ID.to_string(), ui_extension_settings);
63    extensions
64}
65
66#[derive(Debug, Clone, Default, PartialEq)]
67pub struct GooseMcpHostInfo {
68    pub explicit_extensions: bool,
69    pub extensions: ExtensionCapabilities,
70    pub client_name: Option<String>,
71    pub client_version: Option<String>,
72}
73
74impl GooseMcpHostInfo {
75    pub fn mcpui_enabled(&self) -> bool {
76        self.extensions.contains_key(MCP_APPS_UI_EXTENSION_ID)
77    }
78}
79
80#[derive(Clone)]
81pub struct McpCallContext {
82    pub session_id: String,
83    pub working_dir: Option<PathBuf>,
84    pub tool_call_request_id: Option<String>,
85    notification_emitter: Option<ToolCallNotificationEmitter>,
86}
87
88impl McpCallContext {
89    pub fn new(
90        session_id: String,
91        working_dir: Option<PathBuf>,
92        tool_call_request_id: Option<String>,
93    ) -> Self {
94        Self {
95            session_id,
96            working_dir,
97            tool_call_request_id,
98            notification_emitter: None,
99        }
100    }
101    pub fn working_dir_str(&self) -> Option<&str> {
102        self.working_dir.as_ref().and_then(|path| path.to_str())
103    }
104    pub fn with_notification_emitter(mut self, emitter: ToolCallNotificationEmitter) -> Self {
105        self.notification_emitter = Some(emitter);
106        self
107    }
108    pub fn notification_emitter(&self) -> Option<&ToolCallNotificationEmitter> {
109        self.notification_emitter.as_ref()
110    }
111}
112
113#[async_trait::async_trait]
114pub trait McpClientTrait: Send + Sync {
115    async fn list_tools(
116        &self,
117        session_id: &str,
118        next_cursor: Option<String>,
119        cancel_token: CancellationToken,
120    ) -> Result<ListToolsResult, Error>;
121
122    async fn call_tool(
123        &self,
124        ctx: &McpCallContext,
125        name: &str,
126        arguments: Option<JsonObject>,
127        cancel_token: CancellationToken,
128    ) -> Result<CallToolResult, Error>;
129
130    fn get_info(&self) -> Option<&InitializeResult>;
131
132    async fn list_resources(
133        &self,
134        _session_id: &str,
135        _next_cursor: Option<String>,
136        _cancel_token: CancellationToken,
137    ) -> Result<ListResourcesResult, Error> {
138        Err(Error::TransportClosed)
139    }
140
141    async fn read_resource(
142        &self,
143        _session_id: &str,
144        _uri: &str,
145        _cancel_token: CancellationToken,
146    ) -> Result<ReadResourceResult, Error> {
147        Err(Error::TransportClosed)
148    }
149
150    async fn list_prompts(
151        &self,
152        _session_id: &str,
153        _next_cursor: Option<String>,
154        _cancel_token: CancellationToken,
155    ) -> Result<ListPromptsResult, Error> {
156        Err(Error::TransportClosed)
157    }
158
159    async fn get_prompt(
160        &self,
161        _session_id: &str,
162        _name: &str,
163        _arguments: Value,
164        _cancel_token: CancellationToken,
165    ) -> Result<GetPromptResult, Error> {
166        Err(Error::TransportClosed)
167    }
168
169    async fn subscribe(&self) -> mpsc::Receiver<ServerNotification> {
170        mpsc::channel(1).1
171    }
172}
173
174struct ActiveToolCallGuard {
175    active_tool_calls: Arc<StdMutex<HashMap<String, Vec<String>>>>,
176    session_id: String,
177    tool_call_request_id: String,
178}
179
180impl Drop for ActiveToolCallGuard {
181    fn drop(&mut self) {
182        let mut active_tool_calls = self
183            .active_tool_calls
184            .lock()
185            .expect("active_tool_calls mutex poisoned");
186        if let Some(calls) = active_tool_calls.get_mut(&self.session_id) {
187            if let Some(pos) = calls.iter().position(|id| id == &self.tool_call_request_id) {
188                calls.remove(pos);
189            }
190            if calls.is_empty() {
191                active_tool_calls.remove(&self.session_id);
192            }
193        }
194    }
195}
196
197pub struct GooseClient {
198    notification_handlers: Arc<Mutex<Vec<Sender<ServerNotification>>>>,
199    session_id: Mutex<Option<String>>,
200    active_tool_calls: Arc<StdMutex<HashMap<String, Vec<String>>>>,
201    client_name: String,
202    client_version: String,
203    capabilities: GooseMcpClientCapabilities,
204    working_dir: PathBuf,
205    action_required: Arc<ActionRequiredManager>,
206    tools_version: Arc<AtomicU64>,
207}
208
209impl GooseClient {
210    fn new(
211        handlers: Arc<Mutex<Vec<Sender<ServerNotification>>>>,
212        client_name: String,
213        client_version: String,
214        capabilities: GooseMcpClientCapabilities,
215        working_dir: PathBuf,
216        action_required: Arc<ActionRequiredManager>,
217        tools_version: Arc<AtomicU64>,
218    ) -> Self {
219        GooseClient {
220            notification_handlers: handlers,
221            session_id: Mutex::new(None),
222            active_tool_calls: Arc::new(StdMutex::new(HashMap::new())),
223            client_name,
224            client_version,
225            capabilities,
226            working_dir,
227            action_required,
228            tools_version,
229        }
230    }
231
232    async fn set_session_id(&self, session_id: &str) {
233        let mut slot = self.session_id.lock().await;
234        assert!(
235            slot.as_deref().is_none_or(|s| s == session_id),
236            "McpClient received requests from different sessions"
237        );
238        *slot = Some(session_id.to_string());
239    }
240
241    fn handle_tool_list_changed(&self) {
242        self.tools_version.fetch_add(1, Ordering::SeqCst);
243    }
244
245    async fn current_session_id(&self) -> Option<String> {
246        self.session_id.lock().await.clone()
247    }
248
249    /// A server that echoes our request `_meta` on its own requests lets us
250    /// route them to the exact call; otherwise fall back to the session this
251    /// client serves.
252    async fn resolve_session_id(&self, meta: &MetaObject) -> Option<String> {
253        match meta_value(meta, SESSION_ID_HEADER) {
254            Some(session_id) => Some(session_id),
255            None => self.current_session_id().await,
256        }
257    }
258
259    fn register_active_tool_call(
260        &self,
261        session_id: &str,
262        tool_call_request_id: &str,
263    ) -> ActiveToolCallGuard {
264        self.active_tool_calls
265            .lock()
266            .expect("active_tool_calls mutex poisoned")
267            .entry(session_id.to_string())
268            .or_default()
269            .push(tool_call_request_id.to_string());
270        ActiveToolCallGuard {
271            active_tool_calls: self.active_tool_calls.clone(),
272            session_id: session_id.to_string(),
273            tool_call_request_id: tool_call_request_id.to_string(),
274        }
275    }
276
277    fn resolve_tool_call_request_id(
278        &self,
279        session_id: &str,
280        meta: &MetaObject,
281    ) -> Result<String, ErrorData> {
282        if let Some(tool_call_request_id) = meta_value(meta, TOOL_CALL_REQUEST_ID_HEADER) {
283            return Ok(tool_call_request_id);
284        }
285
286        let active_tool_calls = self
287            .active_tool_calls
288            .lock()
289            .expect("active_tool_calls mutex poisoned");
290        match active_tool_calls.get(session_id).map(Vec::as_slice) {
291            Some([tool_call_request_id]) => Ok(tool_call_request_id.clone()),
292            Some(calls) if calls.len() > 1 => Err(ErrorData::new(
293                ErrorCode::INTERNAL_ERROR,
294                "Cannot correlate elicitation request: multiple tool calls are active and the \
295                 server did not echo the tool call request id",
296                None,
297            )),
298            _ => Err(ErrorData::new(
299                ErrorCode::INTERNAL_ERROR,
300                "Could not resolve tool call request id for elicitation request",
301                None,
302            )),
303        }
304    }
305
306    fn resolved_extensions(&self) -> ExtensionCapabilities {
307        if let Some(host_info) = &self.capabilities.host_info {
308            if host_info.explicit_extensions {
309                return host_info.extensions.clone();
310            }
311        }
312
313        if self.capabilities.mcpui {
314            return default_mcp_apps_ui_extensions();
315        }
316
317        ExtensionCapabilities::new()
318    }
319
320    fn resolved_client_info(&self) -> Implementation {
321        let name = self
322            .capabilities
323            .host_info
324            .as_ref()
325            .and_then(|host_info| host_info.client_name.clone())
326            .unwrap_or_else(|| self.client_name.clone());
327        let version = self
328            .capabilities
329            .host_info
330            .as_ref()
331            .and_then(|host_info| host_info.client_version.clone())
332            .unwrap_or_else(|| self.client_version.clone());
333
334        Implementation::new(name, version)
335    }
336}
337
338fn meta_value(meta: &MetaObject, key: &str) -> Option<String> {
339    meta.0
340        .iter()
341        .find(|(k, _)| k.eq_ignore_ascii_case(key))
342        .and_then(|(_, value)| value.as_str())
343        .map(str::to_string)
344}
345
346#[expect(deprecated)]
347fn working_dir_roots(dir: &std::path::Path) -> ListRootsResult {
348    let uri = url::Url::from_file_path(dir)
349        .map(|u| u.to_string())
350        .unwrap_or_else(|()| format!("file://{}", dir.display()));
351    ListRootsResult::new(vec![Root::new(uri).with_name("working_directory")])
352}
353
354/// Fan out a notification to all subscribers, dropping senders whose receivers are gone.
355fn fan_out_notification(
356    handlers: &mut Vec<Sender<ServerNotification>>,
357    notification: ServerNotification,
358) {
359    handlers.retain(|handler| match handler.try_send(notification.clone()) {
360        Ok(()) => true,
361        Err(mpsc::error::TrySendError::Full(_)) => true,
362        Err(mpsc::error::TrySendError::Closed(_)) => false,
363    });
364}
365
366impl ClientHandler for GooseClient {
367    #[expect(deprecated)]
368    async fn list_roots(
369        &self,
370        _context: RequestContext<RoleClient>,
371    ) -> Result<ListRootsResult, ErrorData> {
372        Ok(working_dir_roots(&self.working_dir))
373    }
374
375    async fn on_progress(
376        &self,
377        params: rmcp::model::ProgressNotificationParam,
378        context: rmcp::service::NotificationContext<rmcp::RoleClient>,
379    ) {
380        let mut not = Notification::new(params);
381        not.extensions = context.extensions;
382        fan_out_notification(
383            &mut *self.notification_handlers.lock().await,
384            ServerNotification::ProgressNotification(not),
385        );
386    }
387
388    async fn on_tool_list_changed(&self, _context: rmcp::service::NotificationContext<RoleClient>) {
389        self.handle_tool_list_changed();
390    }
391
392    #[expect(deprecated)]
393    async fn on_logging_message(
394        &self,
395        params: rmcp::model::LoggingMessageNotificationParam,
396        context: rmcp::service::NotificationContext<rmcp::RoleClient>,
397    ) {
398        let mut notification = LoggingMessageNotification::new(params);
399        notification.extensions = context.extensions;
400        fan_out_notification(
401            &mut *self.notification_handlers.lock().await,
402            ServerNotification::LoggingMessageNotification(notification),
403        );
404    }
405
406    async fn create_elicitation(
407        &self,
408        request: ElicitRequestParams,
409        context: RequestContext<RoleClient>,
410    ) -> Result<ElicitResult, ErrorData> {
411        if let Some(handler) = &self.capabilities.elicitation_handler {
412            return Ok(handler(&request));
413        }
414
415        let session_id = self
416            .resolve_session_id(&context.meta)
417            .await
418            .ok_or_else(|| {
419                ErrorData::new(
420                    ErrorCode::INTERNAL_ERROR,
421                    "Could not resolve session id for elicitation request",
422                    None,
423                )
424            })?;
425        let tool_call_request_id = self.resolve_tool_call_request_id(&session_id, &context.meta)?;
426
427        let (message, schema_value) = match &request {
428            ElicitRequestParams::FormElicitationParams {
429                message,
430                requested_schema,
431                ..
432            } => {
433                let schema_value = serde_json::to_value(requested_schema).map_err(|e| {
434                    ErrorData::new(
435                        ErrorCode::INTERNAL_ERROR,
436                        format!("Failed to serialize elicitation schema: {}", e),
437                        None,
438                    )
439                })?;
440                (message.clone(), schema_value)
441            }
442            ElicitRequestParams::UrlElicitationParams { message, url, .. } => {
443                (message.clone(), serde_json::json!({ "url": url }))
444            }
445            _ => (String::new(), serde_json::json!({})),
446        };
447
448        self.action_required
449            .request_and_wait(
450                session_id,
451                tool_call_request_id,
452                message,
453                schema_value,
454                Duration::from_secs(300),
455            )
456            .await
457            .map(|response| match response {
458                ElicitationOutcome::Accept(user_data) => {
459                    ElicitResult::new(ElicitationAction::Accept).with_content(user_data)
460                }
461                ElicitationOutcome::Decline => ElicitResult::new(ElicitationAction::Decline),
462                ElicitationOutcome::Cancel => ElicitResult::new(ElicitationAction::Cancel),
463            })
464            .map_err(|e| {
465                ErrorData::new(
466                    ErrorCode::INTERNAL_ERROR,
467                    format!("Elicitation request timed out or failed: {}", e),
468                    None,
469                )
470            })
471    }
472
473    fn get_info(&self) -> ClientConfig {
474        let extensions = self.resolved_extensions();
475
476        InitializeRequestParams::new(
477            #[expect(deprecated)]
478            ClientCapabilities::builder()
479                .enable_roots()
480                .enable_extensions_with(extensions)
481                .enable_elicitation_with(
482                    ElicitationCapability::new().with_form(FormElicitationCapability::new()),
483                )
484                .build(),
485            self.resolved_client_info(),
486        )
487        .with_protocol_version(
488            self.capabilities
489                .protocol_version
490                .clone()
491                .unwrap_or_default(),
492        )
493    }
494}
495
496pub type ElicitationHandler = Arc<dyn Fn(&ElicitRequestParams) -> ElicitResult + Send + Sync>;
497
498#[derive(Clone, Default)]
499pub struct GooseMcpClientCapabilities {
500    pub mcpui: bool,
501    pub host_info: Option<GooseMcpHostInfo>,
502    pub elicitation_handler: Option<ElicitationHandler>,
503    pub protocol_version: Option<ProtocolVersion>,
504}
505
506impl std::fmt::Debug for GooseMcpClientCapabilities {
507    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
508        formatter
509            .debug_struct("GooseMcpClientCapabilities")
510            .field("mcpui", &self.mcpui)
511            .field("host_info", &self.host_info)
512            .field("elicitation_handler", &self.elicitation_handler.is_some())
513            .field("protocol_version", &self.protocol_version)
514            .finish()
515    }
516}
517
518#[derive(Clone)]
519pub struct ConnectContext {
520    pub timeout: Duration,
521    pub client_name: String,
522    pub client_version: String,
523    pub capabilities: GooseMcpClientCapabilities,
524    pub working_dir: PathBuf,
525    pub docker_container: Option<String>,
526    pub action_required: Arc<ActionRequiredManager>,
527    pub tools_version: Arc<AtomicU64>,
528    pub trace_context: Option<TraceContextInjector>,
529}
530
531/// The MCP client is the interface for MCP operations.
532pub struct McpClient {
533    client: Mutex<Arc<RunningService<RoleClient, GooseClient>>>,
534    notification_subscribers: Arc<Mutex<Vec<mpsc::Sender<ServerNotification>>>>,
535    server_info: Option<InitializeResult>,
536    timeout: std::time::Duration,
537    docker_container: Option<String>,
538    trace_context: Option<TraceContextInjector>,
539}
540
541impl McpClient {
542    pub async fn connect<T, E, A>(
543        transport: T,
544        ctx: ConnectContext,
545    ) -> Result<Self, Box<ClientInitializeError>>
546    where
547        T: IntoTransport<RoleClient, E, A>,
548        E: std::error::Error + From<std::io::Error> + Send + Sync + 'static,
549    {
550        let ConnectContext {
551            timeout,
552            client_name,
553            client_version,
554            capabilities,
555            working_dir,
556            docker_container,
557            action_required,
558            tools_version,
559            trace_context,
560        } = ctx;
561        let notification_subscribers =
562            Arc::new(Mutex::new(Vec::<mpsc::Sender<ServerNotification>>::new()));
563
564        let client = GooseClient::new(
565            notification_subscribers.clone(),
566            client_name.clone(),
567            client_version,
568            capabilities.clone(),
569            working_dir,
570            action_required,
571            tools_version,
572        );
573        let client: rmcp::service::RunningService<rmcp::RoleClient, GooseClient> =
574            if let Some(protocol_version) = capabilities.protocol_version {
575                let lifecycle = if protocol_version >= ProtocolVersion::STANDARD_HEADERS {
576                    ClientLifecycleMode::Discover {
577                        preferred_versions: vec![protocol_version],
578                    }
579                } else {
580                    ClientLifecycleMode::Initialize
581                };
582                client.serve_with_lifecycle(transport, lifecycle).await?
583            } else {
584                client
585                    .serve_with_lifecycle(
586                        transport,
587                        ClientLifecycleMode::Auto {
588                            preferred_versions: vec![
589                                ProtocolVersion::V_2026_07_28,
590                                ProtocolVersion::V_2025_11_25,
591                            ],
592                            legacy_version: Some(ProtocolVersion::V_2025_11_25),
593                        },
594                    )
595                    .await?
596            };
597        let server_info = client.peer_info().map(|info| {
598            let mut initialize_result = InitializeResult::new(info.capabilities.clone())
599                .with_protocol_version(info.protocol_version.clone());
600            if let Some(server_info) = &info.server_info {
601                initialize_result = initialize_result.with_server_info(server_info.clone());
602            }
603            initialize_result.instructions = info.instructions.clone();
604            initialize_result.meta = info.meta.clone();
605            initialize_result
606        });
607
608        Ok(Self {
609            client: Mutex::new(Arc::new(client)),
610            notification_subscribers,
611            server_info,
612            timeout,
613            docker_container,
614            trace_context,
615        })
616    }
617
618    pub fn docker_container(&self) -> Option<&str> {
619        self.docker_container.as_deref()
620    }
621
622    async fn send_request_with_context(
623        &self,
624        session_id: &str,
625        working_dir: Option<&str>,
626        tool_call_request_id: Option<&str>,
627        request: ClientRequest,
628        cancel_token: CancellationToken,
629    ) -> Result<ServerResult, Error> {
630        let request = inject_call_trace_context(
631            inject_session_context_into_request(
632                request,
633                Some(session_id),
634                working_dir,
635                tool_call_request_id,
636            ),
637            self.trace_context,
638        );
639        let active_tool_call = tool_call_request_id.filter(|id| !id.is_empty());
640        // The inner mutex is held only for the send; the actual response wait
641        // happens outside the lock so concurrent calls can overlap. The guard
642        // unregisters the active tool call on drop, covering cancellation and
643        // dropped reply streams as well as normal completion.
644        let (handle, _active_tool_call_guard) = {
645            let client = self.client.lock().await;
646            client.service().set_session_id(session_id).await;
647            let guard = active_tool_call.map(|tool_call_request_id| {
648                client
649                    .service()
650                    .register_active_tool_call(session_id, tool_call_request_id)
651            });
652            let handle = client
653                .send_cancellable_request(request, PeerRequestOptions::no_options())
654                .await?;
655            (handle, guard)
656        };
657
658        await_response(handle, self.timeout, &cancel_token).await
659    }
660}
661
662async fn await_response(
663    handle: RequestHandle<RoleClient>,
664    timeout: Duration,
665    cancel_token: &CancellationToken,
666) -> Result<<RoleClient as ServiceRole>::PeerResp, ServiceError> {
667    let receiver = handle.rx;
668    let peer = handle.peer;
669    let request_id = handle.id;
670    tokio::select! {
671        result = receiver => {
672            result.map_err(|_e| ServiceError::TransportClosed)?
673        }
674        _ = tokio::time::sleep(timeout) => {
675            send_cancel_message(&peer, request_id, Some("timed out".to_owned())).await?;
676            Err(ServiceError::Timeout{timeout})
677        }
678        _ = cancel_token.cancelled() => {
679            send_cancel_message(&peer, request_id, Some("operation cancelled".to_owned())).await?;
680            Err(ServiceError::Cancelled { reason: None })
681        }
682    }
683}
684
685async fn send_cancel_message(
686    peer: &Peer<RoleClient>,
687    request_id: RequestId,
688    reason: Option<String>,
689) -> Result<(), ServiceError> {
690    peer.send_notification(
691        Notification::new(CancelledNotificationParam::new(Some(request_id), reason)).into(),
692    )
693    .await
694}
695
696#[async_trait::async_trait]
697impl McpClientTrait for McpClient {
698    fn get_info(&self) -> Option<&InitializeResult> {
699        self.server_info.as_ref()
700    }
701
702    async fn list_resources(
703        &self,
704        session_id: &str,
705        cursor: Option<String>,
706        cancel_token: CancellationToken,
707    ) -> Result<ListResourcesResult, Error> {
708        let res = self
709            .send_request_with_context(
710                session_id,
711                None,
712                None,
713                ClientRequest::ListResourcesRequest(RequestOptionalParam::with_param(
714                    PaginatedRequestParams::default().with_cursor(cursor),
715                )),
716                cancel_token,
717            )
718            .await?;
719
720        match res {
721            ServerResult::ListResourcesResult(result) => Ok(result),
722            _ => Err(ServiceError::UnexpectedResponse),
723        }
724    }
725
726    async fn read_resource(
727        &self,
728        session_id: &str,
729        uri: &str,
730        cancel_token: CancellationToken,
731    ) -> Result<ReadResourceResult, Error> {
732        let params = ReadResourceRequestParams::new(uri.to_string());
733        let client = self.client.lock().await.clone();
734        if client
735            .peer_info()
736            .is_some_and(|info| info.protocol_version == ProtocolVersion::V_2026_07_28)
737        {
738            client.service().set_session_id(session_id).await;
739            return tokio::select! {
740                result = client.read_resource(params) => result,
741                _ = tokio::time::sleep(self.timeout) => Err(ServiceError::Timeout { timeout: self.timeout }),
742                _ = cancel_token.cancelled() => Err(ServiceError::Cancelled { reason: None }),
743            };
744        }
745        drop(client);
746
747        let res = self
748            .send_request_with_context(
749                session_id,
750                None,
751                None,
752                ClientRequest::ReadResourceRequest(Request::new(params)),
753                cancel_token,
754            )
755            .await?;
756
757        match res {
758            ServerResult::ReadResourceResult(result) => Ok(result),
759            _ => Err(ServiceError::UnexpectedResponse),
760        }
761    }
762
763    async fn list_tools(
764        &self,
765        session_id: &str,
766        cursor: Option<String>,
767        cancel_token: CancellationToken,
768    ) -> Result<ListToolsResult, Error> {
769        let res = self
770            .send_request_with_context(
771                session_id,
772                None,
773                None,
774                ClientRequest::ListToolsRequest(RequestOptionalParam::with_param(
775                    PaginatedRequestParams::default().with_cursor(cursor),
776                )),
777                cancel_token,
778            )
779            .await?;
780
781        match res {
782            ServerResult::ListToolsResult(result) => Ok(result),
783            _ => Err(ServiceError::UnexpectedResponse),
784        }
785    }
786
787    async fn call_tool(
788        &self,
789        ctx: &McpCallContext,
790        name: &str,
791        arguments: Option<JsonObject>,
792        cancel_token: CancellationToken,
793    ) -> Result<CallToolResult, Error> {
794        let mut params = CallToolRequestParams::new(name.to_string());
795        if let Some(args) = arguments {
796            params = params.with_arguments(args);
797        }
798        let protocol_version = {
799            let client = self.client.lock().await;
800            client.peer_info().map(|info| info.protocol_version.clone())
801        };
802        if protocol_version.as_ref() == Some(&ProtocolVersion::V_2026_07_28) {
803            let extensions = inject_trace_context(
804                inject_session_context_into_extensions(
805                    Extensions::new(),
806                    Some(&ctx.session_id),
807                    ctx.working_dir_str(),
808                    ctx.tool_call_request_id.as_deref(),
809                ),
810                self.trace_context,
811            );
812            if let Some(meta) = extensions.get::<MetaObject>() {
813                params.meta.get_or_insert_default().0 .0.extend(
814                    meta.0
815                        .iter()
816                        .map(|(key, value)| (key.clone(), value.clone())),
817                );
818            }
819            let client = self.client.lock().await.clone();
820            client.service().set_session_id(&ctx.session_id).await;
821            let _active_tool_call_guard = ctx
822                .tool_call_request_id
823                .as_deref()
824                .filter(|id| !id.is_empty())
825                .map(|tool_call_request_id| {
826                    client
827                        .service()
828                        .register_active_tool_call(&ctx.session_id, tool_call_request_id)
829                });
830            return tokio::select! {
831                result = client.call_tool(params) => result,
832                _ = tokio::time::sleep(self.timeout) => {
833                    Err(ServiceError::Timeout { timeout: self.timeout })
834                }
835                _ = cancel_token.cancelled() => {
836                    Err(ServiceError::Cancelled { reason: None })
837                }
838            };
839        }
840
841        let request = ClientRequest::CallToolRequest(Request::new(params));
842
843        let result = self
844            .send_request_with_context(
845                &ctx.session_id,
846                ctx.working_dir_str(),
847                ctx.tool_call_request_id.as_deref(),
848                request,
849                cancel_token,
850            )
851            .await;
852
853        match result? {
854            ServerResult::CallToolResult(result) => Ok(result),
855            _ => Err(ServiceError::UnexpectedResponse),
856        }
857    }
858
859    async fn list_prompts(
860        &self,
861        session_id: &str,
862        cursor: Option<String>,
863        cancel_token: CancellationToken,
864    ) -> Result<ListPromptsResult, Error> {
865        let res = self
866            .send_request_with_context(
867                session_id,
868                None,
869                None,
870                ClientRequest::ListPromptsRequest(RequestOptionalParam::with_param(
871                    PaginatedRequestParams::default().with_cursor(cursor),
872                )),
873                cancel_token,
874            )
875            .await?;
876
877        match res {
878            ServerResult::ListPromptsResult(result) => Ok(result),
879            _ => Err(ServiceError::UnexpectedResponse),
880        }
881    }
882
883    async fn get_prompt(
884        &self,
885        session_id: &str,
886        name: &str,
887        arguments: Value,
888        cancel_token: CancellationToken,
889    ) -> Result<GetPromptResult, Error> {
890        let arguments = match arguments {
891            Value::Object(map) => Some(map),
892            _ => None,
893        };
894        let mut params = GetPromptRequestParams::new(name.to_string());
895        if let Some(args) = arguments {
896            params = params.with_arguments(args);
897        }
898        let client = self.client.lock().await.clone();
899        if client
900            .peer_info()
901            .is_some_and(|info| info.protocol_version == ProtocolVersion::V_2026_07_28)
902        {
903            client.service().set_session_id(session_id).await;
904            return tokio::select! {
905                result = client.get_prompt(params) => result,
906                _ = tokio::time::sleep(self.timeout) => Err(ServiceError::Timeout { timeout: self.timeout }),
907                _ = cancel_token.cancelled() => Err(ServiceError::Cancelled { reason: None }),
908            };
909        }
910        drop(client);
911
912        let res = self
913            .send_request_with_context(
914                session_id,
915                None,
916                None,
917                ClientRequest::GetPromptRequest(Request::new(params)),
918                cancel_token,
919            )
920            .await?;
921
922        match res {
923            ServerResult::GetPromptResult(result) => Ok(result),
924            _ => Err(ServiceError::UnexpectedResponse),
925        }
926    }
927
928    async fn subscribe(&self) -> mpsc::Receiver<ServerNotification> {
929        let (tx, rx) = mpsc::channel(16);
930        self.notification_subscribers.lock().await.push(tx);
931        rx
932    }
933}
934
935/// Injects the given session_id and working_dir into Extensions._meta.
936/// None (or empty) removes any existing values.
937fn inject_session_context_into_extensions(
938    mut extensions: Extensions,
939    session_id: Option<&str>,
940    working_dir: Option<&str>,
941    tool_call_request_id: Option<&str>,
942) -> Extensions {
943    let session_id = session_id.filter(|id| !id.is_empty());
944    let working_dir = working_dir.filter(|dir| !dir.is_empty());
945    let tool_call_request_id = tool_call_request_id.filter(|id| !id.is_empty());
946    let mut meta_map = extensions
947        .get::<MetaObject>()
948        .map(|meta| meta.0.clone())
949        .unwrap_or_default();
950
951    // JsonObject is case-sensitive, so we use retain for case-insensitive removal
952    meta_map.retain(|k, _| {
953        !k.eq_ignore_ascii_case(SESSION_ID_HEADER)
954            && !k.eq_ignore_ascii_case(WORKING_DIR_HEADER)
955            && !k.eq_ignore_ascii_case(TOOL_CALL_REQUEST_ID_HEADER)
956    });
957
958    if let Some(session_id) = session_id {
959        meta_map.insert(
960            SESSION_ID_HEADER.to_string(),
961            Value::String(session_id.to_string()),
962        );
963    }
964
965    if let Some(working_dir) = working_dir {
966        meta_map.insert(
967            WORKING_DIR_HEADER.to_string(),
968            Value::String(working_dir.to_string()),
969        );
970    }
971
972    if let Some(tool_call_request_id) = tool_call_request_id {
973        meta_map.insert(
974            TOOL_CALL_REQUEST_ID_HEADER.to_string(),
975            Value::String(tool_call_request_id.to_string()),
976        );
977    }
978
979    extensions.insert(MetaObject(meta_map));
980    extensions
981}
982
983fn inject_trace_context(
984    mut extensions: Extensions,
985    inject: Option<TraceContextInjector>,
986) -> Extensions {
987    let Some(inject) = inject else {
988        return extensions;
989    };
990    let mut meta_map = extensions
991        .get::<MetaObject>()
992        .map(|meta| meta.0.clone())
993        .unwrap_or_default();
994    inject(&mut meta_map);
995    extensions.insert(MetaObject(meta_map));
996    extensions
997}
998
999/// Only tool calls carry the caller's trace, so a server's spans nest under the call.
1000fn inject_call_trace_context(
1001    request: ClientRequest,
1002    inject: Option<TraceContextInjector>,
1003) -> ClientRequest {
1004    match request {
1005        ClientRequest::CallToolRequest(mut req) => {
1006            req.extensions = inject_trace_context(req.extensions, inject);
1007            ClientRequest::CallToolRequest(req)
1008        }
1009        request => request,
1010    }
1011}
1012
1013fn inject_session_context_into_request(
1014    request: ClientRequest,
1015    session_id: Option<&str>,
1016    working_dir: Option<&str>,
1017    tool_call_request_id: Option<&str>,
1018) -> ClientRequest {
1019    match request {
1020        ClientRequest::ListResourcesRequest(mut req) => {
1021            req.extensions = inject_session_context_into_extensions(
1022                req.extensions,
1023                session_id,
1024                working_dir,
1025                None,
1026            );
1027            ClientRequest::ListResourcesRequest(req)
1028        }
1029        ClientRequest::ReadResourceRequest(mut req) => {
1030            req.extensions = inject_session_context_into_extensions(
1031                req.extensions,
1032                session_id,
1033                working_dir,
1034                None,
1035            );
1036            ClientRequest::ReadResourceRequest(req)
1037        }
1038        ClientRequest::ListToolsRequest(mut req) => {
1039            req.extensions = inject_session_context_into_extensions(
1040                req.extensions,
1041                session_id,
1042                working_dir,
1043                None,
1044            );
1045            ClientRequest::ListToolsRequest(req)
1046        }
1047        ClientRequest::CallToolRequest(mut req) => {
1048            req.extensions = inject_session_context_into_extensions(
1049                req.extensions,
1050                session_id,
1051                working_dir,
1052                tool_call_request_id,
1053            );
1054            ClientRequest::CallToolRequest(req)
1055        }
1056        ClientRequest::ListPromptsRequest(mut req) => {
1057            req.extensions = inject_session_context_into_extensions(
1058                req.extensions,
1059                session_id,
1060                working_dir,
1061                None,
1062            );
1063            ClientRequest::ListPromptsRequest(req)
1064        }
1065        ClientRequest::GetPromptRequest(mut req) => {
1066            req.extensions = inject_session_context_into_extensions(
1067                req.extensions,
1068                session_id,
1069                working_dir,
1070                None,
1071            );
1072            ClientRequest::GetPromptRequest(req)
1073        }
1074        other => other,
1075    }
1076}
1077
1078#[cfg(test)]
1079mod tests {
1080    use super::*;
1081
1082    use serde_json::json;
1083    use test_case::test_case;
1084
1085    const DESKTOP: &str = "goose-desktop";
1086    const CLI: &str = "goose-cli";
1087    const VERSION: &str = "1.0.0";
1088
1089    fn new_client(name: &str) -> GooseClient {
1090        let capabilities = GooseMcpClientCapabilities {
1091            mcpui: name == DESKTOP,
1092            host_info: None,
1093            elicitation_handler: None,
1094            protocol_version: None,
1095        };
1096
1097        GooseClient::new(
1098            Arc::new(Mutex::new(Vec::new())),
1099            name.to_string(),
1100            VERSION.to_string(),
1101            capabilities,
1102            std::env::current_dir().unwrap_or_default(),
1103            Arc::new(ActionRequiredManager::new()),
1104            Arc::new(AtomicU64::new(0)),
1105        )
1106    }
1107
1108    #[test]
1109    fn tool_list_changed_bumps_tools_version() {
1110        let client = new_client(CLI);
1111        let before = client.tools_version.load(Ordering::SeqCst);
1112        client.handle_tool_list_changed();
1113        assert_eq!(client.tools_version.load(Ordering::SeqCst), before + 1);
1114    }
1115
1116    fn request_extensions(request: &ClientRequest) -> Option<&Extensions> {
1117        match request {
1118            ClientRequest::ListResourcesRequest(req) => Some(&req.extensions),
1119            ClientRequest::ReadResourceRequest(req) => Some(&req.extensions),
1120            ClientRequest::ListToolsRequest(req) => Some(&req.extensions),
1121            ClientRequest::CallToolRequest(req) => Some(&req.extensions),
1122            ClientRequest::ListPromptsRequest(req) => Some(&req.extensions),
1123            ClientRequest::GetPromptRequest(req) => Some(&req.extensions),
1124            _ => None,
1125        }
1126    }
1127
1128    fn list_resources_request(extensions: Extensions) -> ClientRequest {
1129        let mut req = RequestOptionalParam::with_param(PaginatedRequestParams::default());
1130        req.extensions = extensions;
1131        ClientRequest::ListResourcesRequest(req)
1132    }
1133
1134    fn read_resource_request(extensions: Extensions) -> ClientRequest {
1135        let mut req = Request::new(ReadResourceRequestParams::new(
1136            "test://resource".to_string(),
1137        ));
1138        req.extensions = extensions;
1139        ClientRequest::ReadResourceRequest(req)
1140    }
1141
1142    fn list_tools_request(extensions: Extensions) -> ClientRequest {
1143        let mut req = RequestOptionalParam::with_param(PaginatedRequestParams::default());
1144        req.extensions = extensions;
1145        ClientRequest::ListToolsRequest(req)
1146    }
1147
1148    fn call_tool_request(extensions: Extensions) -> ClientRequest {
1149        let mut req = Request::new(CallToolRequestParams::new("tool".to_string()));
1150        req.extensions = extensions;
1151        ClientRequest::CallToolRequest(req)
1152    }
1153
1154    fn list_prompts_request(extensions: Extensions) -> ClientRequest {
1155        let mut req = RequestOptionalParam::with_param(PaginatedRequestParams::default());
1156        req.extensions = extensions;
1157        ClientRequest::ListPromptsRequest(req)
1158    }
1159
1160    fn get_prompt_request(extensions: Extensions) -> ClientRequest {
1161        let mut req = Request::new(GetPromptRequestParams::new("prompt".to_string()));
1162        req.extensions = extensions;
1163        ClientRequest::GetPromptRequest(req)
1164    }
1165
1166    #[test_case(list_resources_request; "list_resources")]
1167    #[test_case(read_resource_request; "read_resource")]
1168    #[test_case(list_tools_request; "list_tools")]
1169    #[test_case(call_tool_request; "call_tool")]
1170    #[test_case(list_prompts_request; "list_prompts")]
1171    #[test_case(get_prompt_request; "get_prompt")]
1172    fn test_request_injects_session(request_builder: fn(Extensions) -> ClientRequest) {
1173        let session_id = "test-session-id";
1174        let mut extensions = Extensions::new();
1175        extensions.insert(
1176            serde_json::from_value::<MetaObject>(json!({
1177                "Goose-Session-Id": "old-session-id",
1178                "other-key": "preserve-me"
1179            }))
1180            .unwrap(),
1181        );
1182
1183        let request = request_builder(extensions);
1184        let request = inject_session_context_into_request(request, Some(session_id), None, None);
1185        let extensions = request_extensions(&request).expect("request should have extensions");
1186        let meta = extensions
1187            .get::<MetaObject>()
1188            .expect("extensions should contain meta");
1189
1190        assert_eq!(
1191            meta.0.get(SESSION_ID_HEADER),
1192            Some(&Value::String(session_id.to_string()))
1193        );
1194        assert_eq!(
1195            meta.0.get("other-key"),
1196            Some(&Value::String("preserve-me".to_string()))
1197        );
1198        if matches!(request, ClientRequest::CallToolRequest(_)) {
1199            assert!(!meta.0.contains_key(TOOL_CALL_REQUEST_ID_HEADER));
1200        }
1201    }
1202
1203    #[test_case(
1204        Some("new-session-id"),
1205        json!({
1206            SESSION_ID_HEADER: "new-session-id",
1207            "other-key": "preserve-me"
1208        });
1209        "replace"
1210    )]
1211    #[test_case(
1212        None,
1213        json!({
1214            "other-key": "preserve-me"
1215        });
1216        "remove"
1217    )]
1218    #[test_case(
1219        Some(""),
1220        json!({
1221            "other-key": "preserve-me"
1222        });
1223        "empty removes"
1224    )]
1225    fn test_session_id_case_insensitive_replacement(
1226        session_id: Option<&str>,
1227        expected_meta: serde_json::Value,
1228    ) {
1229        use rmcp::model::Extensions;
1230        use serde_json::from_value;
1231
1232        let mut extensions = Extensions::new();
1233        extensions.insert(
1234            from_value::<MetaObject>(json!({
1235                SESSION_ID_HEADER: "old-session-1",
1236                "Agent-Session-Id": "old-session-2",
1237                "other-key": "preserve-me"
1238            }))
1239            .unwrap(),
1240        );
1241
1242        let extensions = inject_session_context_into_extensions(extensions, session_id, None, None);
1243        let mcp_meta = extensions.get::<MetaObject>().unwrap();
1244
1245        assert_eq!(&mcp_meta.0, expected_meta.as_object().unwrap());
1246    }
1247
1248    fn fake_trace_context(meta: &mut JsonObject) {
1249        meta.insert("traceparent".to_string(), json!("trace"));
1250        meta.insert("tracestate".to_string(), json!("vendor=value"));
1251    }
1252
1253    #[test_case(list_resources_request, false; "list_resources")]
1254    #[test_case(read_resource_request, false; "read_resource")]
1255    #[test_case(list_tools_request, false; "list_tools")]
1256    #[test_case(call_tool_request, true; "call_tool")]
1257    #[test_case(list_prompts_request, false; "list_prompts")]
1258    #[test_case(get_prompt_request, false; "get_prompt")]
1259    fn test_request_injects_trace_context_only_on_call_tool(
1260        request_builder: fn(Extensions) -> ClientRequest,
1261        expect_trace_context: bool,
1262    ) {
1263        let request = inject_call_trace_context(
1264            inject_session_context_into_request(
1265                request_builder(Extensions::new()),
1266                Some("test-session-id"),
1267                None,
1268                None,
1269            ),
1270            Some(fake_trace_context),
1271        );
1272        let meta = request_extensions(&request)
1273            .and_then(|extensions| extensions.get::<MetaObject>())
1274            .expect("request should carry meta");
1275
1276        assert_eq!(
1277            meta.0.get(SESSION_ID_HEADER),
1278            Some(&json!("test-session-id"))
1279        );
1280        if expect_trace_context {
1281            assert_eq!(meta.0.get("traceparent"), Some(&json!("trace")));
1282            assert_eq!(meta.0.get("tracestate"), Some(&json!("vendor=value")));
1283        } else {
1284            assert!(!meta.0.contains_key("traceparent"));
1285            assert!(!meta.0.contains_key("tracestate"));
1286        }
1287    }
1288
1289    #[test]
1290    fn test_client_info_advertises_mcp_apps_ui_extension() {
1291        let client = new_client(DESKTOP);
1292        let info = ClientHandler::get_info(&client);
1293
1294        // Verify the client advertises the MCP Apps UI extension capability
1295        let extensions = info
1296            .capabilities
1297            .extensions
1298            .expect("capabilities should have extensions");
1299
1300        let ui_ext = extensions
1301            .get("io.modelcontextprotocol/ui")
1302            .expect("should have io.modelcontextprotocol/ui extension");
1303
1304        let mime_types = ui_ext
1305            .get("mimeTypes")
1306            .expect("ui extension should have mimeTypes");
1307
1308        assert_eq!(mime_types, &json!(["text/html;profile=mcp-app"]));
1309    }
1310
1311    #[test]
1312    fn test_client_capabilities_advertise_roots() {
1313        let client = new_client(CLI);
1314        let info = ClientHandler::get_info(&client);
1315        assert!(
1316            info.capabilities.roots.is_some(),
1317            "client should advertise roots capability"
1318        );
1319    }
1320
1321    #[test]
1322    fn test_client_capabilities_advertise_form_elicitation() {
1323        let client = new_client(CLI);
1324        let info = ClientHandler::get_info(&client);
1325        let capabilities = serde_json::to_value(info.capabilities).unwrap();
1326        assert_eq!(
1327            capabilities.get("elicitation"),
1328            Some(&json!({ "form": {} }))
1329        );
1330    }
1331
1332    #[test]
1333    fn test_client_capabilities_do_not_advertise_sampling() {
1334        let client = new_client(CLI);
1335        let info = ClientHandler::get_info(&client);
1336        let capabilities = serde_json::to_value(info.capabilities).unwrap();
1337        assert!(capabilities.get("sampling").is_none());
1338    }
1339
1340    #[test]
1341    fn test_explicit_host_info_passes_through_client_identity() {
1342        let client = GooseClient::new(
1343            Arc::new(Mutex::new(Vec::new())),
1344            DESKTOP.to_string(),
1345            VERSION.to_string(),
1346            GooseMcpClientCapabilities {
1347                mcpui: true,
1348                host_info: Some(GooseMcpHostInfo {
1349                    explicit_extensions: true,
1350                    extensions: ExtensionCapabilities::new(),
1351                    client_name: Some("goose2".to_string()),
1352                    client_version: Some("0.1.0".to_string()),
1353                }),
1354                elicitation_handler: None,
1355                protocol_version: None,
1356            },
1357            std::env::current_dir().unwrap_or_default(),
1358            Arc::new(ActionRequiredManager::new()),
1359            Arc::new(AtomicU64::new(0)),
1360        );
1361
1362        let info = ClientHandler::get_info(&client);
1363        assert_eq!(info.client_info.name, "goose2");
1364        assert_eq!(info.client_info.version, "0.1.0");
1365        let extensions = info
1366            .capabilities
1367            .extensions
1368            .expect("client should still serialize an extensions object");
1369        assert!(
1370            !extensions.contains_key(MCP_APPS_UI_EXTENSION_ID),
1371            "explicit empty host extensions should disable platform fallback"
1372        );
1373    }
1374
1375    #[test]
1376    fn test_explicit_host_extensions_override_platform_fallback() {
1377        let client = GooseClient::new(
1378            Arc::new(Mutex::new(Vec::new())),
1379            CLI.to_string(),
1380            VERSION.to_string(),
1381            GooseMcpClientCapabilities {
1382                mcpui: false,
1383                host_info: Some(GooseMcpHostInfo {
1384                    explicit_extensions: true,
1385                    extensions: default_mcp_apps_ui_extensions(),
1386                    client_name: Some("goose2".to_string()),
1387                    client_version: Some("0.1.0".to_string()),
1388                }),
1389                elicitation_handler: None,
1390                protocol_version: None,
1391            },
1392            std::env::current_dir().unwrap_or_default(),
1393            Arc::new(ActionRequiredManager::new()),
1394            Arc::new(AtomicU64::new(0)),
1395        );
1396
1397        let info = ClientHandler::get_info(&client);
1398        let extensions = info
1399            .capabilities
1400            .extensions
1401            .expect("capabilities should have explicit host extensions");
1402
1403        assert!(extensions.contains_key(MCP_APPS_UI_EXTENSION_ID));
1404        assert_eq!(info.client_info.name, "goose2");
1405    }
1406
1407    #[test]
1408    fn test_host_identity_does_not_disable_platform_fallback_without_explicit_extensions() {
1409        let client = GooseClient::new(
1410            Arc::new(Mutex::new(Vec::new())),
1411            DESKTOP.to_string(),
1412            VERSION.to_string(),
1413            GooseMcpClientCapabilities {
1414                mcpui: true,
1415                host_info: Some(GooseMcpHostInfo {
1416                    explicit_extensions: false,
1417                    extensions: ExtensionCapabilities::new(),
1418                    client_name: Some("goose2".to_string()),
1419                    client_version: Some("0.1.0".to_string()),
1420                }),
1421                elicitation_handler: None,
1422                protocol_version: None,
1423            },
1424            std::env::current_dir().unwrap_or_default(),
1425            Arc::new(ActionRequiredManager::new()),
1426            Arc::new(AtomicU64::new(0)),
1427        );
1428
1429        let info = ClientHandler::get_info(&client);
1430        let extensions = info
1431            .capabilities
1432            .extensions
1433            .expect("platform fallback should still advertise MCP Apps UI");
1434
1435        assert!(extensions.contains_key(MCP_APPS_UI_EXTENSION_ID));
1436        assert_eq!(info.client_info.name, "goose2");
1437    }
1438
1439    #[tokio::test]
1440    async fn fan_out_notification_prunes_closed_subscribers() {
1441        use rmcp::model::{NumberOrString, ProgressNotificationParam, ProgressToken};
1442
1443        let handlers = Arc::new(Mutex::new(Vec::new()));
1444        let mut receivers = Vec::new();
1445        for _ in 0..5 {
1446            let (tx, rx) = mpsc::channel(16);
1447            handlers.lock().await.push(tx);
1448            receivers.push(rx);
1449        }
1450        assert_eq!(handlers.lock().await.len(), 5);
1451
1452        // Drop all receivers, simulating tool-call completion.
1453        drop(receivers);
1454
1455        let notification = ServerNotification::ProgressNotification(Notification::new(
1456            ProgressNotificationParam::new(
1457                ProgressToken(NumberOrString::String(Arc::from("token"))),
1458                1.0,
1459            ),
1460        ));
1461        fan_out_notification(&mut *handlers.lock().await, notification);
1462        assert!(
1463            handlers.lock().await.is_empty(),
1464            "closed subscribers must be pruned on fan-out"
1465        );
1466
1467        // A live subscriber survives fan-out; subsequent closed ones still prune.
1468        let mut live_rx = {
1469            let (tx, rx) = mpsc::channel(16);
1470            handlers.lock().await.push(tx);
1471            rx
1472        };
1473        for _ in 0..3 {
1474            let (tx, rx) = mpsc::channel(16);
1475            handlers.lock().await.push(tx);
1476            drop(rx);
1477        }
1478        assert_eq!(handlers.lock().await.len(), 4);
1479
1480        let notification = ServerNotification::ProgressNotification(Notification::new(
1481            ProgressNotificationParam::new(
1482                ProgressToken(NumberOrString::String(Arc::from("token-2"))),
1483                2.0,
1484            ),
1485        ));
1486        fan_out_notification(&mut *handlers.lock().await, notification.clone());
1487        assert_eq!(handlers.lock().await.len(), 1);
1488        let received = live_rx
1489            .recv()
1490            .await
1491            .expect("live subscriber should receive");
1492        assert!(matches!(
1493            received,
1494            ServerNotification::ProgressNotification(_)
1495        ));
1496    }
1497}