Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(cua mcp): act as a named agent so Spaces draw its cursor (CUA-1750) (#5290)
Francesco Bonacciafed1fcbba64
diff --git a/libs/cua/crates/cua-cli/src/mcp.rs b/libs/cua/crates/cua-cli/src/mcp.rsindex 240f2cc8d6..1e5aac9be3 100644--- a/libs/cua/crates/cua-cli/src/mcp.rs+++ b/libs/cua/crates/cua-cli/src/mcp.rs@@ -1556,12 +1556,74 @@ fn error_kind(e: &CuaError) -> &'static str {}}+/// The label an MCP client's agent shows on its Space cursor: a known+/// client's product name, else its `title`, else its `name`.+pub(crate) fn agent_label(client_info: &Value) -> String {+ let field = |k: &str| {+ client_info+ .get(k)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|s| !s.is_empty())+ };+ let name = field("name").unwrap_or("");+ let lower = name.to_ascii_lowercase();+ let known = if lower.contains("claude-code") || lower.contains("claude code") {+ Some("Claude Code")+ } else if lower.starts_with("codex") {+ Some("Codex")+ } else if lower.starts_with("cursor") {+ Some("Cursor")+ } else if lower.starts_with("gemini") {+ Some("Gemini CLI")+ } else if lower.starts_with("claude") {+ Some("Claude")+ } else {+ None+ };+ let label = known+ .or_else(|| field("title"))+ .or(Some(name).filter(|n| !n.is_empty()))+ .unwrap_or("Agent");+ label.chars().filter(|c| !c.is_control()).take(40).collect()+}++/// The principal `cua mcp` acts as: an agent named after its client, one per+/// process (`agent:<label>-<pid>`), so every agent gets its own labelled+/// cursor in the Spaces it acts in. Over the relay the host keeps only the+/// kind and this id's suffix; the identity is the signed-in account.+pub(crate) fn agent_principal(client_info: &Value) -> cua_spacesd_client::pb::Principal {+ let label = agent_label(client_info);+ let slug: String = label+ .to_ascii_lowercase()+ .chars()+ .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })+ .collect();+ let slug = slug.trim_matches('-');+ cua_spacesd_client::pb::Principal {+ id: format!(+ "agent:{}-{}",+ if slug.is_empty() { "agent" } else { slug },+ std::process::id()+ ),+ display_name: label,+ color: String::new(),+ kind: cua_spacesd_client::pb::PrincipalKind::Agent as i32,+ }+}+/// The one MCP server `cua mcp` and `cua daemon mcp` serve: the Spaces/// contract (through `cua`) plus the sandbox/computer/skills extension.+/// The process acts as an agent principal: generic until the client+/// initializes, then named after it.pub fn server(cua: Arc<Cua>, permissions: BTreeSet<String>, default_sandbox: String) -> McpServer {+ cua_spacesd_client::set_process_principal(Some(agent_principal(&Value::Null)));let spaces = cua.spaces();let allowed = permissions.clone();McpServer::remote(Arc::new(SdkTools(spaces)))+ .with_client_info_hook(Arc::new(|info: &Value| {+ cua_spacesd_client::set_process_principal(Some(agent_principal(info)));+ })).with_name("cua").with_filter(Arc::new(move |tool: &str| {allowed.contains(&format!("spaces:{tool}"))@@ -1581,6 +1643,49 @@ pub async fn serve_stdio(server: McpServer) -> Result<i32, CuaError> {mod tests {use super::*;+ #[test]+ fn agent_principal_is_named_after_the_client() {+ let p = agent_principal(&json!({"name": "claude-code", "version": "2.1"}));+ assert_eq!(p.display_name, "Claude Code");+ assert_eq!(p.kind, cua_spacesd_client::pb::PrincipalKind::Agent as i32);+ assert_eq!(p.id, format!("agent:claude-code-{}", std::process::id()));+ assert_eq!(agent_label(&json!({"name": "codex-mcp-client"})), "Codex");+ assert_eq!(+ agent_label(&json!({"name": "my-bot", "title": "My Bot"})),+ "My Bot"+ );+ assert_eq!(agent_label(&json!({"name": "my-bot"})), "my-bot");+ assert_eq!(agent_label(&Value::Null), "Agent");+ assert_eq!(+ agent_principal(&Value::Null).id,+ format!("agent:agent-{}", std::process::id())+ );+ }++ struct NoTools;+ #[async_trait::async_trait]+ impl cua_spaces::mcp::ToolBackend for NoTools {+ async fn call(&self, _: &str, _: Value) -> ToolOutcome {+ ToolOutcome::text("")+ }+ }++ #[tokio::test]+ async fn initialize_passes_client_info_to_the_hook() {+ let seen = Arc::new(Mutex::new(Value::Null));+ let sink = seen.clone();+ let server = McpServer::remote(Arc::new(NoTools)).with_client_info_hook(Arc::new(+ move |info: &Value| *sink.lock().unwrap() = info.clone(),+ ));+ let reply = server+ .handle(json!({"jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": {"protocolVersion": "2025-06-18", "clientInfo": {"name": "claude-code"}}}))+ .await+ .unwrap();+ assert!(reply.get("result").is_some(), "{reply}");+ assert_eq!(seen.lock().unwrap()["name"], "claude-code");+ }+#[test]fn every_tool_call_has_a_time_limit() {let none = json!({});diff --git a/libs/cua/crates/cua-spaces/src/mcp/mod.rs b/libs/cua/crates/cua-spaces/src/mcp/mod.rsindex 9d7e5b89eb..bf8957406c 100644--- a/libs/cua/crates/cua-spaces/src/mcp/mod.rs+++ b/libs/cua/crates/cua-spaces/src/mcp/mod.rs@@ -167,8 +167,13 @@ pub struct McpServer {/// keeps the tool fail-closed (it returns a consent requirement and/// delivers nothing).broker: Option<Arc<dyn crate::teleport_broker::SessionBroker>>,+ /// Called with `initialize`'s `clientInfo` (`Null` when absent).+ on_initialize: Option<ClientInfoHook>,}+/// See [`McpServer::with_client_info_hook`].+pub type ClientInfoHook = Arc<dyn Fn(&Value) + Send + Sync>;+impl std::fmt::Debug for McpServer {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {f.debug_struct("McpServer")@@ -189,6 +194,7 @@ impl McpServer {name: SERVER_NAME,instructions: INSTRUCTIONS,broker: None,+ on_initialize: None,}}@@ -201,6 +207,7 @@ impl McpServer {name: SERVER_NAME,instructions: INSTRUCTIONS,broker: None,+ on_initialize: None,}}@@ -216,6 +223,14 @@ impl McpServer {self}+ /// Runs `hook` with the client's `clientInfo` (`name`, `title`,+ /// `version`) when it initializes, so the host can act as that agent+ /// (for example label its cursor "Claude Code").+ pub fn with_client_info_hook(mut self, hook: ClientInfoHook) -> Self {+ self.on_initialize = Some(hook);+ self+ }+/// Adds non-contract tools.pub fn with_extension(mut self, extension: Arc<dyn ToolExtension>) -> Self {self.extensions.push(extension);@@ -352,6 +367,9 @@ impl McpServer {} else {SUPPORTED_PROTOCOL_VERSIONS[0]};+ if let Some(hook) = &self.on_initialize {+ hook(params.get("clientInfo").unwrap_or(&Value::Null));+ }json!({"protocolVersion": version,"capabilities": {"tools": {"listChanged": false}},diff --git a/libs/cua/crates/cua-spacesd-client/src/lib.rs b/libs/cua/crates/cua-spacesd-client/src/lib.rsindex 39c8250445..a07c2e9e56 100644--- a/libs/cua/crates/cua-spacesd-client/src/lib.rs+++ b/libs/cua/crates/cua-spacesd-client/src/lib.rs@@ -65,7 +65,7 @@ pub use process::{};pub use transport::{BearerProvider, ChannelError, ExtraHeaders, GatewayAuth, GrpcChannel, Keepalive, StaticBearer,- Transport, TransportPreference,+ Transport, TransportPreference, set_process_principal,};pub use tunnel::{ForwardOptions, ForwardStats, TUNNEL_FORWARD_FEATURE, TcpForward};diff --git a/libs/cua/crates/cua-spacesd-client/src/transport.rs b/libs/cua/crates/cua-spacesd-client/src/transport.rsindex 7c5933dd40..7af8f15620 100644--- a/libs/cua/crates/cua-spacesd-client/src/transport.rs+++ b/libs/cua/crates/cua-spacesd-client/src/transport.rs@@ -164,6 +164,30 @@ impl Default for Keepalive {}}+static PROCESS_PRINCIPAL: std::sync::RwLock<Option<HeaderValue>> = std::sync::RwLock::new(None);++/// Sets the principal every client in this process sends when its own+/// [`crate::ConnectOptions::principal`] is unset. An agent host (`cua mcp`)+/// sets an agent principal once it knows the agent's name, so the Spaces it+/// acts in draw a labelled agent cursor. Read on each request: clients made+/// before the call pick it up. `None` clears it.+pub fn set_process_principal(principal: Option<Principal>) {+ let value = principal.and_then(|p| {+ HeaderValue::from_str(+ &base64::engine::general_purpose::STANDARD_NO_PAD.encode(p.encode_to_vec()),+ )+ .ok()+ });+ *PROCESS_PRINCIPAL.write().unwrap_or_else(|e| e.into_inner()) = value;+}++fn process_principal() -> Option<HeaderValue> {+ PROCESS_PRINCIPAL+ .read()+ .unwrap_or_else(|e| e.into_inner())+ .clone()+}+/// Everything needed to build a channel.#[derive(Clone)]pub(crate) struct ChannelConfig {@@ -487,8 +511,8 @@ impl HeaderInjector {} else if let Some(auth) = &self.authorization {headers.insert(AUTHORIZATION, auth.clone());}- if let Some(p) = &self.principal {- headers.insert(metadata::PRINCIPAL_BIN, p.clone());+ if let Some(p) = self.principal.clone().or_else(process_principal) {+ headers.insert(metadata::PRINCIPAL_BIN, p);}for (name, value) in &self.extra {headers.insert(name.clone(), value.clone());@@ -607,4 +631,43 @@ mod extra_header_tests {plain.apply(&mut req).await.unwrap();assert!(!req.headers().contains_key("x-cua-device-session"));}++ /// The process principal fills in for clients without their own, is+ /// read per request, and never overrides an explicit one.+ #[tokio::test]+ async fn process_principal_is_the_fallback() {+ let decode = |req: &Request<()>| {+ let raw = req.headers().get(metadata::PRINCIPAL_BIN)?.to_str().ok()?;+ let bytes = base64::engine::general_purpose::STANDARD_NO_PAD+ .decode(raw)+ .ok()?;+ Principal::decode(&bytes[..]).ok()+ };+ let agent = Principal {+ id: "agent:claude-code".into(),+ display_name: "Claude Code".into(),+ kind: cua_proto::env::v1::PrincipalKind::Agent as i32,+ ..Principal::default()+ };+ let plain = HeaderInjector::new(&config(Arc::new(StaticBearer("a".into())))).unwrap();+ let mut explicit_cfg = config(Arc::new(StaticBearer("a".into())));+ explicit_cfg.principal = Some(Principal {+ id: "ada".into(),+ ..Principal::default()+ });+ let explicit = HeaderInjector::new(&explicit_cfg).unwrap();++ set_process_principal(Some(agent.clone()));+ let mut req = Request::new(());+ plain.apply(&mut req).await.unwrap();+ assert_eq!(decode(&req), Some(agent));+ let mut req = Request::new(());+ explicit.apply(&mut req).await.unwrap();+ assert_eq!(decode(&req).unwrap().id, "ada");++ set_process_principal(None);+ let mut req = Request::new(());+ plain.apply(&mut req).await.unwrap();+ assert!(decode(&req).is_none());+ }}