Clean up cancelled MCP elicitation requests (#35836)

## Why

Cancelling an in-flight MCP elicitation could leave its response handler registered in the shared router.

## What changed

- Remove an elicitation from the router when its pending request future is dropped.
- Keep cleanup scoped to the cancelled request so other pending elicitations remain routable.

## Testing

Added a test that cancels one of two pending elicitations, verifies the cancelled request can no longer be resolved, and confirms the other request still completes.

GitOrigin-RevId: 9a10360459f0b39552d9d29a6e1b867c1f09e97d
This commit is contained in:
jif authored and copyberry committed 2026-07-28 22:16:42 +00:00
1 parent 1def0a8925
commit c550cb3e01
2 files changed
+121 -9

No files matched your search

+33 -9
View File
@@ -32,7 +32,6 @@ use futures::future::BoxFuture;
use futures::future::FutureExt;
use rmcp::model::ElicitationAction;
use rmcp::model::RequestId;
use tokio::sync::Mutex;
use tokio::sync::oneshot;
static NEXT_ELICITATION_REQUEST_ID: AtomicU64 = AtomicU64::new(0);
@@ -87,10 +86,27 @@ struct ActiveElicitation {
/// the same server request ID without colliding.
#[derive(Clone, Default)]
pub(crate) struct ElicitationRequestRouter {
requests: Arc<Mutex<ResponderMap>>,
requests: Arc<StdMutex<ResponderMap>>,
auto_deny: Arc<AtomicBool>,
}
struct PendingElicitationRequest {
router: ElicitationRequestRouter,
key: (String, RequestId),
}
impl Drop for PendingElicitationRequest {
fn drop(&mut self) {
let responder = self
.router
.requests
.lock()
.ok()
.and_then(|mut requests| requests.remove(&self.key));
drop(responder);
}
}
impl ElicitationRequestRouter {
pub(crate) fn auto_deny(&self) -> bool {
self.auto_deny.load(Ordering::Relaxed)
@@ -106,11 +122,13 @@ impl ElicitationRequestRouter {
id: RequestId,
response: ElicitationResponse,
) -> Result<()> {
self.requests
let responder = self
.requests
.lock()
.await
.map_err(|_| anyhow!("elicitation request router unavailable"))?
.remove(&(server_name, id))
.ok_or_else(|| anyhow!("elicitation request not found"))?
.ok_or_else(|| anyhow!("elicitation request not found"))?;
responder
.send(response)
.map_err(|e| anyhow!("failed to send elicitation response: {e:?}"))
}
@@ -294,10 +312,16 @@ impl ElicitationRequestManager {
};
let (tx, rx) = oneshot::channel();
let _active_elicitation = lifecycle.as_ref().map(ElicitationLifecycle::start);
{
let mut lock = router.requests.lock().await;
lock.insert((server_name.clone(), routed_request_id), tx);
}
let request_key = (server_name.clone(), routed_request_id);
router
.requests
.lock()
.map_err(|_| anyhow!("elicitation request router unavailable"))?
.insert(request_key.clone(), tx);
let _pending_request = PendingElicitationRequest {
router: router.clone(),
key: request_key,
};
let _ = tx_event
.send(Event {
id: "mcp_elicitation_request".to_string(),