1use crate::runtime::VerificationOutcome;
2use crate::runtime::binding::{
3 validate_envelope_freshness, validate_lease, validate_receipt, validate_reservation,
4};
5use crate::{
6 ActionEnvelope, ActionPreview, ComputerUseError, ComputerUseRuntime, ControlLease,
7 ExecutionReceipt, SessionDeletionResult, SessionFollowUp, SessionFollowUpPage,
8 TargetReservation,
9};
10use adk_tool::McpToolset;
11use async_trait::async_trait;
12use rmcp::{RoleClient, service::Service};
13use serde_json::{Map, Value, json};
14use std::collections::HashMap;
15use std::sync::Arc;
16use tokio::sync::Mutex;
17use tracing::Instrument;
18
19#[derive(Debug, Clone)]
21pub struct ComputerUseMcpConfig {
22 pub session_id: String,
24 pub expected_principal_id: String,
26 pub capability_tool: String,
28 pub target_app: Option<String>,
30 pub target_window_id: Option<u64>,
32 pub correlation: TraceCorrelation,
34}
35
36#[derive(Debug, Clone, Default)]
38pub struct TraceCorrelation {
39 pub adk_session_id: Option<String>,
41 pub adk_invocation_id: Option<String>,
43 pub adk_graph_thread_id: Option<String>,
45 pub trace_id: Option<String>,
47}
48
49pub struct ComputerUseMcpRuntime<S>
70where
71 S: Service<RoleClient> + Send + Sync + 'static,
72{
73 toolset: Arc<McpToolset<S>>,
74 config: ComputerUseMcpConfig,
75 proposed: Mutex<HashMap<String, ProposedAction>>,
76}
77
78#[derive(Clone)]
79struct ProposedAction {
80 arguments: Map<String, Value>,
81 preview: ActionPreview,
82}
83
84impl<S> ComputerUseMcpRuntime<S>
85where
86 S: Service<RoleClient> + Send + Sync + 'static,
87{
88 pub fn new(toolset: Arc<McpToolset<S>>, config: ComputerUseMcpConfig) -> Self {
90 Self { toolset, config, proposed: Mutex::new(HashMap::new()) }
91 }
92
93 pub async fn observe_tool(
101 &self,
102 tool: &str,
103 arguments: Value,
104 ) -> Result<Value, ComputerUseError> {
105 self.observe_through_shadow(tool, arguments).await
106 }
107
108 pub async fn delete_terminal_session(&self) -> Result<SessionDeletionResult, ComputerUseError> {
116 let value = output(
117 self.call(
118 "delete_session",
119 object(json!({
120 "session_id": self.config.session_id,
121 "confirm": true,
122 }))?,
123 )
124 .await?,
125 );
126 Ok(serde_json::from_value(value.get("deletion").cloned().unwrap_or(value))?)
127 }
128
129 pub async fn prune_terminal_sessions(
137 &self,
138 older_than: &str,
139 limit: u32,
140 ) -> Result<Vec<SessionDeletionResult>, ComputerUseError> {
141 let value = output(
142 self.call(
143 "prune_sessions",
144 object(json!({
145 "older_than": older_than,
146 "limit": limit,
147 "confirm": true,
148 }))?,
149 )
150 .await?,
151 );
152 Ok(serde_json::from_value(value.get("deletions").cloned().unwrap_or_else(|| json!([])))?)
153 }
154
155 pub async fn get_follow_ups(
165 &self,
166 after_sequence: u64,
167 limit: u32,
168 ) -> Result<SessionFollowUpPage, ComputerUseError> {
169 if limit == 0 || limit > 1000 {
170 return Err(ComputerUseError::InvalidRequest(
171 "follow-up limit must be between 1 and 1000".into(),
172 ));
173 }
174 let value = output(
175 self.call(
176 "get_follow_ups",
177 object(json!({
178 "session_id": self.config.session_id,
179 "after_sequence": after_sequence,
180 "limit": limit,
181 }))?,
182 )
183 .await?,
184 );
185 let page: SessionFollowUpPage = serde_json::from_value(value)?;
186 if page.follow_ups.iter().any(|item| {
187 item.session_id != self.config.session_id
188 || item.principal_id != self.config.expected_principal_id
189 }) {
190 return Err(ComputerUseError::IdentityMismatch(
191 "follow-up identity does not match authenticated ADK context".into(),
192 ));
193 }
194 Ok(page)
195 }
196
197 pub async fn submit_follow_up(
206 &self,
207 instruction: &str,
208 ) -> Result<SessionFollowUp, ComputerUseError> {
209 let value = output(
210 self.call(
211 "submit_follow_up",
212 object(json!({
213 "session_id": self.config.session_id,
214 "instruction": instruction,
215 }))?,
216 )
217 .await?,
218 );
219 let follow_up: SessionFollowUp =
220 serde_json::from_value(value.get("follow_up").cloned().unwrap_or(value))?;
221 if follow_up.session_id != self.config.session_id
222 || follow_up.principal_id != self.config.expected_principal_id
223 {
224 return Err(ComputerUseError::IdentityMismatch(
225 "follow-up identity does not match authenticated ADK context".into(),
226 ));
227 }
228 Ok(follow_up)
229 }
230
231 async fn call(
232 &self,
233 name: &str,
234 arguments: Map<String, Value>,
235 ) -> Result<Value, ComputerUseError> {
236 let span = tracing::info_span!(
237 "computer_use.mcp",
238 mcp.tool = name,
239 runtime.session_id = %self.config.session_id,
240 adk.session_id = ?self.config.correlation.adk_session_id,
241 adk.invocation_id = ?self.config.correlation.adk_invocation_id,
242 adk.graph_thread_id = ?self.config.correlation.adk_graph_thread_id,
243 trace_id = ?self.config.correlation.trace_id,
244 );
245 self.toolset
246 .call_tool_value(name, arguments)
247 .instrument(span)
248 .await
249 .map_err(|error| ComputerUseError::Mcp(error.to_string()))
250 }
251
252 async fn observe_through_shadow(
253 &self,
254 tool: &str,
255 arguments: Value,
256 ) -> Result<Value, ComputerUseError> {
257 self.call(
258 "execute_action",
259 object(json!({
260 "session_id": self.config.session_id,
261 "action_id": uuid::Uuid::new_v4().to_string(),
262 "tool": tool,
263 "arguments": arguments,
264 "mode": "shadow",
265 "data_labels": ["private"],
266 }))?,
267 )
268 .await
269 }
270}
271
272fn output(value: Value) -> Value {
273 value
274 .get("response")
275 .and_then(|value| value.get("output"))
276 .or_else(|| value.get("output"))
277 .cloned()
278 .unwrap_or(value)
279}
280
281fn object(value: Value) -> Result<Map<String, Value>, ComputerUseError> {
282 let mut value = value.as_object().cloned().ok_or_else(|| {
283 ComputerUseError::InvalidRequest("proposed action must be an object".into())
284 })?;
285 value.retain(|_, entry| !entry.is_null());
286 Ok(value)
287}
288
289fn evaluate_postcondition_evidence(
296 receipt: &ExecutionReceipt,
297 postcondition: &crate::ActionPostcondition,
298) -> VerificationOutcome {
299 let expected = expected_digest(postcondition);
300
301 let Some(verification) = receipt.result.as_ref().and_then(|result| result.get("verification"))
302 else {
303 return VerificationOutcome::CommittedUnverified {
304 reason: "the receipt carried no verification evidence for the declared postcondition"
305 .to_string(),
306 };
307 };
308
309 if verification.get("satisfied").and_then(Value::as_bool) == Some(false) {
311 return VerificationOutcome::Failed {
312 reason: "the runtime reported the postcondition was not satisfied".to_string(),
313 };
314 }
315
316 let observed = verification.get("observedDigest").and_then(Value::as_str);
317
318 match (expected, observed) {
319 (Some(expected), Some(observed)) if expected == observed => VerificationOutcome::Verified,
320 (Some(expected), Some(observed)) => VerificationOutcome::Failed {
321 reason: format!(
322 "observed digest {observed:?} does not match the expected postcondition digest \
323 {expected:?}"
324 ),
325 },
326 (Some(_), None) => VerificationOutcome::CommittedUnverified {
327 reason: "verification evidence carried no observed digest to compare".to_string(),
328 },
329 (None, _) => match verification.get("satisfied").and_then(Value::as_bool) {
332 Some(true) => VerificationOutcome::Verified,
333 _ => VerificationOutcome::CommittedUnverified {
334 reason: "the postcondition declares no digest and the evidence made no explicit \
335 satisfied claim"
336 .to_string(),
337 },
338 },
339 }
340}
341
342fn expected_digest(postcondition: &crate::ActionPostcondition) -> Option<&str> {
344 use crate::ActionPostcondition;
345 match postcondition {
346 ActionPostcondition::UiElement { value_digest, .. } => value_digest.as_deref(),
347 ActionPostcondition::Filesystem { content_digest, .. } => content_digest.as_deref(),
348 ActionPostcondition::Registry { value_digest, .. } => value_digest.as_deref(),
349 _ => None,
350 }
351}
352
353#[async_trait]
354impl<S> ComputerUseRuntime for ComputerUseMcpRuntime<S>
355where
356 S: Service<RoleClient> + Send + Sync + 'static,
357{
358 async fn discover_capabilities(&self) -> Result<Value, ComputerUseError> {
359 self.call(
360 "get_execution_capabilities",
361 object(json!({
362 "tool": self.config.capability_tool,
363 "app_id": self.config.target_app,
364 }))?,
365 )
366 .await
367 }
368
369 async fn observe_visual(&self) -> Result<Value, ComputerUseError> {
370 self.observe_through_shadow(
371 "snapshot",
372 json!({
373 "use_vision": true,
374 "use_annotation": true,
375 "target_app": self.config.target_app,
376 }),
377 )
378 .await
379 }
380
381 async fn observe_semantic(&self) -> Result<Value, ComputerUseError> {
382 let (name, args) = match self.config.target_window_id {
383 Some(window_id) => ("get_ui_tree", json!({ "window_id": window_id })),
384 None => ("list_windows", json!({ "bundle_id": self.config.target_app })),
385 };
386 self.observe_through_shadow(name, args).await
387 }
388
389 async fn preview_action(
390 &self,
391 proposed_action: Value,
392 ) -> Result<ActionPreview, ComputerUseError> {
393 let mut args = object(proposed_action)?;
394 args.insert("session_id".into(), json!(self.config.session_id));
395 let preview: ActionPreview =
396 serde_json::from_value(output(self.call("preview_action", args.clone()).await?))?;
397 if preview.envelope.session_id != self.config.session_id {
398 return Err(ComputerUseError::IdentityMismatch(
399 "preview returned a different session identity".into(),
400 ));
401 }
402 if preview.envelope.principal_id != self.config.expected_principal_id {
403 return Err(ComputerUseError::IdentityMismatch(
404 "preview principal does not match authenticated ADK identity".into(),
405 ));
406 }
407 self.proposed.lock().await.insert(
408 preview.envelope.action_id.clone(),
409 ProposedAction { arguments: args, preview: preview.clone() },
410 );
411 Ok(preview)
412 }
413
414 async fn acquire_lease(
415 &self,
416 envelope: &ActionEnvelope,
417 ) -> Result<ControlLease, ComputerUseError> {
418 let kind = if envelope.requested_mode == crate::ExecutionMode::Foreground {
419 "exclusive"
420 } else {
421 "cooperative"
422 };
423 let value = output(
424 self.call(
425 "acquire_control_lease",
426 object(json!({
427 "session_id": envelope.session_id,
428 "agent_id": envelope.agent_id,
429 "kind": kind,
430 "mode": envelope.requested_mode,
431 "ttl_ms": 30_000,
432 "action_budget": 1,
433 "app_ids": envelope.target.as_ref().map(|target| vec![target.app_id.clone()]),
434 "window_ids": envelope.target.as_ref().and_then(|target| target.window_id.clone()).map(|id| vec![id]),
435 }))?,
436 )
437 .await?,
438 );
439 let lease: ControlLease =
440 serde_json::from_value(value.get("lease").cloned().unwrap_or(value))?;
441 validate_lease(&lease, envelope)?;
444 Ok(lease)
445 }
446
447 async fn reserve_target(
448 &self,
449 envelope: &ActionEnvelope,
450 ) -> Result<Option<TargetReservation>, ComputerUseError> {
451 let Some(target) = envelope.target.as_ref() else {
452 return Ok(None);
453 };
454 let value = output(
455 self.call(
456 "reserve_target",
457 object(json!({
458 "session_id": envelope.session_id,
459 "intent_id": envelope.action_id,
460 "execution_group_id": envelope.execution_group_id,
461 "agent_id": envelope.agent_id,
462 "app_id": target.app_id,
463 "window_id": target.window_id,
464 "ttl_ms": 30_000,
465 }))?,
466 )
467 .await?,
468 );
469 let reservation: TargetReservation =
470 serde_json::from_value(value.get("reservation").cloned().unwrap_or(value))?;
471 validate_reservation(&reservation, envelope)?;
472 Ok(Some(reservation))
473 }
474
475 async fn release_target(
476 &self,
477 reservation: &TargetReservation,
478 ) -> Result<(), ComputerUseError> {
479 self.call(
480 "release_target_reservation",
481 object(json!({
482 "session_id": reservation.session_id,
483 "reservation_id": reservation.reservation_id,
484 }))?,
485 )
486 .await?;
487 Ok(())
488 }
489
490 async fn execute_action(
491 &self,
492 envelope: &ActionEnvelope,
493 lease: &ControlLease,
494 approval_grant_id: Option<&str>,
495 ) -> Result<ExecutionReceipt, ComputerUseError> {
496 validate_envelope_freshness(envelope)?;
497 validate_lease(lease, envelope)?;
498 let proposed =
499 self.proposed.lock().await.get(&envelope.action_id).cloned().ok_or_else(|| {
500 ComputerUseError::Runtime("missing exact proposed action for execution".into())
501 })?;
502 if proposed.preview.envelope != *envelope {
503 return Err(ComputerUseError::IdentityMismatch(format!(
504 "action envelope {} changed after preview; exact preview binding is required",
505 envelope.action_id
506 )));
507 }
508 let mut args = proposed.arguments;
509 args.insert("action_id".into(), json!(envelope.action_id));
510 args.insert("lease_id".into(), json!(lease.lease_id));
511 if let Some(grant) = approval_grant_id {
512 args.insert("approval_grant_id".into(), json!(grant));
513 }
514 let value = output(self.call("execute_action", args).await?);
515 let receipt: ExecutionReceipt =
516 serde_json::from_value(value.get("receipt").cloned().unwrap_or(value))?;
517 tracing::info!(
518 runtime.session_id = %receipt.session_id,
519 runtime.action_id = %receipt.action_id,
520 runtime.receipt_id = %receipt.receipt_id,
521 runtime.action_digest = %receipt.action_digest,
522 "computer-use action receipt"
523 );
524 validate_receipt(&receipt, envelope, &envelope.args_digest)?;
527 Ok(receipt)
528 }
529
530 async fn verify(
531 &self,
532 receipt: &ExecutionReceipt,
533 postcondition: Option<&crate::ActionPostcondition>,
534 ) -> Result<VerificationOutcome, ComputerUseError> {
535 if receipt.status != crate::ReceiptStatus::Committed {
539 return Ok(VerificationOutcome::Failed {
540 reason: format!("receipt status is {:?}, not committed", receipt.status),
541 });
542 }
543
544 let Some(postcondition) = postcondition else {
545 return Ok(VerificationOutcome::CommittedUnverified {
546 reason: "the action declared no postcondition, so there is nothing to verify"
547 .to_string(),
548 });
549 };
550
551 Ok(evaluate_postcondition_evidence(receipt, postcondition))
555 }
556
557 async fn pause_session(&self, session_id: &str, reason: &str) -> Result<(), ComputerUseError> {
558 self.call("pause_session", object(json!({ "session_id": session_id, "reason": reason }))?)
559 .await?;
560 Ok(())
561 }
562
563 async fn stop_session(&self, session_id: &str, reason: &str) -> Result<(), ComputerUseError> {
564 self.call("stop_session", object(json!({ "session_id": session_id, "reason": reason }))?)
565 .await?;
566 Ok(())
567 }
568
569 async fn emergency_stop(&self, reason: &str) -> Result<(), ComputerUseError> {
570 self.call("emergency_stop", object(json!({ "reason": reason }))?).await?;
571 Ok(())
572 }
573}