1use std::collections::HashSet;
4use std::sync::Arc;
5
6use adk_core::{
7 ActuationOutput, AdkError, ComputerAction, ComputerActionKind, ComputerActuator, ErrorCategory,
8 ErrorComponent, MouseButton, Result, ScreenPoint, Screenshot, ScrollDirection, Toolset,
9};
10use adk_tool::{McpToolset, SimpleToolContext};
11use async_trait::async_trait;
12use rmcp::{RoleClient, service::Service};
13use serde_json::{Value, json};
14use tokio::sync::RwLock;
15use tracing::Instrument;
16
17pub const DEFAULT_SCREENSHOT_WIDTH: u32 = 1280;
19
20const MAX_HOLD_SECONDS: f64 = 10.0;
22
23#[derive(Debug, Clone, Copy, PartialEq)]
25struct Mapping {
26 origin_x: f64,
27 origin_y: f64,
28 scale_x: f64,
29 scale_y: f64,
30}
31
32impl Mapping {
33 fn to_screen(self, point: ScreenPoint) -> [f64; 2] {
34 [
35 self.origin_x + point.x as f64 * self.scale_x,
36 self.origin_y + point.y as f64 * self.scale_y,
37 ]
38 }
39
40 fn to_image(self, [x, y]: [f64; 2]) -> ScreenPoint {
41 ScreenPoint::new(
42 ((x - self.origin_x) / self.scale_x).round() as i64,
43 ((y - self.origin_y) / self.scale_y).round() as i64,
44 )
45 }
46
47 fn parse(text: &str) -> Option<Self> {
50 let axis = |name: &str| -> Option<(f64, f64)> {
51 let prefix = format!("screen_{name} = ");
52 let rest = text.lines().find_map(|line| line.trim().strip_prefix(prefix.as_str()))?;
53 let (origin, rest) = match rest.split_once(" + ") {
54 Some((origin, rest)) => (origin.trim().parse::<f64>().ok()?, rest),
55 None => (0.0, rest),
56 };
57 let scale = rest
58 .trim()
59 .strip_prefix(format!("image_{name} * ").as_str())?
60 .parse::<f64>()
61 .ok()?;
62 (origin.is_finite() && scale.is_finite() && scale > 0.0).then_some((origin, scale))
63 };
64 let (origin_x, scale_x) = axis("x")?;
65 let (origin_y, scale_y) = axis("y")?;
66 Some(Self { origin_x, origin_y, scale_x, scale_y })
67 }
68}
69
70pub struct McpComputerActuatorBuilder<S = ()>
72where
73 S: Service<RoleClient> + Send + Sync + 'static,
74{
75 toolset: Arc<McpToolset<S>>,
76 screenshot_width: u32,
77 display_id: Option<i64>,
78}
79
80impl<S> McpComputerActuatorBuilder<S>
81where
82 S: Service<RoleClient> + Send + Sync + 'static,
83{
84 pub fn screenshot_width(mut self, width: u32) -> Self {
87 self.screenshot_width = width.max(1);
88 self
89 }
90
91 pub fn display_id(mut self, display_id: i64) -> Self {
94 self.display_id = Some(display_id);
95 self
96 }
97
98 pub async fn connect(self) -> Result<McpComputerActuator<S>> {
106 let tools = self
107 .toolset
108 .tools(Arc::new(SimpleToolContext::new("computer-use-actuator")))
109 .await?
110 .iter()
111 .map(|tool| tool.name().to_string())
112 .collect::<HashSet<_>>();
113 if !tools.contains("screenshot") {
114 return Err(AdkError::new(
115 ErrorComponent::Tool,
116 ErrorCategory::Unsupported,
117 "computer_use.mcp.no_screenshot",
118 "the MCP server lists no `screenshot` tool; connect McpComputerActuator to a \
119 computer-use-mcp server, whose every profile lists it",
120 ));
121 }
122 let actuator = McpComputerActuator {
123 toolset: self.toolset,
124 tools,
125 screenshot_width: self.screenshot_width,
126 display_id: self.display_id,
127 display: (0, 0),
128 mapping: RwLock::new(Mapping {
129 origin_x: 0.0,
130 origin_y: 0.0,
131 scale_x: 1.0,
132 scale_y: 1.0,
133 }),
134 };
135 let shot = actuator.screenshot().await?;
136 Ok(McpComputerActuator { display: (shot.width, shot.height), ..actuator })
137 }
138}
139
140pub struct McpComputerActuator<S = ()>
170where
171 S: Service<RoleClient> + Send + Sync + 'static,
172{
173 toolset: Arc<McpToolset<S>>,
174 tools: HashSet<String>,
175 screenshot_width: u32,
176 display_id: Option<i64>,
177 display: (u32, u32),
178 mapping: RwLock<Mapping>,
179}
180
181impl<S> McpComputerActuator<S>
182where
183 S: Service<RoleClient> + Send + Sync + 'static,
184{
185 pub fn builder(toolset: Arc<McpToolset<S>>) -> McpComputerActuatorBuilder<S> {
187 McpComputerActuatorBuilder {
188 toolset,
189 screenshot_width: DEFAULT_SCREENSHOT_WIDTH,
190 display_id: None,
191 }
192 }
193
194 async fn call(&self, tool: &str, arguments: Value) -> Result<Value> {
196 let Value::Object(arguments) = arguments else {
197 return Err(invalid(format!("arguments for `{tool}` must be a JSON object")));
198 };
199 let value = self
200 .toolset
201 .call_tool_value(tool, arguments)
202 .instrument(tracing::info_span!("computer_use.mcp_actuator", mcp.tool = tool))
203 .await?;
204 match value.get("error") {
205 Some(error) => Err(failed(tool, error.as_str().unwrap_or(&error.to_string()))),
206 None => Ok(value),
207 }
208 }
209
210 async fn screenshot(&self) -> Result<Screenshot> {
211 let mut arguments = json!({
212 "full_screen": true,
213 "width": self.screenshot_width,
214 "quality": 0,
215 "resend": true,
217 });
218 if let Some(display_id) = self.display_id {
219 arguments["display_id"] = json!(display_id);
220 }
221 let value = self.call("screenshot", arguments).await?;
222 let image = value
223 .get("inline_data")
224 .and_then(Value::as_array)
225 .and_then(|parts| {
226 parts.iter().find(|part| {
227 part.get("mime_type")
228 .and_then(Value::as_str)
229 .is_some_and(|mime| mime.starts_with("image/"))
230 })
231 })
232 .ok_or_else(|| failed("screenshot", "the reply carried no image"))?;
233 let data = serde_json::from_value::<Vec<u8>>(image["data"].clone()).map_err(|error| {
234 failed("screenshot", format!("the image bytes are invalid: {error}"))
235 })?;
236 let shot = Screenshot::png(data).ok_or_else(|| {
237 failed("screenshot", "the image is not a PNG; quality 0 asks for one")
238 })?;
239 let text = value.pointer("/response/output").and_then(Value::as_str).unwrap_or_default();
240 let mapping = Mapping::parse(text).ok_or_else(|| {
241 failed(
242 "screenshot",
243 "the reply states no `screen_x = ... image_x * ...` mapping; computer-use-mcp \
244 7.4 and later state one",
245 )
246 })?;
247 *self.mapping.write().await = mapping;
248 Ok(shot)
249 }
250
251 async fn cursor(&self) -> Result<[f64; 2]> {
253 let value = self.call("cursor_position", json!({})).await?;
254 let text = value.get("output").and_then(Value::as_str).unwrap_or_default();
255 text.trim()
256 .strip_prefix('(')
257 .and_then(|rest| rest.strip_suffix(')'))
258 .and_then(|pair| pair.split_once(','))
259 .and_then(|(x, y)| Some([x.trim().parse().ok()?, y.trim().parse().ok()?]))
260 .ok_or_else(|| failed("cursor_position", format!("unreadable position {text:?}")))
261 }
262
263 async fn screen_point(&self, at: Option<ScreenPoint>) -> Result<[f64; 2]> {
265 match at {
266 Some(point) => Ok(self.mapping.read().await.to_screen(point)),
267 None if self.tools.contains("cursor_position") => self.cursor().await,
268 None => Err(unsupported("acting at the cursor needs the `cursor_position` tool")),
269 }
270 }
271
272 async fn act(&self, tool: &str, arguments: Value) -> Result<ActuationOutput> {
273 self.call(tool, arguments).await.map(|_| ActuationOutput::Done)
274 }
275}
276
277#[async_trait]
278impl<S> ComputerActuator for McpComputerActuator<S>
279where
280 S: Service<RoleClient> + Send + Sync + 'static,
281{
282 fn display_size(&self) -> Option<(u32, u32)> {
283 Some(self.display)
284 }
285
286 fn supports(&self, kind: ComputerActionKind) -> bool {
287 let listed = |tool: &str| self.tools.contains(tool);
288 match kind {
289 ComputerActionKind::Screenshot => true,
290 ComputerActionKind::Click => listed("click"),
291 ComputerActionKind::Drag => listed("mouse_drag") || listed("left_click_drag"),
292 ComputerActionKind::MoveTo => listed("mouse_move"),
293 ComputerActionKind::MouseDown => listed("left_mouse_down") && listed("cursor_position"),
294 ComputerActionKind::MouseUp => listed("left_mouse_up") && listed("cursor_position"),
295 ComputerActionKind::CursorPosition => listed("cursor_position"),
296 ComputerActionKind::Scroll => listed("scroll"),
297 ComputerActionKind::Type => listed("type"),
298 ComputerActionKind::Key => listed("key"),
299 ComputerActionKind::HoldKey => listed("hold_key"),
300 ComputerActionKind::Zoom | ComputerActionKind::Wait => false,
302 _ => false,
303 }
304 }
305
306 async fn perform(&self, action: ComputerAction) -> Result<ActuationOutput> {
307 if !self.supports(action.kind()) {
308 return Err(unsupported(format!(
309 "the server lists no tool for {:?} actions",
310 action.kind()
311 )));
312 }
313 match action {
314 ComputerAction::Screenshot => self.screenshot().await.map(ActuationOutput::Image),
315 ComputerAction::Click { button, count, at, modifiers } => {
316 let mut arguments = json!({
317 "coordinate": self.screen_point(at).await?,
318 "button": button_name(button),
319 "count": count,
320 });
321 with_modifiers(&mut arguments, &modifiers)?;
322 self.act("click", arguments).await
323 }
324 ComputerAction::Drag { from, to, modifiers } => {
325 let mapping = *self.mapping.read().await;
326 let (from, to) = (mapping.to_screen(from), mapping.to_screen(to));
327 if self.tools.contains("mouse_drag") {
328 let mut arguments = json!({ "path": [from, to], "button": "left" });
329 with_modifiers(&mut arguments, &modifiers)?;
330 self.act("mouse_drag", arguments).await
331 } else if modifiers.is_empty() {
332 self.act(
333 "left_click_drag",
334 json!({ "start_coordinate": from, "coordinate": to }),
335 )
336 .await
337 } else {
338 Err(unsupported(
339 "a drag with modifiers needs the `mouse_drag` tool (the `ax` profile)",
340 ))
341 }
342 }
343 ComputerAction::MoveTo { at } => {
344 let coordinate = self.mapping.read().await.to_screen(at);
345 self.act("mouse_move", json!({ "coordinate": coordinate })).await
346 }
347 ComputerAction::MouseDown => {
348 let coordinate = self.cursor().await?;
349 self.act("left_mouse_down", json!({ "coordinate": coordinate })).await
350 }
351 ComputerAction::MouseUp => {
352 let coordinate = self.cursor().await?;
353 self.act("left_mouse_up", json!({ "coordinate": coordinate })).await
354 }
355 ComputerAction::CursorPosition => {
356 let position = self.cursor().await?;
357 Ok(ActuationOutput::Cursor(self.mapping.read().await.to_image(position)))
358 }
359 ComputerAction::Scroll { at, direction, amount, modifiers } => {
360 let mut arguments = json!({
361 "coordinate": self.screen_point(at).await?,
362 "direction": direction_name(direction),
363 "amount": amount,
364 });
365 with_modifiers(&mut arguments, &modifiers)?;
366 self.act("scroll", arguments).await
367 }
368 ComputerAction::Type { text } => self.act("type", json!({ "text": text })).await,
369 ComputerAction::Key { keys, repeat } => {
370 let mut arguments = json!({ "text": keys });
371 if repeat > 1 {
372 arguments["repeat"] = json!(repeat);
373 }
374 self.act("key", arguments).await
375 }
376 ComputerAction::HoldKey { keys, duration } => {
377 let seconds = duration.as_secs_f64();
378 if !(seconds > 0.0 && seconds <= MAX_HOLD_SECONDS) {
379 return Err(invalid(format!(
380 "hold_key lasts {seconds} s; computer-use-mcp holds keys for more than 0 \
381 and at most {MAX_HOLD_SECONDS} s"
382 )));
383 }
384 let keys: Vec<&str> = keys.split('+').map(str::trim).collect();
385 self.act("hold_key", json!({ "keys": keys, "duration": seconds })).await
386 }
387 other => Err(unsupported(format!("{:?} actions are not offered", other.kind()))),
388 }
389 }
390}
391
392fn button_name(button: MouseButton) -> &'static str {
393 match button {
394 MouseButton::Left => "left",
395 MouseButton::Right => "right",
396 MouseButton::Middle => "middle",
397 }
398}
399
400fn direction_name(direction: ScrollDirection) -> &'static str {
401 match direction {
402 ScrollDirection::Up => "up",
403 ScrollDirection::Down => "down",
404 ScrollDirection::Left => "left",
405 ScrollDirection::Right => "right",
406 }
407}
408
409fn with_modifiers(arguments: &mut Value, modifiers: &[String]) -> Result<()> {
411 if modifiers.is_empty() {
412 return Ok(());
413 }
414 let names = modifiers
415 .iter()
416 .map(|modifier| match modifier.to_ascii_lowercase().as_str() {
417 "shift" => Ok("shift"),
418 "ctrl" | "control" => Ok("ctrl"),
419 "alt" | "option" => Ok("alt"),
420 "super" | "cmd" | "command" | "meta" | "win" => Ok("cmd"),
421 other => Err(invalid(format!(
422 "unknown modifier {other:?}; expected shift, ctrl, alt or super"
423 ))),
424 })
425 .collect::<Result<Vec<_>>>()?;
426 arguments["modifiers"] = json!(names);
427 Ok(())
428}
429
430fn failed(tool: &str, detail: impl std::fmt::Display) -> AdkError {
431 AdkError::new(
432 ErrorComponent::Tool,
433 ErrorCategory::InvalidInput,
434 "computer_use.mcp.action_failed",
435 format!("computer-use-mcp `{tool}` failed: {detail}"),
436 )
437}
438
439fn invalid(message: impl Into<String>) -> AdkError {
440 AdkError::new(
441 ErrorComponent::Tool,
442 ErrorCategory::InvalidInput,
443 "computer_use.mcp.invalid_action",
444 message,
445 )
446}
447
448fn unsupported(message: impl Into<String>) -> AdkError {
449 AdkError::new(
450 ErrorComponent::Tool,
451 ErrorCategory::Unsupported,
452 "computer_use.mcp.unsupported_action",
453 message,
454 )
455}
456
457#[cfg(test)]
458mod tests {
459 use super::*;
460
461 #[test]
462 fn reads_both_mapping_forms() {
463 let display = "1280x800 | screen: display 1 at 0,0 sized 2560x1600 (ScreenCaptureKit)\n\
464 screen_x = 0 + image_x * 2.0000\n\
465 screen_y = 0 + image_y * 2.0000\n\
466 a display capture scales uniformly, so this mapping is exact.";
467 assert_eq!(
468 Mapping::parse(display),
469 Some(Mapping { origin_x: 0.0, origin_y: 0.0, scale_x: 2.0, scale_y: 2.0 })
470 );
471 let offset = "screen_x = -1512 + image_x * 1.1813\nscreen_y = 25 + image_y * 1.1813";
472 assert_eq!(
473 Mapping::parse(offset),
474 Some(Mapping { origin_x: -1512.0, origin_y: 25.0, scale_x: 1.1813, scale_y: 1.1813 })
475 );
476 let bare = "screen_x = image_x * 1.5000\nscreen_y = image_y * 1.5000";
477 assert_eq!(
478 Mapping::parse(bare),
479 Some(Mapping { origin_x: 0.0, origin_y: 0.0, scale_x: 1.5, scale_y: 1.5 })
480 );
481 assert_eq!(Mapping::parse("screen_x = 0 + image_x * 0\nscreen_y = 0 + image_y * 1"), None);
482 assert_eq!(Mapping::parse("1280x800"), None);
483 }
484
485 #[test]
486 fn maps_points_both_ways() {
487 let mapping = Mapping { origin_x: -1512.0, origin_y: 25.0, scale_x: 2.0, scale_y: 2.0 };
488 assert_eq!(mapping.to_screen(ScreenPoint::new(100, 50)), [-1312.0, 125.0]);
489 assert_eq!(mapping.to_image([-1312.0, 125.0]), ScreenPoint::new(100, 50));
490 }
491}