Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(cua-driver): add stable health_report MCP tool for end-to-end driver diagnostics

Francesco Bonaccibe761fac796d
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/health_report.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/health_report.rs
new file mode 100644
index 0000000000..84dd090bdd
--- /dev/null
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/health_report.rs
@@ -0,0 +1,746 @@
+//! `health_report` — single-call end-to-end driver diagnostics.
+//!
+//! The point of this tool is to let downstream consumers (Hermes Agent
+//! and similar — see NousResearch/hermes-agent#47065) ship one stable
+//! diagnostic call and never have to know cua-driver internals: specific
+//! MCP tool names, TCC field names, bundle IDs, per-platform check
+//! matrix. cua-driver owns the health model entirely; consumers stay
+//! thin and the driver evolves freely.
+//!
+//! ## Stability
+//!
+//! Output shape is the stable contract — documented inline in the
+//! tool's `description`. `schema_version: "1"` is the commitment;
+//! future breaking changes go to `"2"`. Adding new `name` values to
+//! `checks[]` under the same `schema_version` is non-breaking;
+//! consumers must tolerate unknown check names.
+//!
+//! ## Architecture
+//!
+//! This module ports the Swift `HealthReportTool` (closed PR #1905) to
+//! the canonical Rust workspace. The check matrix differs per platform,
+//! so the per-platform crates (`platform-macos`, `platform-windows`,
+//! `platform-linux`) supply a [`HealthCheckProvider`] and a list of
+//! check names; this module owns the cross-platform skeleton:
+//! schema shape, status rollup, include/skip filtering, JSON-RPC tool
+//! plumbing, and the text summary.
+
+use async_trait::async_trait;
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::collections::BTreeSet;
+use std::sync::Arc;
+
+use crate::{
+ protocol::ToolResult,
+ tool::{Tool, ToolDef},
+};
+
+// ── Canonical check names ────────────────────────────────────────────────────
+//
+// Constants live here (not on each platform) so the wire format stays
+// consistent and downstream consumers can hard-code these strings
+// against the documented `schema_version=1` contract.
+
+pub const NAME_BINARY_VERSION: &str = "binary_version";
+pub const NAME_PLATFORM_SUPPORTED: &str = "platform_supported";
+pub const NAME_SESSION_ACTIVE: &str = "session_active";
+pub const NAME_BUNDLE_IDENTITY: &str = "bundle_identity";
+pub const NAME_TCC_ACCESSIBILITY: &str = "tcc_accessibility";
+pub const NAME_TCC_SCREEN_RECORDING: &str = "tcc_screen_recording";
+pub const NAME_AX_CAPABILITY: &str = "ax_capability";
+pub const NAME_SCREEN_CAPTURE_CAPABILITY: &str = "screen_capture_capability";
+
+/// Checks whose failure marks the whole report as `failed` (vs
+/// `degraded`). Binary, platform, and the MCP session itself are
+/// non-negotiable; everything else is degraded.
+///
+/// This list is fixed across platforms — a "core" check that doesn't
+/// apply on a platform simply isn't present in that platform's `names`
+/// vector, so the overall rollup ignores it.
+pub fn core_check_names() -> &'static [&'static str] {
+ &[NAME_BINARY_VERSION, NAME_PLATFORM_SUPPORTED, NAME_SESSION_ACTIVE]
+}
+
+// ── Output model ─────────────────────────────────────────────────────────────
+
+/// Per-check status. Serialized lowercase to match the documented contract.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum CheckStatus {
+ Pass,
+ Fail,
+ Skip,
+}
+
+/// Aggregate health verdict. Lowercase wire format.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+pub enum Overall {
+ Ok,
+ Degraded,
+ Failed,
+}
+
+/// Per-check structured data. Kept as a fixed set of optional fields —
+/// not a free-form map — so the JSON shape is statically known. Adding
+/// new optional fields here is non-breaking under `schema_version="1"`;
+/// removing any documented field would break consumers and gates a
+/// version bump.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+pub struct CheckData {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub bundle_identifier: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub executable_path: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub os_version: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub architecture: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub display_count: Option<u32>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub error_detail: Option<String>,
+}
+
+impl CheckData {
+ /// True if no field is set. Used by check authors so an empty
+ /// `data` block is omitted from the wire format rather than
+ /// serialized as `{}`.
+ pub fn is_empty(&self) -> bool {
+ self.bundle_identifier.is_none()
+ && self.executable_path.is_none()
+ && self.os_version.is_none()
+ && self.architecture.is_none()
+ && self.display_count.is_none()
+ && self.error_detail.is_none()
+ }
+}
+
+/// One entry in `report.checks[]`.
+///
+/// `hint` is required on `Fail` (the documented "fail entries carry a
+/// remediation step" contract), optional on `Pass`/`Skip`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CheckEntry {
+ pub name: String,
+ pub status: CheckStatus,
+ pub message: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub hint: Option<String>,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub data: Option<CheckData>,
+}
+
+impl CheckEntry {
+ /// Build a `Pass` entry with no hint and no structured data.
+ pub fn pass(name: impl Into<String>, message: impl Into<String>) -> Self {
+ Self {
+ name: name.into(),
+ status: CheckStatus::Pass,
+ message: message.into(),
+ hint: None,
+ data: None,
+ }
+ }
+
+ /// Build a `Fail` entry. `hint` is required on the contract level —
+ /// taking it as a non-`Option` argument makes the requirement
+ /// explicit at the call site rather than catching it in a test.
+ pub fn fail(
+ name: impl Into<String>,
+ message: impl Into<String>,
+ hint: impl Into<String>,
+ ) -> Self {
+ Self {
+ name: name.into(),
+ status: CheckStatus::Fail,
+ message: message.into(),
+ hint: Some(hint.into()),
+ data: None,
+ }
+ }
+
+ /// Build a `Skip` entry — used when a check is filtered out by the
+ /// caller's `include`/`skip` or doesn't apply to this platform.
+ pub fn skip(name: impl Into<String>, message: impl Into<String>) -> Self {
+ Self {
+ name: name.into(),
+ status: CheckStatus::Skip,
+ message: message.into(),
+ hint: None,
+ data: None,
+ }
+ }
+
+ /// Attach structured `data`. Empty payloads are dropped so the wire
+ /// format stays clean.
+ pub fn with_data(mut self, data: CheckData) -> Self {
+ if !data.is_empty() {
+ self.data = Some(data);
+ }
+ self
+ }
+}
+
+/// Top-level `health_report` payload.
+///
+/// JSON shape is the consumer-facing contract documented in the tool's
+/// description. Field-rename in serde keeps the snake_case wire format
+/// regardless of Rust naming.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct Report {
+ pub schema_version: String,
+ pub platform: String,
+ pub driver_version: String,
+ pub overall: Overall,
+ pub checks: Vec<CheckEntry>,
+}
+
+// ── Provider trait ───────────────────────────────────────────────────────────
+
+/// Per-platform contract: list the canonical check names this platform
+/// supports, and run a single check by name.
+///
+/// Implementations live in each `platform-*` crate so the
+/// platform-specific TCC / UIA / AT-SPI / SCK plumbing stays out of the
+/// core. Implementations must return entries for every name in their
+/// `check_names()`; the dispatcher does not synthesize results.
+#[async_trait]
+pub trait HealthCheckProvider: Send + Sync {
+ /// The platform tag for the `Report.platform` field — `"darwin"`,
+ /// `"win32"`, or `"linux"`. The documented stable contract.
+ fn platform(&self) -> &'static str;
+
+ /// Canonical check names, in the run order the consumer should see
+ /// reflected back in `report.checks[]`.
+ fn check_names(&self) -> &'static [&'static str];
+
+ /// Run a single check by name. The dispatcher only forwards names
+ /// from `check_names()`; provider authors do not need to handle
+ /// unknown names defensively.
+ async fn run_check(&self, name: &str) -> CheckEntry;
+}
+
+// ── Filter / rollup logic ────────────────────────────────────────────────────
+
+/// Decide which checks the call should actually run.
+///
+/// - `include` wins if non-empty: run exactly the canonical names
+/// that intersect `include`. Unknown names in `include` are
+/// silently ignored (forward-compat — a consumer may know a name
+/// from a newer driver build).
+/// - Otherwise `skip` filters out from the full canonical list.
+/// - Empty filters → run everything.
+pub fn select_checks(
+ all_checks: &[&str],
+ include: &BTreeSet<String>,
+ skip: &BTreeSet<String>,
+) -> BTreeSet<String> {
+ let all: BTreeSet<String> = all_checks.iter().map(|s| (*s).to_owned()).collect();
+ if !include.is_empty() {
+ return all.intersection(include).cloned().collect();
+ }
+ if !skip.is_empty() {
+ return all.difference(skip).cloned().collect();
+ }
+ all
+}
+
+/// Roll per-check statuses up into the documented overall verdict.
+pub fn compute_overall(checks: &[CheckEntry]) -> Overall {
+ let core: BTreeSet<&str> = core_check_names().iter().copied().collect();
+ let mut any_fail = false;
+ let mut any_core_fail = false;
+ for entry in checks {
+ if entry.status != CheckStatus::Fail {
+ continue;
+ }
+ any_fail = true;
+ if core.contains(entry.name.as_str()) {
+ any_core_fail = true;
+ }
+ }
+ if any_core_fail {
+ return Overall::Failed;
+ }
+ if any_fail {
+ return Overall::Degraded;
+ }
+ Overall::Ok
+}
+
+/// Pull a `BTreeSet<String>` out of a JSON value, treating non-array
+/// inputs and non-string items as empty. Used to parse the optional
+/// `include` / `skip` arguments.
+pub fn parse_string_set(v: Option<&Value>) -> BTreeSet<String> {
+ let mut out = BTreeSet::new();
+ let Some(Value::Array(items)) = v else {
+ return out;
+ };
+ for item in items {
+ if let Some(s) = item.as_str() {
+ out.insert(s.to_owned());
+ }
+ }
+ out
+}
+
+// ── Text summary ─────────────────────────────────────────────────────────────
+
+/// Compact human-readable summary of a report, for clients squinting at
+/// MCP traces. `structuredContent` is the authoritative wire format;
+/// this text is decorative.
+pub fn text_summary(report: &Report) -> String {
+ let overall_icon = match report.overall {
+ Overall::Ok => "✅",
+ Overall::Degraded => "⚠️",
+ Overall::Failed => "❌",
+ };
+ let overall_word = match report.overall {
+ Overall::Ok => "ok",
+ Overall::Degraded => "degraded",
+ Overall::Failed => "failed",
+ };
+ let mut lines = vec![format!(
+ "{overall_icon} cua-driver {} on {} — {overall_word}",
+ report.driver_version, report.platform
+ )];
+ for entry in &report.checks {
+ let icon = match entry.status {
+ CheckStatus::Pass => "✅",
+ CheckStatus::Fail => "❌",
+ CheckStatus::Skip => "⏭",
+ };
+ lines.push(format!(" {icon} {}: {}", entry.name, entry.message));
+ }
+ lines.join("\n")
+}
+
+// ── The MCP tool ─────────────────────────────────────────────────────────────
+
+/// Cross-platform `health_report` MCP tool. The platform-specific bits
+/// (which checks to run, how to run each one) are supplied by the
+/// `HealthCheckProvider` passed at construction time.
+pub struct HealthReportTool {
+ provider: Arc<dyn HealthCheckProvider>,
+}
+
+impl HealthReportTool {
+ pub fn new(provider: Arc<dyn HealthCheckProvider>) -> Self {
+ Self { provider }
+ }
+}
+
+static DEF: std::sync::OnceLock<ToolDef> = std::sync::OnceLock::new();
+
+fn def() -> &'static ToolDef {
+ DEF.get_or_init(|| ToolDef {
+ name: "health_report".into(),
+ // The description is part of the public contract — downstream
+ // consumers (Hermes Agent / `hermes computer-use doctor`)
+ // depend on it spelling out `schema_version="1"` and the per-
+ // platform check matrix. A test pins this commitment.
+ description: r#"Single-call end-to-end driver diagnostics. Designed to let downstream consumers (Hermes Agent and similar) ship one stable call instead of stitching together check_permissions, doctor, version, bundle attribution, and a screenshot probe. cua-driver owns the health model; consumers stay thin.
+
+Input — all optional:
+ {
+ "include": ["<check_name>", ...], // run only these
+ "skip": ["<check_name>", ...] // skip these
+ }
+If both are given, `include` wins.
+
+Canonical check names:
+ macOS : binary_version, platform_supported, session_active,
+ bundle_identity, tcc_accessibility, tcc_screen_recording,
+ ax_capability, screen_capture_capability
+ Windows: binary_version, platform_supported, session_active,
+ ax_capability (via UIA), screen_capture_capability (via DXGI)
+ Linux : binary_version, platform_supported, session_active,
+ ax_capability (via AT-SPI), screen_capture_capability (via X11)
+
+Output — stable contract, schema_version="1":
+ {
+ "schema_version": "1",
+ "platform": "darwin" | "win32" | "linux",
+ "driver_version": "<semver>",
+ "overall": "ok" | "degraded" | "failed",
+ "checks": [
+ {
+ "name": "<one of the canonical names above>",
+ "status": "pass" | "fail" | "skip",
+ "message": "<one-line summary, always present>",
+ "hint": "<remediation step, present when status=fail>",
+ "data": { /* check-specific structured fields */ }
+ },
+ ...
+ ]
+ }
+
+`overall` rules:
+ - `ok` — every non-skipped check passes
+ - `degraded` — at least one non-core check fails (binary is still usable)
+ - `failed` — any core check fails (binary_version, platform_supported, session_active)
+
+Stability: schema_version="1" is the contract. Future breaking changes will be `"2"`. Adding new check names under the same schema_version is non-breaking; consumers must tolerate unknown check names. Downstream consumer: NousResearch/hermes-agent#47065."#.into(),
+ input_schema: json!({
+ "type": "object",
+ "properties": {
+ "include": {
+ "type": "array",
+ "items": { "type": "string" },
+ "description":
+ "Only run these checks (canonical names). Wins over `skip`."
+ },
+ "skip": {
+ "type": "array",
+ "items": { "type": "string" },
+ "description":
+ "Skip these checks (canonical names). Ignored when `include` is set."
+ }
+ },
+ "additionalProperties": false,
+ }),
+ // This is a diagnostic probe; it never mutates driver state.
+ read_only: true,
+ destructive: false,
+ idempotent: true,
+ open_world: false,
+ })
+}
+
+#[async_trait]
+impl Tool for HealthReportTool {
+ fn def(&self) -> &ToolDef {
+ def()
+ }
+
+ async fn invoke(&self, args: Value) -> ToolResult {
+ let include = parse_string_set(args.get("include"));
+ let skip = parse_string_set(args.get("skip"));
+
+ let all = self.provider.check_names();
+ let to_run = select_checks(all, &include, &skip);
+
+ // Every canonical check appears in the output, even if filtered
+ // out — consumers get a complete map of what was considered.
+ let mut checks: Vec<CheckEntry> = Vec::with_capacity(all.len());
+ for name in all {
+ if !to_run.contains(*name) {
+ checks.push(CheckEntry::skip(*name, "Skipped by include/skip filter."));
+ continue;
+ }
+ checks.push(self.provider.run_check(name).await);
+ }
+
+ let report = Report {
+ schema_version: "1".to_owned(),
+ platform: self.provider.platform().to_owned(),
+ driver_version: env!("CARGO_PKG_VERSION").to_owned(),
+ overall: compute_overall(&checks),
+ checks,
+ };
+
+ let text = text_summary(&report);
+ let structured = serde_json::to_value(&report)
+ .unwrap_or_else(|_| json!({ "schema_version": "1", "error": "serialize_failed" }));
+
+ // health_report is the consumer's "what's broken?" probe — it
+ // must NEVER itself set isError, regardless of how degraded
+ // the report is, or consumers can't tell apart "tool broken"
+ // from "driver degraded".
+ ToolResult::text(text).with_structured(structured)
+ }
+}
+
+// ── Tests ────────────────────────────────────────────────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use serde_json::json;
+
+ // A platform-agnostic fixture provider used to exercise the
+ // dispatcher, filter, and rollup logic without touching any real
+ // TCC / UIA / SCK plumbing.
+ struct FixtureProvider {
+ names: &'static [&'static str],
+ platform: &'static str,
+ // Per-name override: if Some, return this entry; if None, return
+ // a vanilla Pass with the canonical name.
+ fail_names: BTreeSet<String>,
+ }
+
+ #[async_trait]
+ impl HealthCheckProvider for FixtureProvider {
+ fn platform(&self) -> &'static str {
+ self.platform
+ }
+ fn check_names(&self) -> &'static [&'static str] {
+ self.names
+ }
+ async fn run_check(&self, name: &str) -> CheckEntry {
+ if self.fail_names.contains(name) {
+ CheckEntry::fail(name, format!("{name} failed in fixture"), "remediate")
+ } else {
+ CheckEntry::pass(name, format!("{name} ok"))
+ }
+ }
+ }
+
+ fn macos_names() -> &'static [&'static str] {
+ &[
+ NAME_BINARY_VERSION,
+ NAME_PLATFORM_SUPPORTED,
+ NAME_SESSION_ACTIVE,
+ NAME_BUNDLE_IDENTITY,
+ NAME_TCC_ACCESSIBILITY,
+ NAME_TCC_SCREEN_RECORDING,
+ NAME_AX_CAPABILITY,
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+ ]
+ }
+
+ fn parse_args(v: Value) -> (BTreeSet<String>, BTreeSet<String>) {
+ (
+ parse_string_set(v.get("include")),
+ parse_string_set(v.get("skip")),
+ )
+ }
+
+ // ── select_checks ────────────────────────────────────────────────
+
+ #[test]
+ fn include_wins_over_skip() {
+ let mut include = BTreeSet::new();
+ include.insert(NAME_BINARY_VERSION.to_owned());
+ let mut skip = BTreeSet::new();
+ skip.insert(NAME_BINARY_VERSION.to_owned());
+ let chosen = select_checks(macos_names(), &include, &skip);
+ assert_eq!(
+ chosen.into_iter().collect::<Vec<_>>(),
+ vec![NAME_BINARY_VERSION.to_owned()]
+ );
+ }
+
+ #[test]
+ fn include_filters_out_unknowns_silently() {
+ let mut include = BTreeSet::new();
+ include.insert(NAME_BINARY_VERSION.to_owned());
+ include.insert("tomorrows_check_name".to_owned());
+ let chosen = select_checks(macos_names(), &include, &BTreeSet::new());
+ assert_eq!(
+ chosen.into_iter().collect::<Vec<_>>(),
+ vec![NAME_BINARY_VERSION.to_owned()]
+ );
+ }
+
+ #[test]
+ fn empty_filters_runs_everything() {
+ let chosen = select_checks(macos_names(), &BTreeSet::new(), &BTreeSet::new());
+ let expected: BTreeSet<String> = macos_names().iter().map(|s| (*s).to_owned()).collect();
+ assert_eq!(chosen, expected);
+ }
+
+ #[test]
+ fn skip_removes_named() {
+ let mut skip = BTreeSet::new();
+ skip.insert(NAME_TCC_ACCESSIBILITY.to_owned());
+ let chosen = select_checks(macos_names(), &BTreeSet::new(), &skip);
+ assert!(!chosen.contains(NAME_TCC_ACCESSIBILITY));
+ assert!(chosen.contains(NAME_BINARY_VERSION));
+ }
+
+ // ── compute_overall ──────────────────────────────────────────────
+
+ #[test]
+ fn all_pass_is_ok() {
+ let checks: Vec<_> = macos_names()
+ .iter()
+ .map(|n| CheckEntry::pass(*n, "ok"))
+ .collect();
+ assert_eq!(compute_overall(&checks), Overall::Ok);
+ }
+
+ #[test]
+ fn all_skip_is_ok() {
+ let checks: Vec<_> = macos_names()
+ .iter()
+ .map(|n| CheckEntry::skip(*n, "skipped"))
+ .collect();
+ assert_eq!(compute_overall(&checks), Overall::Ok);
+ }
+
+ #[test]
+ fn non_core_fail_is_degraded() {
+ // bundle_identity is non-core.
+ let checks: Vec<_> = macos_names()
+ .iter()
+ .map(|n| {
+ if *n == NAME_BUNDLE_IDENTITY {
+ CheckEntry::fail(*n, "no bundle", "relaunch in .app")
+ } else {
+ CheckEntry::pass(*n, "ok")
+ }
+ })
+ .collect();
+ assert_eq!(compute_overall(&checks), Overall::Degraded);
+ }
+
+ #[test]
+ fn core_fail_is_failed() {
+ let checks: Vec<_> = macos_names()
+ .iter()
+ .map(|n| {
+ if *n == NAME_BINARY_VERSION {
+ CheckEntry::fail(*n, "no version", "rebuild")
+ } else {
+ CheckEntry::pass(*n, "ok")
+ }
+ })
+ .collect();
+ assert_eq!(compute_overall(&checks), Overall::Failed);
+ }
+
+ // ── parse_string_set ─────────────────────────────────────────────
+
+ #[test]
+ fn parse_string_set_ignores_non_string_items() {
+ let v = json!(["a", 7, true, "b"]);
+ let parsed = parse_string_set(Some(&v));
+ let expected: BTreeSet<String> = ["a".to_owned(), "b".to_owned()].into_iter().collect();
+ assert_eq!(parsed, expected);
+ }
+
+ #[test]
+ fn parse_string_set_handles_nil_and_scalars() {
+ assert!(parse_string_set(None).is_empty());
+ assert!(parse_string_set(Some(&json!("x"))).is_empty());
+ assert!(parse_string_set(Some(&json!(3))).is_empty());
+ }
+
+ // ── invoke end-to-end via the fixture provider ───────────────────
+
+ #[tokio::test]
+ async fn invoke_no_args_produces_documented_schema() {
+ let provider = Arc::new(FixtureProvider {
+ names: macos_names(),
+ platform: "darwin",
+ fail_names: BTreeSet::new(),
+ });
+ let tool = HealthReportTool::new(provider);
+ let result = tool.invoke(json!({})).await;
+ assert!(
+ result.is_error.is_none(),
+ "health_report must never set isError"
+ );
+ let structured = result.structured_content.expect("structured payload");
+ // Top-level keys must match the documented schema verbatim.
+ assert_eq!(structured["schema_version"], "1");
+ assert_eq!(structured["platform"], "darwin");
+ assert!(structured["driver_version"].is_string());
+ assert!(structured["overall"].is_string());
+ let checks = structured["checks"].as_array().expect("checks array");
+ assert!(!checks.is_empty());
+ for entry in checks {
+ assert!(entry["name"].is_string());
+ assert!(entry["message"].is_string());
+ let status = entry["status"].as_str().unwrap();
+ assert!(matches!(status, "pass" | "fail" | "skip"));
+ }
+ }
+
+ #[tokio::test]
+ async fn skip_filter_marks_check_as_skip_end_to_end() {
+ let provider = Arc::new(FixtureProvider {
+ names: macos_names(),
+ platform: "darwin",
+ fail_names: BTreeSet::new(),
+ });
+ let tool = HealthReportTool::new(provider);
+ let result = tool
+ .invoke(json!({ "skip": [NAME_TCC_ACCESSIBILITY] }))
+ .await;
+ let structured = result.structured_content.expect("structured");
+ let checks = structured["checks"].as_array().unwrap();
+ let entry = checks
+ .iter()
+ .find(|c| c["name"] == NAME_TCC_ACCESSIBILITY)
+ .expect("tcc_accessibility appears even when skipped");
+ assert_eq!(entry["status"], "skip");
+ }
+
+ #[tokio::test]
+ async fn include_filter_runs_only_named_check() {
+ let provider = Arc::new(FixtureProvider {
+ names: macos_names(),
+ platform: "darwin",
+ fail_names: BTreeSet::new(),
+ });
+ let tool = HealthReportTool::new(provider);
+ let result = tool
+ .invoke(json!({ "include": [NAME_BINARY_VERSION] }))
+ .await;
+ let structured = result.structured_content.expect("structured");
+ let checks = structured["checks"].as_array().unwrap();
+ let ran: Vec<&str> = checks
+ .iter()
+ .filter(|c| c["status"] != "skip")
+ .map(|c| c["name"].as_str().unwrap())
+ .collect();
+ assert_eq!(ran, vec![NAME_BINARY_VERSION]);
+ }
+
+ #[tokio::test]
+ async fn fail_mode_does_not_set_is_error() {
+ // Every check fails — overall should be Failed but the tool
+ // result itself must NOT set isError.
+ let mut fail = BTreeSet::new();
+ for n in macos_names() {
+ fail.insert((*n).to_owned());
+ }
+ let provider = Arc::new(FixtureProvider {
+ names: macos_names(),
+ platform: "darwin",
+ fail_names: fail,
+ });
+ let tool = HealthReportTool::new(provider);
+ let result = tool.invoke(json!({})).await;
+ assert!(
+ result.is_error.is_none(),
+ "health_report must never set isError even on total failure"
+ );
+ let structured = result.structured_content.expect("structured");
+ assert_eq!(structured["overall"], "failed");
+ // Every entry must carry hint + message.
+ for entry in structured["checks"].as_array().unwrap() {
+ assert_eq!(entry["status"], "fail");
+ assert!(entry["hint"].as_str().unwrap_or("").len() > 0);
+ assert!(entry["message"].as_str().unwrap_or("").len() > 0);
+ }
+ }
+
+ // ── tool description contract ────────────────────────────────────
+
+ #[test]
+ fn description_commits_to_schema_version_1() {
+ // The PR description and downstream consumers bake
+ // `schema_version: "1"` into their expectations. A future
+ // change that drops this commitment from the schema text
+ // without bumping the version would silently break consumers
+ // — this test fails loudly the moment that drift starts.
+ let description = &def().description;
+ assert!(
+ description.contains(r#"schema_version="1""#)
+ || description.contains(r#"schema_version: "1""#),
+ "schema_version=1 must be documented in the tool description"
+ );
+ }
+
+ // Belt-and-suspenders use of `parse_args` — keeps the helper
+ // exercised in case future tests reach for it.
+ #[test]
+ fn parse_args_compiles() {
+ let _ = parse_args(json!({ "include": ["x"], "skip": ["y"] }));
+ }
+}
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
index 8790ce2d75..6e4886270c 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/lib.rs
@@ -16,6 +16,7 @@ pub mod cdp;
pub mod element_cache;
pub mod element_token;
pub mod ffmpeg_install;
+pub mod health_report;
pub mod image_utils;
pub mod page;
pub mod pip_hook;
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/health_report.rs b/libs/cua-driver/rust/crates/platform-linux/src/health_report.rs
new file mode 100644
index 0000000000..03d146de88
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-linux/src/health_report.rs
@@ -0,0 +1,245 @@
+//! Linux `health_report` provider.
+//!
+//! Implements [`cua_driver_core::health_report::HealthCheckProvider`]
+//! for Linux. Reuses the same probes the Linux `check_permissions`
+//! tool runs — X11 connectivity for AX (driven via XSendEvent +
+//! AT-SPI) and X11 again for the screen capture path.
+//!
+//! The TCC / bundle checks emit `status: "skip"` with `message: "not
+//! applicable on Linux"`; Linux has no TCC.
+
+use async_trait::async_trait;
+use cua_driver_core::health_report::{
+ CheckData, CheckEntry, HealthCheckProvider, NAME_AX_CAPABILITY, NAME_BINARY_VERSION,
+ NAME_BUNDLE_IDENTITY, NAME_PLATFORM_SUPPORTED, NAME_SCREEN_CAPTURE_CAPABILITY,
+ NAME_SESSION_ACTIVE, NAME_TCC_ACCESSIBILITY, NAME_TCC_SCREEN_RECORDING,
+};
+
+/// Linux canonical check names — same Swift-PR contract, with TCC /
+/// bundle entries surfaced as `skip("not applicable on Linux")`. The
+/// full set of entries always appears so cross-platform consumers see
+/// a complete check map.
+pub const LINUX_CHECK_NAMES: &[&str] = &[
+ NAME_BINARY_VERSION,
+ NAME_PLATFORM_SUPPORTED,
+ NAME_SESSION_ACTIVE,
+ NAME_BUNDLE_IDENTITY,
+ NAME_TCC_ACCESSIBILITY,
+ NAME_TCC_SCREEN_RECORDING,
+ NAME_AX_CAPABILITY,
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+];
+
+pub struct LinuxHealthProvider;
+
+#[async_trait]
+impl HealthCheckProvider for LinuxHealthProvider {
+ fn platform(&self) -> &'static str {
+ "linux"
+ }
+
+ fn check_names(&self) -> &'static [&'static str] {
+ LINUX_CHECK_NAMES
+ }
+
+ async fn run_check(&self, name: &str) -> CheckEntry {
+ match name {
+ NAME_BINARY_VERSION => check_binary_version(),
+ NAME_PLATFORM_SUPPORTED => check_platform_supported(),
+ NAME_SESSION_ACTIVE => check_session_active(),
+ NAME_BUNDLE_IDENTITY => skip_not_applicable(NAME_BUNDLE_IDENTITY),
+ NAME_TCC_ACCESSIBILITY => skip_not_applicable(NAME_TCC_ACCESSIBILITY),
+ NAME_TCC_SCREEN_RECORDING => skip_not_applicable(NAME_TCC_SCREEN_RECORDING),
+ NAME_AX_CAPABILITY => check_ax_capability().await,
+ NAME_SCREEN_CAPTURE_CAPABILITY => check_screen_capture_capability().await,
+ other => CheckEntry::skip(
+ other.to_owned(),
+ "Unknown check name (not implemented on this platform).",
+ ),
+ }
+ }
+}
+
+// ── Individual checks ────────────────────────────────────────────────────────
+
+pub(crate) fn check_binary_version() -> CheckEntry {
+ CheckEntry::pass(
+ NAME_BINARY_VERSION,
+ format!("cua-driver {}", env!("CARGO_PKG_VERSION")),
+ )
+}
+
+pub(crate) fn check_platform_supported() -> CheckEntry {
+ let arch = arch_label();
+ let os_version = os_release_pretty_name().unwrap_or_else(|| "Linux".to_owned());
+ CheckEntry::pass(
+ NAME_PLATFORM_SUPPORTED,
+ format!("{os_version} ({arch})"),
+ )
+ .with_data(CheckData {
+ os_version: Some(os_version),
+ architecture: Some(arch.to_owned()),
+ ..Default::default()
+ })
+}
+
+pub(crate) fn check_session_active() -> CheckEntry {
+ CheckEntry::pass(NAME_SESSION_ACTIVE, "MCP session is active.")
+}
+
+fn skip_not_applicable(name: &str) -> CheckEntry {
+ CheckEntry::skip(name.to_owned(), "not applicable on Linux".to_owned())
+}
+
+async fn check_ax_capability() -> CheckEntry {
+ // Mirror the existing `check_permissions` Linux probe: X11
+ // connectivity is the AX prerequisite (AT-SPI is over D-Bus, but
+ // input/readback need an X server). Cheap and side-effect-free.
+ let x11_ok = tokio::task::spawn_blocking(probe_x11_connect)
+ .await
+ .unwrap_or(false);
+ if x11_ok {
+ return CheckEntry::pass(
+ NAME_AX_CAPABILITY,
+ "X11 reachable; AT-SPI + XSendEvent input will work.",
+ );
+ }
+ CheckEntry::fail(
+ NAME_AX_CAPABILITY,
+ "X11 is not reachable; UI inspection and event injection will fail.",
+ "Set DISPLAY (X11) — under Wayland, run via XWayland or expose XDG_SESSION_TYPE=x11.",
+ )
+}
+
+async fn check_screen_capture_capability() -> CheckEntry {
+ // On Linux the canonical capture path is X11 GetImage / xwd / scrot
+ // — all require an open X11 connection. The probe is the same one
+ // we use for ax_capability, but the consumer-facing message and
+ // hint differ so future drift between the two doesn't break either
+ // contract.
+ let x11_ok = tokio::task::spawn_blocking(probe_x11_connect)
+ .await
+ .unwrap_or(false);
+ if x11_ok {
+ return CheckEntry::pass(
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+ "X11 reachable; screen capture path is functional.",
+ );
+ }
+ CheckEntry::fail(
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+ "X11 is not reachable; screen capture will fail.",
+ "Set DISPLAY (X11). Pure Wayland sessions require an XWayland bridge for capture.",
+ )
+}
+
+// ── Probes ───────────────────────────────────────────────────────────────────
+
+#[cfg(target_os = "linux")]
+fn probe_x11_connect() -> bool {
+ x11rb::rust_connection::RustConnection::connect(None).is_ok()
+}
+
+#[cfg(not(target_os = "linux"))]
+fn probe_x11_connect() -> bool {
+ false
+}
+
+/// `PRETTY_NAME=` out of `/etc/os-release`. Fails to "Linux" so the
+/// downstream message stays human-readable.
+fn os_release_pretty_name() -> Option<String> {
+ let s = std::fs::read_to_string("/etc/os-release").ok()?;
+ for line in s.lines() {
+ if let Some(rest) = line.strip_prefix("PRETTY_NAME=") {
+ let v = rest.trim_matches('"').to_owned();
+ if !v.is_empty() {
+ return Some(v);
+ }
+ }
+ }
+ None
+}
+
+fn arch_label() -> &'static str {
+ match std::env::consts::ARCH {
+ "aarch64" => "arm64",
+ other => other,
+ }
+}
+
+// ── Tests ────────────────────────────────────────────────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cua_driver_core::health_report::{CheckStatus, HealthReportTool};
+ use cua_driver_core::tool::Tool;
+ use std::sync::Arc;
+
+ #[test]
+ fn binary_version_always_passes() {
+ let entry = check_binary_version();
+ assert_eq!(entry.status, CheckStatus::Pass);
+ assert!(entry.message.contains("cua-driver "));
+ }
+
+ #[test]
+ fn session_active_passes() {
+ let entry = check_session_active();
+ assert_eq!(entry.status, CheckStatus::Pass);
+ }
+
+ #[test]
+ fn tcc_and_bundle_are_skipped_with_canonical_message() {
+ for name in [
+ NAME_TCC_ACCESSIBILITY,
+ NAME_TCC_SCREEN_RECORDING,
+ NAME_BUNDLE_IDENTITY,
+ ] {
+ let entry = skip_not_applicable(name);
+ assert_eq!(entry.status, CheckStatus::Skip, "{name} must be skipped");
+ assert_eq!(entry.message, "not applicable on Linux");
+ }
+ }
+
+ #[tokio::test]
+ async fn invoke_full_run_produces_linux_check_set() {
+ let provider = Arc::new(LinuxHealthProvider);
+ let tool = HealthReportTool::new(provider);
+ let result = tool.invoke(serde_json::json!({})).await;
+ assert!(
+ result.is_error.is_none(),
+ "health_report must never set isError"
+ );
+ let structured = result.structured_content.expect("structured payload");
+ assert_eq!(structured["platform"], "linux");
+ assert_eq!(structured["schema_version"], "1");
+ let names: Vec<&str> = structured["checks"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|c| c["name"].as_str().unwrap())
+ .collect();
+ let expected: Vec<&str> = LINUX_CHECK_NAMES.to_vec();
+ assert_eq!(names, expected);
+
+ let by_name: std::collections::HashMap<_, _> = structured["checks"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|c| (c["name"].as_str().unwrap(), c))
+ .collect();
+ for name in [
+ NAME_TCC_ACCESSIBILITY,
+ NAME_TCC_SCREEN_RECORDING,
+ NAME_BUNDLE_IDENTITY,
+ ] {
+ let entry = by_name[name];
+ assert_eq!(
+ entry["status"], "skip",
+ "{name} must be skipped on Linux"
+ );
+ assert_eq!(entry["message"], "not applicable on Linux");
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
index 86c7eae777..545b077e7f 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/lib.rs
@@ -15,6 +15,7 @@ use cua_driver_core::tool::ToolRegistry;
pub mod tools;
pub mod overlay;
pub mod pip;
+pub mod health_report;
#[cfg(target_os = "linux")]
pub mod x11;
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
index e058cbe87a..876056122c 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
@@ -3622,6 +3622,13 @@ pub fn build_registry(compat: bool) -> ToolRegistry {
r.register(Box::new(GetAgentCursorStateTool { state: state.clone() }));
r.register(Box::new(SetAgentCursorStyleTool { state: state.clone() }));
r.register(Box::new(CheckPermissionsTool));
+ // `health_report` — single-call cross-platform driver diagnostics.
+ // Stable schema_version="1" contract for downstream consumers
+ // (Hermes Agent, NousResearch/hermes-agent#47065). Linux skips
+ // tcc_* and bundle_identity with "not applicable on Linux".
+ r.register(Box::new(cua_driver_core::health_report::HealthReportTool::new(
+ std::sync::Arc::new(crate::health_report::LinuxHealthProvider),
+ )));
r.register(Box::new(GetConfigTool { state: state.clone() }));
r.register(Box::new(SetConfigTool { state: state.clone() }));
r.register(Box::new(GetAccessibilityTreeTool));
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs
index c65a6e1db2..a235ad3848 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/stubs.rs
@@ -222,6 +222,12 @@ pub fn build_registry() -> cua_driver_core::tool::ToolRegistry {
r.register(Box::new(GetAgentCursorStateTool));
r.register(Box::new(SetAgentCursorStyleTool));
r.register(Box::new(CheckPermissionsTool));
+ // health_report is cross-platform — the Linux provider here lets
+ // non-Linux hosts running the stubbed registry still advertise
+ // the documented schema_version="1" contract.
+ r.register(Box::new(cua_driver_core::health_report::HealthReportTool::new(
+ std::sync::Arc::new(crate::health_report::LinuxHealthProvider),
+ )));
r.register(Box::new(GetConfigTool));
r.register(Box::new(SetConfigTool));
r.register(Box::new(GetAccessibilityTreeTool));
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs
new file mode 100644
index 0000000000..c46e55aebe
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/health_report.rs
@@ -0,0 +1,399 @@
+//! macOS `health_report` provider.
+//!
+//! Implements [`HealthCheckProvider`] for darwin. Reuses the existing
+//! TCC plumbing in `crate::permissions::status` rather than
+//! re-implementing it — the goal of the tool is one stable diagnostic
+//! call, not duplicate health logic.
+//!
+//! Schema contract + filter / rollup logic lives in
+//! `cua_driver_core::health_report`. This file owns the platform
+//! probes only.
+
+use async_trait::async_trait;
+use cua_driver_core::health_report::{
+ CheckData, CheckEntry, HealthCheckProvider, NAME_AX_CAPABILITY, NAME_BINARY_VERSION,
+ NAME_BUNDLE_IDENTITY, NAME_PLATFORM_SUPPORTED, NAME_SCREEN_CAPTURE_CAPABILITY,
+ NAME_SESSION_ACTIVE, NAME_TCC_ACCESSIBILITY, NAME_TCC_SCREEN_RECORDING,
+};
+
+use crate::permissions::status::{
+ accessibility_granted, current_status, screen_recording_granted,
+};
+
+/// macOS run order, in the order consumers see them reflected back in
+/// `report.checks[]`. Matches the Swift PR #1905 contract.
+pub const MACOS_CHECK_NAMES: &[&str] = &[
+ NAME_BINARY_VERSION,
+ NAME_PLATFORM_SUPPORTED,
+ NAME_SESSION_ACTIVE,
+ NAME_BUNDLE_IDENTITY,
+ NAME_TCC_ACCESSIBILITY,
+ NAME_TCC_SCREEN_RECORDING,
+ NAME_AX_CAPABILITY,
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+];
+
+/// The canonical bundle identifier whose TCC grants matter for the
+/// daemon. The `bundle_identity` check passes when the running process
+/// reports this id.
+pub const CANONICAL_BUNDLE_ID: &str = "com.trycua.driver";
+
+pub struct MacosHealthProvider;
+
+#[async_trait]
+impl HealthCheckProvider for MacosHealthProvider {
+ fn platform(&self) -> &'static str {
+ "darwin"
+ }
+
+ fn check_names(&self) -> &'static [&'static str] {
+ MACOS_CHECK_NAMES
+ }
+
+ async fn run_check(&self, name: &str) -> CheckEntry {
+ match name {
+ NAME_BINARY_VERSION => check_binary_version(),
+ NAME_PLATFORM_SUPPORTED => check_platform_supported(),
+ NAME_SESSION_ACTIVE => check_session_active(),
+ NAME_BUNDLE_IDENTITY => check_bundle_identity(),
+ NAME_TCC_ACCESSIBILITY => check_tcc_accessibility(),
+ NAME_TCC_SCREEN_RECORDING => check_tcc_screen_recording(),
+ NAME_AX_CAPABILITY => check_ax_capability(),
+ NAME_SCREEN_CAPTURE_CAPABILITY => check_screen_capture_capability().await,
+ // Defensive: the dispatcher only forwards names in
+ // `check_names()`, so this branch should be unreachable.
+ other => CheckEntry::skip(
+ other.to_owned(),
+ "Unknown check name (not implemented on this platform).",
+ ),
+ }
+ }
+}
+
+// ── Individual checks ────────────────────────────────────────────────────────
+
+pub(crate) fn check_binary_version() -> CheckEntry {
+ // CARGO_PKG_VERSION is a compiled-in constant; reaching this code
+ // already implies the binary built. Always pass.
+ CheckEntry::pass(
+ NAME_BINARY_VERSION,
+ format!("cua-driver {}", env!("CARGO_PKG_VERSION")),
+ )
+}
+
+pub(crate) fn check_platform_supported() -> CheckEntry {
+ // Reaching this code path on macOS implies a supported platform —
+ // the macOS build is gated behind `cfg(target_os = "macos")`.
+ let os_version = sw_vers_product_version().unwrap_or_else(|| "unknown".to_owned());
+ let arch = arch_label();
+ CheckEntry::pass(
+ NAME_PLATFORM_SUPPORTED,
+ format!("macOS {os_version} ({arch})"),
+ )
+ .with_data(CheckData {
+ os_version: Some(os_version),
+ architecture: Some(arch.to_owned()),
+ ..Default::default()
+ })
+}
+
+pub(crate) fn check_session_active() -> CheckEntry {
+ // We are servicing this MCP call, so by construction the session
+ // is up. The check exists so consumers can hard-code a canonical
+ // "is the server reachable?" signal in a fixed shape.
+ CheckEntry::pass(NAME_SESSION_ACTIVE, "MCP session is active.")
+}
+
+pub(crate) fn check_bundle_identity() -> CheckEntry {
+ let bid = current_bundle_identifier();
+ let exe = std::env::current_exe()
+ .ok()
+ .and_then(|p| std::fs::canonicalize(p).ok())
+ .and_then(|p| p.to_str().map(str::to_owned))
+ .unwrap_or_default();
+
+ let is_correct = bid.as_deref() == Some(CANONICAL_BUNDLE_ID);
+ let data = CheckData {
+ bundle_identifier: bid.clone(),
+ executable_path: if exe.is_empty() { None } else { Some(exe) },
+ ..Default::default()
+ };
+ if is_correct {
+ return CheckEntry::pass(
+ NAME_BUNDLE_IDENTITY,
+ format!("Bundle is {CANONICAL_BUNDLE_ID}."),
+ )
+ .with_data(data);
+ }
+ let (message, hint) = match bid.as_deref() {
+ None | Some("") => (
+ "Process has no CFBundleIdentifier.".to_owned(),
+ format!(
+ "Run the binary inside CuaDriver.app so TCC grants attribute correctly. \
+ Start the daemon with `open -n -g -a CuaDriver --args serve` and \
+ connect via `cua-driver mcp`."
+ ),
+ ),
+ Some(other) => (
+ format!("Bundle is {other}, not {CANONICAL_BUNDLE_ID}."),
+ format!(
+ "TCC grants will be attributed to {other}, not the cua-driver daemon. \
+ Run via `cua-driver mcp` (auto-relaunches inside CuaDriver.app) or \
+ start the daemon manually: `open -n -g -a CuaDriver --args serve`."
+ ),
+ ),
+ };
+ CheckEntry::fail(NAME_BUNDLE_IDENTITY, message, hint).with_data(data)
+}
+
+fn check_tcc_accessibility() -> CheckEntry {
+ // Reuse the shared probe — do not duplicate AXIsProcessTrusted.
+ let status = current_status();
+ let data = CheckData {
+ bundle_identifier: current_bundle_identifier(),
+ ..Default::default()
+ };
+ if status.accessibility {
+ return CheckEntry::pass(NAME_TCC_ACCESSIBILITY, "Accessibility is granted.")
+ .with_data(data);
+ }
+ CheckEntry::fail(
+ NAME_TCC_ACCESSIBILITY,
+ "Accessibility is NOT granted for this process.",
+ "Grant Accessibility to CuaDriver.app in System Settings → Privacy & Security → \
+ Accessibility. If the process bundle is not com.trycua.driver (see bundle_identity), \
+ the grant must target the responsible app — restart via `cua-driver mcp` to relaunch \
+ inside CuaDriver.app.",
+ )
+ .with_data(data)
+}
+
+fn check_tcc_screen_recording() -> CheckEntry {
+ let granted = screen_recording_granted();
+ let data = CheckData {
+ bundle_identifier: current_bundle_identifier(),
+ ..Default::default()
+ };
+ if granted {
+ return CheckEntry::pass(NAME_TCC_SCREEN_RECORDING, "Screen Recording is granted.")
+ .with_data(data);
+ }
+ CheckEntry::fail(
+ NAME_TCC_SCREEN_RECORDING,
+ "Screen Recording is NOT granted for this process.",
+ "Grant Screen Recording to CuaDriver.app in System Settings → Privacy & Security → \
+ Screen Recording. The grant is attributed to the responsible process — see \
+ bundle_identity to confirm the right binary is being prompted.",
+ )
+ .with_data(data)
+}
+
+fn check_ax_capability() -> CheckEntry {
+ // The AX trust gate is the same kAXIsProcessTrusted probe
+ // `tcc_accessibility` runs, but ax_capability is the consumer-
+ // facing "can I actually drive UI" signal. We separate them so a
+ // future change (e.g. capability degraded without TCC denial)
+ // doesn't break either contract.
+ if accessibility_granted() {
+ return CheckEntry::pass(NAME_AX_CAPABILITY, "AX is trusted and reachable.");
+ }
+ CheckEntry::fail(
+ NAME_AX_CAPABILITY,
+ "AX is not trusted; UI inspection and event posting will fail.",
+ "Resolve tcc_accessibility first — AX capability follows directly from the \
+ Accessibility TCC grant.",
+ )
+}
+
+async fn check_screen_capture_capability() -> CheckEntry {
+ // Live ScreenCaptureKit probe — same shape as `check_permissions`'s
+ // `screen_recording_capturable`, but answer the consumer-facing
+ // capability question and surface the display count.
+ //
+ // `SCShareableContent::get()` is a synchronous C call; wrap it in
+ // spawn_blocking so the async runtime isn't held by a system call
+ // that can take 10-100ms on first invocation.
+ let result = tokio::task::spawn_blocking(probe_shareable_displays)
+ .await
+ .unwrap_or(Err("probe task panicked".to_owned()));
+ match result {
+ Ok(count) => CheckEntry::pass(
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+ format!("ScreenCaptureKit reachable; {count} display(s) shareable."),
+ )
+ .with_data(CheckData {
+ display_count: Some(count),
+ ..Default::default()
+ }),
+ Err(detail) => CheckEntry::fail(
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+ "ScreenCaptureKit probe failed.",
+ "Confirm tcc_screen_recording is granted. If it is, this is an SCK regression — \
+ set capture_mode to `ax` to skip screen capture entirely.",
+ )
+ .with_data(CheckData {
+ error_detail: Some(detail),
+ ..Default::default()
+ }),
+ }
+}
+
+// ── Helpers ──────────────────────────────────────────────────────────────────
+
+/// Live ScreenCaptureKit probe — enumerates shareable displays. Writes
+/// nothing to disk; we never start a stream. Returns display count on
+/// success, error string on failure.
+fn probe_shareable_displays() -> Result<u32, String> {
+ use screencapturekit::prelude::SCShareableContent;
+ let content =
+ SCShareableContent::get().map_err(|e| format!("SCShareableContent::get: {e:?}"))?;
+ Ok(content.displays().len() as u32)
+}
+
+/// Read the running process's `CFBundleIdentifier` via CoreFoundation.
+/// Returns `None` when the process has no associated bundle (e.g.
+/// running the bare binary outside `CuaDriver.app`).
+fn current_bundle_identifier() -> Option<String> {
+ use core_foundation::base::TCFType;
+ use core_foundation::bundle::{CFBundle, CFBundleGetMainBundle};
+ use core_foundation::string::CFString;
+
+ unsafe {
+ let raw = CFBundleGetMainBundle();
+ if raw.is_null() {
+ return None;
+ }
+ // CFBundleGetMainBundle returns a borrowed reference; wrap it
+ // without retaining and read the bundle identifier. `bundle`
+ // intentionally doesn't drop the underlying CF object.
+ let bundle = CFBundle::wrap_under_get_rule(raw);
+ let id_ref = core_foundation::bundle::CFBundleGetIdentifier(bundle.as_concrete_TypeRef());
+ if id_ref.is_null() {
+ return None;
+ }
+ let id = CFString::wrap_under_get_rule(id_ref);
+ let s = id.to_string();
+ if s.is_empty() {
+ None
+ } else {
+ Some(s)
+ }
+ }
+}
+
+/// `sw_vers -productVersion` — e.g. "14.5". Used in the
+/// `platform_supported` message; failure falls back to "unknown".
+fn sw_vers_product_version() -> Option<String> {
+ let output = std::process::Command::new("/usr/bin/sw_vers")
+ .arg("-productVersion")
+ .output()
+ .ok()?;
+ if !output.status.success() {
+ return None;
+ }
+ let v = String::from_utf8_lossy(&output.stdout).trim().to_owned();
+ if v.is_empty() {
+ None
+ } else {
+ Some(v)
+ }
+}
+
+/// `arm64` / `x86_64`. Matches the label scheme used by `telemetry::arch`.
+fn arch_label() -> &'static str {
+ match std::env::consts::ARCH {
+ "aarch64" => "arm64",
+ other => other,
+ }
+}
+
+// ── Tests ────────────────────────────────────────────────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cua_driver_core::health_report::{CheckStatus, HealthReportTool};
+ use cua_driver_core::tool::Tool;
+ use std::sync::Arc;
+
+ #[test]
+ fn binary_version_always_passes() {
+ let entry = check_binary_version();
+ assert_eq!(entry.status, CheckStatus::Pass);
+ assert!(
+ entry.message.contains("cua-driver "),
+ "message must include the binary version"
+ );
+ }
+
+ #[test]
+ fn platform_supported_carries_os_and_arch_data() {
+ let entry = check_platform_supported();
+ assert_eq!(entry.status, CheckStatus::Pass);
+ let data = entry.data.expect("data block expected");
+ assert!(data.os_version.is_some(), "os_version must be set");
+ assert!(data.architecture.is_some(), "architecture must be set");
+ }
+
+ #[test]
+ fn session_active_passes() {
+ let entry = check_session_active();
+ assert_eq!(entry.status, CheckStatus::Pass);
+ }
+
+ #[test]
+ fn bundle_identity_in_test_host_fails_with_full_shape() {
+ // The Rust test binary runs outside CuaDriver.app, so its
+ // bundle id is either absent or not com.trycua.driver. Either
+ // way the documented fail-mode shape applies: message + hint
+ // + data + (when bid is present) bundle_identifier surfaced.
+ //
+ // This is the same fixture pattern the Swift PR used: the
+ // test environment naturally reproduces the canonical
+ // attribution-drift fail mode without any mocking.
+ let entry = check_bundle_identity();
+ assert_eq!(
+ entry.status,
+ CheckStatus::Fail,
+ "expected bundle_identity to fail in the test host environment"
+ );
+ assert!(!entry.message.is_empty());
+ assert!(
+ entry.hint.is_some(),
+ "fail entries must carry a remediation hint"
+ );
+ let data = entry.data.expect("fail entries must carry diagnostic data");
+ // executable_path is always available when current_exe()
+ // works; surface it so consumers can locate the wrong binary.
+ assert!(
+ data.executable_path.is_some(),
+ "executable_path must be set so consumers can identify the wrong binary"
+ );
+ }
+
+ // End-to-end through the dispatcher — checks every macOS canonical
+ // name appears in the response and the response shape matches the
+ // documented contract.
+ #[tokio::test]
+ async fn invoke_full_run_produces_macos_check_set() {
+ let provider = Arc::new(MacosHealthProvider);
+ let tool = HealthReportTool::new(provider);
+ let result = tool.invoke(serde_json::json!({})).await;
+ assert!(
+ result.is_error.is_none(),
+ "health_report must never set isError"
+ );
+ let structured = result.structured_content.expect("structured payload");
+ assert_eq!(structured["platform"], "darwin");
+ assert_eq!(structured["schema_version"], "1");
+ let names: Vec<&str> = structured["checks"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|c| c["name"].as_str().unwrap())
+ .collect();
+ // Every documented macOS check appears, in declared order.
+ let expected: Vec<&str> = MACOS_CHECK_NAMES.to_vec();
+ assert_eq!(names, expected);
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
index c2634540b8..7d4457669e 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
@@ -28,6 +28,7 @@ mod check_permissions;
mod get_config;
mod set_config;
mod get_accessibility_tree;
+mod health_report;
mod zoom;
mod type_text_chars;
mod page;
@@ -336,6 +337,15 @@ pub fn register_all(registry: &mut ToolRegistry, compat: bool) {
registry.register(Box::new(cursor_tools::SetAgentCursorStyleTool::new(state.clone())));
registry.register(Box::new(cursor_tools::GetAgentCursorStateTool::new(state.clone())));
registry.register(Box::new(check_permissions::CheckPermissionsTool));
+ // `health_report` — single-call end-to-end diagnostics. Stable
+ // schema_version="1" contract aimed at downstream consumers
+ // (Hermes Agent's `hermes computer-use doctor`, NousResearch/
+ // hermes-agent#47065) who must NOT have to know cua-driver
+ // internals. Provider is platform-specific; tool plumbing is in
+ // `cua_driver_core::health_report`.
+ registry.register(Box::new(cua_driver_core::health_report::HealthReportTool::new(
+ Arc::new(health_report::MacosHealthProvider),
+ )));
registry.register(Box::new(get_config::GetConfigTool::new(state.clone())));
registry.register(Box::new(set_config::SetConfigTool::new(state.clone())));
registry.register(Box::new(get_accessibility_tree::GetAccessibilityTreeTool::new(state.clone())));
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs b/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs
new file mode 100644
index 0000000000..63cbd0fad2
--- /dev/null
+++ b/libs/cua-driver/rust/crates/platform-windows/src/health_report.rs
@@ -0,0 +1,300 @@
+//! Windows `health_report` provider.
+//!
+//! Implements [`cua_driver_core::health_report::HealthCheckProvider`]
+//! for `win32`. Reuses the existing UIA + DXGI probes — see
+//! [`crate::diagnostics::ui_automation_available`] for AX and a fresh
+//! `D3D11CreateDevice` probe for screen capture.
+//!
+//! The TCC / bundle checks emit `status: "skip"` with `message: "not
+//! applicable on Windows"` rather than `fail`; Windows has no TCC.
+
+use async_trait::async_trait;
+use cua_driver_core::health_report::{
+ CheckData, CheckEntry, HealthCheckProvider, NAME_AX_CAPABILITY, NAME_BINARY_VERSION,
+ NAME_BUNDLE_IDENTITY, NAME_PLATFORM_SUPPORTED, NAME_SCREEN_CAPTURE_CAPABILITY,
+ NAME_SESSION_ACTIVE, NAME_TCC_ACCESSIBILITY, NAME_TCC_SCREEN_RECORDING,
+};
+
+/// Windows canonical check names — the same Swift-PR contract, with
+/// TCC/bundle entries surfaced as `skip("not applicable on Windows")`
+/// rather than `fail`. Skipped entries still appear so cross-platform
+/// consumers see a complete check map.
+pub const WINDOWS_CHECK_NAMES: &[&str] = &[
+ NAME_BINARY_VERSION,
+ NAME_PLATFORM_SUPPORTED,
+ NAME_SESSION_ACTIVE,
+ NAME_BUNDLE_IDENTITY,
+ NAME_TCC_ACCESSIBILITY,
+ NAME_TCC_SCREEN_RECORDING,
+ NAME_AX_CAPABILITY,
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+];
+
+pub struct WindowsHealthProvider;
+
+#[async_trait]
+impl HealthCheckProvider for WindowsHealthProvider {
+ fn platform(&self) -> &'static str {
+ "win32"
+ }
+
+ fn check_names(&self) -> &'static [&'static str] {
+ WINDOWS_CHECK_NAMES
+ }
+
+ async fn run_check(&self, name: &str) -> CheckEntry {
+ match name {
+ NAME_BINARY_VERSION => check_binary_version(),
+ NAME_PLATFORM_SUPPORTED => check_platform_supported(),
+ NAME_SESSION_ACTIVE => check_session_active(),
+ NAME_BUNDLE_IDENTITY => skip_not_applicable(NAME_BUNDLE_IDENTITY),
+ NAME_TCC_ACCESSIBILITY => skip_not_applicable(NAME_TCC_ACCESSIBILITY),
+ NAME_TCC_SCREEN_RECORDING => skip_not_applicable(NAME_TCC_SCREEN_RECORDING),
+ NAME_AX_CAPABILITY => check_ax_capability().await,
+ NAME_SCREEN_CAPTURE_CAPABILITY => check_screen_capture_capability().await,
+ other => CheckEntry::skip(
+ other.to_owned(),
+ "Unknown check name (not implemented on this platform).",
+ ),
+ }
+ }
+}
+
+// ── Individual checks ────────────────────────────────────────────────────────
+
+pub(crate) fn check_binary_version() -> CheckEntry {
+ CheckEntry::pass(
+ NAME_BINARY_VERSION,
+ format!("cua-driver {}", env!("CARGO_PKG_VERSION")),
+ )
+}
+
+pub(crate) fn check_platform_supported() -> CheckEntry {
+ // The Windows build is gated behind `cfg(target_os = "windows")`,
+ // so reaching this code path already implies a supported platform.
+ let arch = arch_label();
+ let os_version = ver_string().unwrap_or_else(|| "unknown".to_owned());
+ CheckEntry::pass(
+ NAME_PLATFORM_SUPPORTED,
+ format!("Windows {os_version} ({arch})"),
+ )
+ .with_data(CheckData {
+ os_version: Some(os_version),
+ architecture: Some(arch.to_owned()),
+ ..Default::default()
+ })
+}
+
+pub(crate) fn check_session_active() -> CheckEntry {
+ CheckEntry::pass(NAME_SESSION_ACTIVE, "MCP session is active.")
+}
+
+/// Standard "this category does not exist on Windows" entry. Used for
+/// `tcc_*` and `bundle_identity` so cross-platform consumers can rely
+/// on a known answer rather than the entry being missing.
+fn skip_not_applicable(name: &str) -> CheckEntry {
+ CheckEntry::skip(name.to_owned(), "not applicable on Windows".to_owned())
+}
+
+async fn check_ax_capability() -> CheckEntry {
+ // CoCreateInstance is synchronous and can take a few ms; keep the
+ // async runtime responsive by punting to spawn_blocking.
+ let result = tokio::task::spawn_blocking(crate::diagnostics::ui_automation_available)
+ .await
+ .unwrap_or(Err("UIA probe task panicked".to_owned()));
+ match result {
+ Ok(()) => CheckEntry::pass(
+ NAME_AX_CAPABILITY,
+ "UIAutomation is reachable; UI tree walking will succeed.",
+ ),
+ Err(detail) => CheckEntry::fail(
+ NAME_AX_CAPABILITY,
+ "UIAutomation is not reachable; AX-driven tools will fail.",
+ "If running under Session 0 (Windows service or SSH-launched), re-run from \
+ an interactive logon (RDP, console, or a scheduled task in the user's session). \
+ Session 0 has no attached desktop, so the UIA COM server cannot be activated.",
+ )
+ .with_data(CheckData {
+ error_detail: Some(detail),
+ ..Default::default()
+ }),
+ }
+}
+
+async fn check_screen_capture_capability() -> CheckEntry {
+ let result = tokio::task::spawn_blocking(probe_d3d11_device)
+ .await
+ .unwrap_or(Err("D3D11 probe task panicked".to_owned()));
+ match result {
+ Ok(()) => CheckEntry::pass(
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+ "D3D11 device reachable; Windows Graphics Capture will succeed.",
+ ),
+ Err(detail) => CheckEntry::fail(
+ NAME_SCREEN_CAPTURE_CAPABILITY,
+ "D3D11 device probe failed.",
+ "Confirm a hardware-accelerated graphics adapter is present and current drivers \
+ are installed. In Session 0 / headless contexts, D3D hardware may be unavailable \
+ — set capture_mode to `ax` to skip screen capture entirely.",
+ )
+ .with_data(CheckData {
+ error_detail: Some(detail),
+ ..Default::default()
+ }),
+ }
+}
+
+// ── Probes ───────────────────────────────────────────────────────────────────
+
+/// Try to create a hardware D3D11 device + BGRA-capable feature level
+/// 11.0 — exactly what the WGC capture path needs.
+#[cfg(target_os = "windows")]
+fn probe_d3d11_device() -> Result<(), String> {
+ use windows::Win32::Graphics::{
+ Direct3D::{D3D_DRIVER_TYPE_HARDWARE, D3D_FEATURE_LEVEL_11_0},
+ Direct3D11::{
+ D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext,
+ D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_SDK_VERSION,
+ },
+ };
+ let mut device: Option<ID3D11Device> = None;
+ let mut context: Option<ID3D11DeviceContext> = None;
+ let result = unsafe {
+ D3D11CreateDevice(
+ None,
+ D3D_DRIVER_TYPE_HARDWARE,
+ windows::Win32::Foundation::HMODULE(std::ptr::null_mut()),
+ D3D11_CREATE_DEVICE_BGRA_SUPPORT,
+ Some(&[D3D_FEATURE_LEVEL_11_0]),
+ D3D11_SDK_VERSION,
+ Some(&mut device),
+ None,
+ Some(&mut context),
+ )
+ };
+ result.map_err(|e| format!("D3D11CreateDevice: {e}"))?;
+ // Drop the COM interfaces explicitly so Release runs on this thread.
+ drop(context);
+ drop(device);
+ Ok(())
+}
+
+#[cfg(not(target_os = "windows"))]
+fn probe_d3d11_device() -> Result<(), String> {
+ Err("not a Windows host".to_owned())
+}
+
+/// `cmd /c ver` — e.g. "Microsoft Windows [Version 10.0.19045.4170]".
+/// Fails fast on non-Windows — returns `None`.
+fn ver_string() -> Option<String> {
+ #[cfg(target_os = "windows")]
+ {
+ let output = std::process::Command::new("cmd").args(["/c", "ver"]).output().ok()?;
+ if !output.status.success() {
+ return None;
+ }
+ let v = String::from_utf8_lossy(&output.stdout).trim().to_owned();
+ if v.is_empty() {
+ None
+ } else {
+ Some(v)
+ }
+ }
+ #[cfg(not(target_os = "windows"))]
+ {
+ None
+ }
+}
+
+fn arch_label() -> &'static str {
+ match std::env::consts::ARCH {
+ "aarch64" => "arm64",
+ other => other,
+ }
+}
+
+// ── Tests ────────────────────────────────────────────────────────────────────
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use cua_driver_core::health_report::{CheckStatus, HealthReportTool};
+ use cua_driver_core::tool::Tool;
+ use std::sync::Arc;
+
+ #[test]
+ fn binary_version_always_passes() {
+ let entry = check_binary_version();
+ assert_eq!(entry.status, CheckStatus::Pass);
+ assert!(entry.message.contains("cua-driver "));
+ }
+
+ #[test]
+ fn session_active_passes() {
+ let entry = check_session_active();
+ assert_eq!(entry.status, CheckStatus::Pass);
+ }
+
+ #[test]
+ fn tcc_and_bundle_are_skipped_with_canonical_message() {
+ for name in [
+ NAME_TCC_ACCESSIBILITY,
+ NAME_TCC_SCREEN_RECORDING,
+ NAME_BUNDLE_IDENTITY,
+ ] {
+ let entry = skip_not_applicable(name);
+ assert_eq!(entry.status, CheckStatus::Skip, "{name} must be skipped");
+ assert_eq!(entry.message, "not applicable on Windows");
+ }
+ }
+
+ // End-to-end through the dispatcher: every Windows canonical name
+ // appears in the response, in declared order. Run on every host so
+ // CI matrices that don't target Windows still verify the schema
+ // shape — the platform-skipped entries are deterministic regardless
+ // of host.
+ #[tokio::test]
+ async fn invoke_full_run_produces_windows_check_set() {
+ let provider = Arc::new(WindowsHealthProvider);
+ let tool = HealthReportTool::new(provider);
+ let result = tool.invoke(serde_json::json!({})).await;
+ assert!(
+ result.is_error.is_none(),
+ "health_report must never set isError"
+ );
+ let structured = result.structured_content.expect("structured payload");
+ assert_eq!(structured["platform"], "win32");
+ assert_eq!(structured["schema_version"], "1");
+ let names: Vec<&str> = structured["checks"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|c| c["name"].as_str().unwrap())
+ .collect();
+ let expected: Vec<&str> = WINDOWS_CHECK_NAMES.to_vec();
+ assert_eq!(names, expected);
+
+ // Cross-platform consumers depend on these being skipped (not
+ // failed) on Windows — that's the documented "not applicable"
+ // shape.
+ let by_name: std::collections::HashMap<_, _> = structured["checks"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|c| (c["name"].as_str().unwrap(), c))
+ .collect();
+ for name in [
+ NAME_TCC_ACCESSIBILITY,
+ NAME_TCC_SCREEN_RECORDING,
+ NAME_BUNDLE_IDENTITY,
+ ] {
+ let entry = by_name[name];
+ assert_eq!(
+ entry["status"], "skip",
+ "{name} must be skipped on Windows, got {:?}",
+ entry["status"]
+ );
+ assert_eq!(entry["message"], "not applicable on Windows");
+ }
+ }
+}
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
index 28d4bfd026..30c424fa01 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/lib.rs
@@ -21,6 +21,7 @@ use cua_driver_core::tool::ToolRegistry;
pub mod tools;
pub mod overlay;
pub mod diagnostics;
+pub mod health_report;
pub mod recording_hooks;
pub mod pip;
pub mod terminal;
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
index f44a188844..272b508d22 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
@@ -5759,6 +5759,13 @@ pub fn build_registry(compat: bool) -> ToolRegistry {
r.register(Box::new(GetAgentCursorStateTool { state: state.clone() }));
r.register(Box::new(SetAgentCursorStyleTool { state: state.clone() }));
r.register(Box::new(CheckPermissionsTool));
+ // `health_report` — single-call cross-platform driver diagnostics.
+ // Stable schema_version="1" contract for downstream consumers
+ // (Hermes Agent, NousResearch/hermes-agent#47065). Windows skips
+ // tcc_* and bundle_identity with "not applicable on Windows".
+ r.register(Box::new(cua_driver_core::health_report::HealthReportTool::new(
+ std::sync::Arc::new(crate::health_report::WindowsHealthProvider),
+ )));
r.register(Box::new(GetConfigTool { state: state.clone() }));
r.register(Box::new(SetConfigTool { state: state.clone() }));
r.register(Box::new(GetAccessibilityTreeTool));
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs
index a7eb705411..181ec6bdcb 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/stubs.rs
@@ -222,6 +222,12 @@ pub fn build_registry() -> cua_driver_core::tool::ToolRegistry {
r.register(Box::new(GetAgentCursorStateTool));
r.register(Box::new(SetAgentCursorStyleTool));
r.register(Box::new(CheckPermissionsTool));
+ // health_report is cross-platform — the Windows provider here lets
+ // non-Windows hosts running the stubbed registry still advertise
+ // the documented schema_version="1" contract.
+ r.register(Box::new(cua_driver_core::health_report::HealthReportTool::new(
+ std::sync::Arc::new(crate::health_report::WindowsHealthProvider),
+ )));
r.register(Box::new(GetConfigTool));
r.register(Box::new(SetConfigTool));
r.register(Box::new(GetAccessibilityTreeTool));
diff --git a/libs/cua-driver/rust/tests/integration/test_health_report_mcp.py b/libs/cua-driver/rust/tests/integration/test_health_report_mcp.py
new file mode 100644
index 0000000000..26c1908ba2
--- /dev/null
+++ b/libs/cua-driver/rust/tests/integration/test_health_report_mcp.py
@@ -0,0 +1,238 @@
+"""Integration test: `health_report` MCP tool over the stdio protocol.
+
+Boots the real `cua-driver mcp` server, performs the JSON-RPC handshake,
+asks `tools/list` for the tool catalog, and exercises the tool with
+several argument shapes:
+
+ 1. `tools/list` advertises `health_report` (the consumer-facing
+ contract is that the tool exists and ships `schema_version="1"` in
+ its description).
+
+ 2. Calling with no arguments produces a well-formed report with the
+ documented top-level keys and per-check key shape.
+
+ 3. The `skip` filter is honored end-to-end: a skipped check appears in
+ the output with `status: "skip"`.
+
+ 4. The `include` filter narrows the report to a single check.
+
+ 5. A documented fail mode is observable end-to-end: when called via
+ `cua-driver mcp` from a terminal (which is what an XCTest / CI
+ host looks like on macOS), the `bundle_identity` check fails
+ because the stdio process is NOT attributed to com.trycua.driver.
+ The schema guarantees `status="fail"` entries carry a `hint` and
+ surface the runtime bundle identifier under
+ `data.bundle_identifier` — both are asserted here. On Windows /
+ Linux the same check returns `status="skip"`, which we tolerate.
+
+ 6. health_report must NEVER itself set isError, even when every
+ check fails — that's the whole point of the tool.
+
+Run with the standard integration test harness:
+ ./run_tests.sh test_health_report_mcp
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import sys
+import unittest
+
+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
+from driver_client import DriverClient, default_binary_path
+
+
+REQUIRED_TOP_LEVEL_KEYS = {
+ "schema_version",
+ "platform",
+ "driver_version",
+ "overall",
+ "checks",
+}
+
+REQUIRED_CHECK_KEYS = {"name", "status", "message"}
+ALLOWED_STATUS_VALUES = {"pass", "fail", "skip"}
+ALLOWED_OVERALL_VALUES = {"ok", "degraded", "failed"}
+ALLOWED_PLATFORM_VALUES = {"darwin", "win32", "linux"}
+
+
+def _structured_or_parsed(result: dict) -> dict:
+ """Pull the JSON report out of an MCP tool result.
+
+ Tools that emit `structuredContent` (the canonical path here)
+ return it as a top-level field. We also tolerate a text-content
+ fallback so if structured emission ever breaks, the test fails
+ loudly with a clear message rather than crashing on a KeyError.
+ """
+ if "structuredContent" in result:
+ return result["structuredContent"]
+ for content in result.get("content", []):
+ if content.get("type") == "text":
+ try:
+ return json.loads(content.get("text", ""))
+ except json.JSONDecodeError:
+ continue
+ raise AssertionError(
+ "health_report response carried neither structuredContent nor a JSON text block: "
+ + json.dumps(result)
+ )
+
+
+class HealthReportMCPTests(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls) -> None:
+ cls.binary = default_binary_path()
+
+ # ── tools/list ────────────────────────────────────────────────────
+
+ def test_tools_list_advertises_health_report(self) -> None:
+ with DriverClient(self.binary) as client:
+ tools = client.list_tools()
+ names = {t["name"] for t in tools}
+ self.assertIn(
+ "health_report",
+ names,
+ "tools/list must advertise health_report so consumers can discover it",
+ )
+ descriptor = next(t for t in tools if t["name"] == "health_report")
+ # The schema_version commitment lives in the description text —
+ # that's the consumer-facing stability contract.
+ description = descriptor.get("description", "")
+ self.assertIn(
+ "schema_version",
+ description,
+ "tool description must call out the stable schema_version contract",
+ )
+
+ # ── tools/call with no args ───────────────────────────────────────
+
+ def test_call_with_no_args_returns_schema_shape(self) -> None:
+ with DriverClient(self.binary) as client:
+ result = client.call_tool("health_report")
+ report = _structured_or_parsed(result)
+
+ # Top-level keys exactly match the documented schema.
+ self.assertEqual(
+ REQUIRED_TOP_LEVEL_KEYS,
+ REQUIRED_TOP_LEVEL_KEYS & set(report.keys()),
+ f"missing top-level keys; got {set(report.keys())!r}",
+ )
+ self.assertEqual(report["schema_version"], "1")
+ self.assertIn(report["platform"], ALLOWED_PLATFORM_VALUES)
+ self.assertIsInstance(report["driver_version"], str)
+ self.assertIn(report["overall"], ALLOWED_OVERALL_VALUES)
+
+ checks = report["checks"]
+ self.assertIsInstance(checks, list)
+ self.assertGreater(len(checks), 0)
+
+ for check in checks:
+ self.assertTrue(
+ REQUIRED_CHECK_KEYS.issubset(check.keys()),
+ f"check missing required keys: {check!r}",
+ )
+ self.assertIn(check["status"], ALLOWED_STATUS_VALUES)
+ # hint is only required when status == fail.
+ if check["status"] == "fail":
+ self.assertIn(
+ "hint",
+ check,
+ f"fail entries must carry a remediation hint: {check!r}",
+ )
+ self.assertTrue(
+ isinstance(check["hint"], str) and check["hint"].strip(),
+ f"hint must be a non-empty string: {check!r}",
+ )
+
+ # ── skip filter ───────────────────────────────────────────────────
+
+ def test_skip_filter_marks_check_as_skip(self) -> None:
+ with DriverClient(self.binary) as client:
+ result = client.call_tool(
+ "health_report",
+ {"skip": ["tcc_accessibility"]},
+ )
+ report = _structured_or_parsed(result)
+ names_to_status = {c["name"]: c["status"] for c in report["checks"]}
+ self.assertEqual(names_to_status.get("tcc_accessibility"), "skip")
+
+ # ── include filter ───────────────────────────────────────────────
+
+ def test_include_filter_runs_only_named_check(self) -> None:
+ with DriverClient(self.binary) as client:
+ result = client.call_tool(
+ "health_report",
+ {"include": ["binary_version"]},
+ )
+ report = _structured_or_parsed(result)
+ run_names = {
+ c["name"] for c in report["checks"] if c["status"] != "skip"
+ }
+ # Only `binary_version` should have been actually run; the rest
+ # show up with status: skip.
+ self.assertEqual(run_names, {"binary_version"})
+
+ # ── documented fail mode (macOS only) ────────────────────────────
+
+ def test_bundle_identity_fail_mode_under_stdio_mcp(self) -> None:
+ """On macOS the stdio MCP process spawned by an IDE/CI shell
+ runs outside CuaDriver.app, so its CFBundleIdentifier is NOT
+ com.trycua.driver. That's the canonical "wrong attribution"
+ fail mode the tool is designed to surface — schema-wise:
+ status=fail + non-empty message + non-empty hint +
+ data.bundle_identifier present so consumers can detect the
+ drift without parsing the message text.
+
+ On Windows / Linux the same check returns status=skip ("not
+ applicable on Windows/Linux"); the test tolerates that.
+ """
+ with DriverClient(self.binary) as client:
+ result = client.call_tool(
+ "health_report",
+ {"include": ["bundle_identity"]},
+ )
+ report = _structured_or_parsed(result)
+ bundle_check = next(
+ c for c in report["checks"] if c["name"] == "bundle_identity"
+ )
+ if bundle_check["status"] == "skip":
+ # Windows / Linux path — `not applicable on <platform>`.
+ self.assertIn("not applicable", bundle_check.get("message", ""))
+ return
+ if bundle_check["status"] == "pass":
+ # macOS launched inside CuaDriver.app — legitimately passes.
+ return
+ # macOS fail mode — schema contract on fail entries.
+ self.assertEqual(bundle_check["status"], "fail")
+ self.assertIn("hint", bundle_check)
+ self.assertTrue(bundle_check["hint"].strip())
+ data = bundle_check.get("data") or {}
+ # bundle_identifier surfaces the runtime CFBundleIdentifier so
+ # consumers can detect drift without parsing the message.
+ # Optional only when the process literally has no bundle id;
+ # Rust-built binaries always have an executable_path.
+ self.assertTrue(
+ "bundle_identifier" in data or "executable_path" in data,
+ "fail mode must surface either bundle_identifier or executable_path in `data`",
+ )
+
+ # ── invocation surface itself doesn't error ──────────────────────
+
+ def test_call_does_not_set_isError(self) -> None:
+ """`health_report` is the consumer's "what's broken?" probe —
+ it must never itself report `isError: true`, even when every
+ check fails. Otherwise consumers can't tell apart "the tool
+ itself is broken" from "the driver has degraded health" —
+ defeating the whole point of the tool.
+ """
+ with DriverClient(self.binary) as client:
+ result = client.call_tool("health_report")
+ self.assertFalse(
+ result.get("isError", False),
+ f"health_report must never set isError; got {result!r}",
+ )
+
+
+if __name__ == "__main__":
+ unittest.main()