Repository navigation
Expand file tree
/
Copy pathinstallation_confirmation.rs
More file actions
294 lines (271 loc) · 10 KB
/
Copy pathinstallation_confirmation.rs
File metadata and controls
294 lines (271 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
// Copyright (c) Microsoft Corporation. All rights reserved.
//! Connection-global human confirmation for experimental installation operations.
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::panic::AssertUnwindSafe;
use std::sync::{Arc, OnceLock, Weak};
use async_trait::async_trait;
use futures_util::FutureExt;
use parking_lot::{Mutex, RwLock};
use tokio_util::sync::CancellationToken;
use tracing::warn;
pub use crate::rpc::{
InstallationConfirmationRequest, InstallationConfirmationResponse, InstallationDecision,
InstallationReview, McpInstallationReview,
};
use crate::{
Client, ClientInner, JsonRpcError, JsonRpcRequest, JsonRpcResponse, Result, error_codes,
};
pub(crate) const CONFIRM_METHOD: &str = "installations.confirm";
const REQUEST_CANCELLED: i32 = -32800;
/// The cancellation lifetime of one confirmation.
///
/// This signal retires a human review when the runtime cancels the request or
/// the original connection closes. It does not cancel outbound installation or
/// OAuth RPCs. The runtime remains authoritative for the operation's expiry.
#[derive(Clone)]
pub struct InstallationConfirmationContext {
cancellation: CancellationToken,
}
impl InstallationConfirmationContext {
/// Cancelled when the runtime retires this request or the original connection closes.
///
/// Cancelling the returned child token cannot cancel another review.
pub fn cancellation(&self) -> CancellationToken {
self.cancellation.child_token()
}
}
/// Collects a fresh human decision for the complete review on its original connection.
///
/// Match the request's `operation_id` and `policy_session_id` against the exact
/// action registered by the host before displaying it. Never infer the originating
/// action from a current session, server name or global pending slot. Refuse
/// unknown actions or incomplete reviews.
///
/// The SDK echoes the original challenge and fingerprint; the handler returns
/// only the decision. Cancellation drops the handler future, so any separately
/// spawned UI work must also observe the supplied context.
///
/// This experimental callback does not imply that the connected runtime supports
/// installation, removal or activation.
#[async_trait]
pub trait InstallationConfirmationHandler: Send + Sync + 'static {
/// Review this operation and return an explicit decision, or an error to refuse it.
async fn confirm(
&self,
request: InstallationConfirmationRequest,
context: InstallationConfirmationContext,
) -> Result<InstallationDecision>;
}
/// Registered synchronously by the transport before forwarding each confirmation.
/// This preserves request/cancellation ordering across the router's separate queues.
#[derive(Default)]
pub(crate) struct ConfirmationRequests {
pending: Mutex<HashMap<u64, Arc<CancellationToken>>>,
}
impl ConfirmationRequests {
pub(crate) fn register(&self, id: u64) -> bool {
let mut pending = self.pending.lock();
match pending.entry(id) {
Entry::Vacant(entry) => {
entry.insert(Arc::new(CancellationToken::new()));
true
}
Entry::Occupied(_) => false,
}
}
pub(crate) fn cancel(&self, id: u64) {
if let Some(token) = self.pending.lock().get(&id) {
token.cancel();
}
}
pub(crate) fn clear(&self) {
self.pending.lock().clear();
}
fn claim(self: &Arc<Self>, id: u64) -> Option<PendingConfirmation> {
let cancellation = self.pending.lock().get(&id)?.clone();
Some(PendingConfirmation {
requests: self.clone(),
id,
cancellation,
})
}
}
struct PendingConfirmation {
requests: Arc<ConfirmationRequests>,
id: u64,
cancellation: Arc<CancellationToken>,
}
impl Drop for PendingConfirmation {
fn drop(&mut self) {
let mut pending = self.requests.pending.lock();
if pending
.get(&self.id)
.is_some_and(|token| Arc::ptr_eq(token, &self.cancellation))
{
pending.remove(&self.id);
}
}
}
pub(crate) struct InstallationConfirmationDispatcher {
handler: RwLock<Option<Arc<dyn InstallationConfirmationHandler>>>,
client: OnceLock<Weak<ClientInner>>,
}
impl InstallationConfirmationDispatcher {
pub(crate) fn new() -> Self {
Self {
handler: RwLock::new(None),
client: OnceLock::new(),
}
}
pub(crate) fn set_client(&self, client: Weak<ClientInner>) {
let _ = self.client.set(client);
}
#[cfg(any(feature = "runtime", test, feature = "test-support"))]
pub(crate) fn set_handler(&self, handler: Option<Arc<dyn InstallationConfirmationHandler>>) {
*self.handler.write() = handler;
}
pub(crate) fn clear(&self) {
self.handler.write().take();
}
pub(crate) fn dispatch(self: &Arc<Self>, request: JsonRpcRequest) {
let Some(client) = self.client.get().and_then(Weak::upgrade) else {
return;
};
let Some(pending) = client.rpc.confirmation_requests.claim(request.id) else {
warn!("confirmation request retired before dispatch");
return;
};
let request_cancelled = pending.cancellation.as_ref().clone();
let connection_closed = client.rpc.connection_closed_token();
let context = InstallationConfirmationContext {
cancellation: connection_closed.child_token(),
};
let handler = self.handler.read().clone();
let dispatcher = self.clone();
tokio::spawn(async move {
let outcome = tokio::select! {
biased;
_ = connection_closed.cancelled() => return,
_ = request_cancelled.cancelled() => {
context.cancellation.cancel();
Err((REQUEST_CANCELLED, "Installation confirmation request cancelled"))
}
outcome = Self::handle(handler, request.params, context.clone()) => outcome,
};
if connection_closed.is_cancelled() {
return;
}
let outcome = if request_cancelled.is_cancelled() {
context.cancellation.cancel();
Err((
REQUEST_CANCELLED,
"Installation confirmation request cancelled",
))
} else {
outcome
};
dispatcher.respond(request.id, outcome).await;
drop(pending);
});
}
async fn handle(
handler: Option<Arc<dyn InstallationConfirmationHandler>>,
params: Option<serde_json::Value>,
context: InstallationConfirmationContext,
) -> std::result::Result<InstallationConfirmationResponse, (i32, &'static str)> {
let Some(handler) = handler else {
return Err((
error_codes::METHOD_NOT_FOUND,
"No installations client-global handler registered",
));
};
let request: InstallationConfirmationRequest =
serde_json::from_value(params.unwrap_or(serde_json::Value::Null)).map_err(|_| {
(
error_codes::INVALID_PARAMS,
"Invalid installation confirmation review",
)
})?;
let confirmation_id = request.confirmation_id.clone();
let review_fingerprint = request.review_fingerprint.clone();
let outcome = AssertUnwindSafe(handler.confirm(request, context))
.catch_unwind()
.await;
let decision = match outcome {
Ok(Ok(
decision @ (InstallationDecision::Confirm
| InstallationDecision::Decline
| InstallationDecision::Cancel),
)) => decision,
Ok(Ok(InstallationDecision::Unknown)) => {
return Err((
error_codes::INTERNAL_ERROR,
"Invalid installation confirmation decision",
));
}
Ok(Err(_)) => {
return Err((
error_codes::INTERNAL_ERROR,
"Installation confirmation handler failed",
));
}
Err(_) => {
return Err((
error_codes::INTERNAL_ERROR,
"Installation confirmation handler panicked",
));
}
};
Ok(InstallationConfirmationResponse {
confirmation_id,
review_fingerprint,
decision,
})
}
async fn respond(
&self,
id: u64,
outcome: std::result::Result<InstallationConfirmationResponse, (i32, &'static str)>,
) {
let Some(client) = self.client.get().and_then(Weak::upgrade) else {
return;
};
let (result, error) = match outcome {
Ok(response) => match serde_json::to_value(response) {
Ok(value) => (Some(value), None),
Err(_) => {
warn!("failed to serialise installation confirmation response");
(
None,
Some(JsonRpcError {
code: error_codes::INTERNAL_ERROR,
message: "Installation confirmation serialisation failed".to_string(),
data: None,
}),
)
}
},
Err((code, message)) => (
None,
Some(JsonRpcError {
code,
message: message.to_string(),
data: None,
}),
),
};
if Client::from_inner(client)
.send_response(&JsonRpcResponse {
jsonrpc: "2.0".to_string(),
id,
result,
error,
})
.await
.is_err()
{
warn!("failed to send installation confirmation response");
}
}
}