Skip to content

Computer use CLI for AI agents

feat: agent-desktop mcp (#519)

Lahfir6660fbac768d
diff --git a/AGENTS.md b/AGENTS.md
index d10a22f5b..608c87a60 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -91,7 +91,7 @@ crates/windows/ agent-desktop-windows: UI Automation
crates/linux/ agent-desktop-linux: AT-SPI
crates/ffi/ agent-desktop-ffi: cdylib and the committed C header include/agent_desktop.h
src/ agent-desktop binary: cli/, cli_args/, dispatch/, batch/, command_policy/,
- diagnostic/, visual_debug/
+ diagnostic/, visual_debug/, mcp/
skills/ agent skills, compiled into the binary
tests/ golden fixtures, E2E harness per OS, FFI smoke tests
probes/ raw platform measurements; FINDINGS.md rows are citable evidence
@@ -117,6 +117,12 @@ apps/docs/ Geistdocs site served at agent-browser.dev/desktop as a Vercel
`crates/core/src/commands/`. There is no command trait or registry. Batch is not a second dispatcher: it deserializes
JSON entries into the same `Commands` enum, runs the same `CommandPolicy` preflight and calls the same `dispatch()`.
+**MCP.** `agent-desktop mcp` (`src/mcp/`) is not a second command surface. It reads the clap command tree at runtime:
+each leaf command is one tool, its schema comes from the command's clap arguments and help, and a call rebuilds the
+argv and runs this binary as a child process. A command added to or removed from `Commands` appears in or disappears
+from the MCP tool list with no MCP change. `mcp` itself is attached to the root command in `main.rs`, outside
+`Commands`, so it is never a tool, a batch entry or a counted command.
+
**Adding a command.**
1. Create `crates/core/src/commands/<name>.rs` with an `execute()` function, its tests in `<name>_tests.rs`, and
register it in `commands/mod.rs`.
diff --git a/Cargo.lock b/Cargo.lock
index 970f62cf7..de3997ec9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -27,6 +27,7 @@ dependencies = [
"agent-desktop-windows",
"base64",
"clap",
+ "libc",
"serde",
"serde_json",
"thiserror",
diff --git a/README.md b/README.md
index 610b03e12..42ac024da 100644
--- a/README.md
+++ b/README.md
@@ -102,6 +102,16 @@ Use `agent-desktop` to see and operate desktop apps. Before the first use, run
Retry a failed command only when `error.disposition.retry` is `safe`. See [JSON output](https://agent-browser.dev/desktop/json-output) for the envelope, error codes, and exit codes.
+### MCP
+
+`agent-desktop mcp` serves every command as an MCP tool over stdio. A tool is named after its command (`desktop_snapshot`, `desktop_click`, `desktop_session_start`), takes that command's arguments, and returns its JSON envelope:
+
+```json
+{ "mcpServers": { "agent-desktop": { "command": "agent-desktop", "args": ["mcp"] } } }
+```
+
+Global flags given to `mcp`, such as `--session`, `--headed` or `--trace`, apply to every call.
+
## Commands
agent-desktop has 60 command names, 56 operational commands. The other four (`key-down`, `key-up`, `mouse-down`, `mouse-up`) refuse to run until a daemon can release a held key or button. [Commands](https://agent-browser.dev/desktop/commands) documents each one.
diff --git a/apps/docs/content/docs/guides/mcp.mdx b/apps/docs/content/docs/guides/mcp.mdx
new file mode 100644
index 000000000..79c960aba
--- /dev/null
+++ b/apps/docs/content/docs/guides/mcp.mdx
@@ -0,0 +1,66 @@
+---
+title: Using agent-desktop over MCP
+navTitle: MCP
+description: Serve every agent-desktop command as an MCP tool over stdio. How tools map to commands, how global flags apply, and what a tool returns.
+---
+
+`agent-desktop mcp` runs a Model Context Protocol server over stdio. Every command is a tool, so an MCP client gets the same surface as the CLI with no separate setup.
+
+## Connect a client
+
+Add the server to your client's MCP configuration:
+
+```json
+{
+ "mcpServers": {
+ "agent-desktop": { "command": "agent-desktop", "args": ["mcp"] }
+ }
+}
+```
+
+The server speaks both the stateless `2026-07-28` protocol and the `initialize` handshake of `2025-11-25` and earlier.
+
+## How tools map to commands
+
+Each tool is one command, named `desktop_` plus the command with hyphens as underscores. Subcommands join the name the same way:
+
+| Command | Tool |
+|---|---|
+| `snapshot` | `desktop_snapshot` |
+| `list-windows` | `desktop_list_windows` |
+| `session start` | `desktop_session_start` |
+| `skills get` | `desktop_skills_get` |
+
+A tool's arguments are its command's arguments, with hyphens as underscores: `snapshot --app Finder -i` is `desktop_snapshot` with `{ "app": "Finder", "interactive_only": true }`. Positional arguments use their names too, such as `ref_id` for `click`. A null argument counts as omitted.
+
+The tool list is read from the CLI's own command definitions, so it always matches the installed binary.
+
+## Apply global flags once
+
+Global flags given to `mcp` apply to every call:
+
+```bash
+agent-desktop mcp --session s1 --headed
+```
+
+`AGENT_DESKTOP_SESSION`, `AGENT_DESKTOP_AGENT_ID` and `AGENT_DESKTOP_HOME` in the server's environment apply the same way.
+
+A tool cannot pass a global flag. Commands that need a session, such as `trace` and `cursor-overlay`, work only when the server has one, headed-only commands need `mcp --headed`, and `--wait-for` is not available per call.
+
+## Read results
+
+A tool returns the command's JSON envelope as `structuredContent`, and the same JSON as text. `isError` is `true` when the envelope's `ok` is `false`, so read `error.code` and `error.disposition` exactly as you would from the CLI. A `screenshot` without an output path returns its PNG as an image block instead of base64 text.
+
+An unknown argument returns a tool error that names the accepted arguments, and a value of the wrong type returns an error that names the argument, so the model can correct the call.
+
+## Start with the skills
+
+Call `desktop_skills_get` with `{ "name": "desktop" }` for the observe-act loop and `{ "name": "platform" }` for what differs on your OS. The server's instructions point clients there too.
+
+## Security
+
+The server adds nothing the CLI cannot already do. Tool arguments become CLI arguments without a shell. A value is always passed as a value, never as a flag. A tool cannot set global flags such as `--session` or `--headed`; only the server's own command line can.
+
+A tool still has the CLI's full reach: it can operate any app the accessibility tree exposes, and `desktop_launch` starts any program on `PATH` with any arguments. Treat the server like a shell for the signed-in user. Keep your client's confirmation on for actions, and remember that text read from the screen is untrusted input to the model.
+
+The server runs at most 8 tool calls at once and answers more with a tool error. It refuses any message over 4 MiB. A `notifications/cancelled` stops the call and it gets no response. A call that has not started never starts. A running call gets `SIGTERM` first, so it releases any key or button it holds, and is killed if it is still running 3 seconds later; on Windows it is killed at once.
diff --git a/apps/docs/content/docs/guides/meta.json b/apps/docs/content/docs/guides/meta.json
index 6761466e6..cabcf3cc5 100644
--- a/apps/docs/content/docs/guides/meta.json
+++ b/apps/docs/content/docs/guides/meta.json
@@ -6,6 +6,7 @@
"batch",
"chromium-and-electron",
"headed-mode",
- "traces"
+ "traces",
+ "mcp"
]
}
diff --git a/scripts/check_architecture.py b/scripts/check_architecture.py
index 4a16ee124..3b9633a15 100644
--- a/scripts/check_architecture.py
+++ b/scripts/check_architecture.py
@@ -33,7 +33,7 @@ CORE_DOMAINS = {"actionability", "actions", "adapter", "commands", "context", "c
"locator", "notifications", "ref_action", "refs", "response", "session", "snapshot",
"storage", "system", "trace", "tree", "wait"}
BINARY_TOP_FILES = {"main.rs", "Cargo.toml"}
-BINARY_DIRS = {"batch", "cli", "cli_args", "command_policy", "diagnostic", "dispatch",
+BINARY_DIRS = {"batch", "cli", "cli_args", "command_policy", "diagnostic", "dispatch", "mcp",
"tests", "visual_debug"}
CAPABILITY_HOMES = {
"PlatformAdapter": ("adapter.rs",),
diff --git a/src/Cargo.toml b/src/Cargo.toml
index d24dcc062..94533fb05 100644
--- a/src/Cargo.toml
+++ b/src/Cargo.toml
@@ -18,6 +18,9 @@ tracing-subscriber.workspace = true
[target.'cfg(target_os = "macos")'.dependencies]
agent-desktop-macos = { path = "../crates/macos" }
+[target.'cfg(unix)'.dependencies]
+libc.workspace = true
+
[target.'cfg(target_os = "windows")'.dependencies]
agent-desktop-windows = { path = "../crates/windows" }
@@ -47,6 +50,10 @@ path = "tests/conformance.rs"
name = "cli_process"
path = "tests/cli_process.rs"
+[[test]]
+name = "mcp_process"
+path = "tests/mcp_process.rs"
+
[[test]]
name = "command_host_absent"
path = "tests/command_host_absent.rs"
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 2dd7cf023..2f9a8fdc5 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -80,9 +80,9 @@ pub(crate) enum Commands {
ScrollTo(RefArgs),
#[command(about = "Send a key combo: return, escape, cmd+c, shift+tab ...")]
Press(PressArgs),
- #[command(about = "Hold a key or modifier down")]
+ #[command(about = "Hold a key or modifier down (fails closed in stateless mode; use press)")]
KeyDown(KeyComboArgs),
- #[command(about = "Release a held key or modifier")]
+ #[command(about = "Release a held key or modifier (fails closed in stateless mode; use press)")]
KeyUp(KeyComboArgs),
#[command(about = "Move cursor to element center or coordinates (requires --headed)")]
Hover(HoverArgs),
diff --git a/src/diagnostic/mod.rs b/src/diagnostic/mod.rs
index 007acf428..bc4a155a2 100644
--- a/src/diagnostic/mod.rs
+++ b/src/diagnostic/mod.rs
@@ -1,7 +1,5 @@
pub(crate) fn clap_command_name(args: impl IntoIterator<Item = String>) -> String {
- use clap::CommandFactory;
-
- let command = crate::cli::Cli::command();
+ let command = crate::root_command();
let global_flags: Vec<_> = command
.get_arguments()
.filter(|arg| arg.is_global_set())
diff --git a/src/main.rs b/src/main.rs
index 788faee98..3e61f7f89 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -6,6 +6,7 @@ mod cli_args;
mod command_policy;
mod diagnostic;
mod dispatch;
+mod mcp;
mod visual_debug;
/// Shared blanket-default `PlatformAdapter` test double, sourced once from
@@ -22,7 +23,7 @@ use agent_desktop_core::{
response::output::{ErrorPayload, Response},
session::resolve_active_session,
};
-use clap::{CommandFactory, Parser};
+use clap::{CommandFactory, FromArgMatches};
use cli::{Cli, Commands};
use cli_args::skills::SkillsAction;
use std::io::{BufWriter, Write};
@@ -79,30 +80,16 @@ fn run() -> ExitCode {
agent_desktop_windows::WindowsPrivateFile,
));
- let mut cli = match Cli::try_parse() {
+ let matches = match root_command().try_get_matches() {
+ Ok(matches) => matches,
+ Err(e) => return report_parse_failure(e),
+ };
+ if let Some(("mcp", mcp_matches)) = matches.subcommand() {
+ return mcp::serve(mcp_matches);
+ }
+ let mut cli = match Cli::from_arg_matches(&matches) {
Ok(c) => c,
- Err(e) => {
- if matches!(
- e.kind(),
- clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion
- ) {
- return match e.print() {
- Ok(()) => ExitCode::SUCCESS,
- Err(write_err) => report_output_failure(write_err),
- };
- }
- let summary = diagnostic::clap_error_summary(&e.to_string());
- let error = AppError::invalid_input(diagnostic::bounded_text(&summary, 512));
- let command_name = diagnostic::clap_command_name(std::env::args().skip(1));
- return if let Err(write_err) = emit_response(&Response::err(
- &command_name,
- ErrorPayload::from_app_error(&error),
- )) {
- report_output_failure(write_err)
- } else {
- ExitCode::from(EXIT_INVALID_ARGS)
- };
- }
+ Err(e) => return report_parse_failure(e),
};
init_tracing(cli.visual_debug.verbose);
@@ -110,7 +97,7 @@ fn run() -> ExitCode {
let cmd = match cli.command.take() {
Some(c) => c,
None => {
- return match Cli::command().print_help() {
+ return match root_command().print_help() {
Ok(()) => ExitCode::SUCCESS,
Err(write_err) => report_output_failure(write_err),
};
@@ -121,6 +108,34 @@ fn run() -> ExitCode {
finish(cmd_name, execute(cli, cmd))
}
+/// The parsed command tree: every `Commands` variant plus `mcp`, which serves them.
+fn root_command() -> clap::Command {
+ Cli::command().subcommand(mcp::command())
+}
+
+fn report_parse_failure(e: clap::Error) -> ExitCode {
+ if matches!(
+ e.kind(),
+ clap::error::ErrorKind::DisplayHelp | clap::error::ErrorKind::DisplayVersion
+ ) {
+ return match e.print() {
+ Ok(()) => ExitCode::SUCCESS,
+ Err(write_err) => report_output_failure(write_err),
+ };
+ }
+ let summary = diagnostic::clap_error_summary(&e.to_string());
+ let error = AppError::invalid_input(diagnostic::bounded_text(&summary, 512));
+ let command_name = diagnostic::clap_command_name(std::env::args().skip(1));
+ if let Err(write_err) = emit_response(&Response::err(
+ &command_name,
+ ErrorPayload::from_app_error(&error),
+ )) {
+ report_output_failure(write_err)
+ } else {
+ ExitCode::from(EXIT_INVALID_ARGS)
+ }
+}
+
fn execute(cli: Cli, cmd: Commands) -> Result<serde_json::Value, AppError> {
execute_with_deadline(cli, cmd, None, None)
}
diff --git a/src/mcp/call.rs b/src/mcp/call.rs
new file mode 100644
index 000000000..fd5818800
--- /dev/null
+++ b/src/mcp/call.rs
@@ -0,0 +1,96 @@
+//! Runs one tool call as a child process of this same binary and maps its JSON envelope to an MCP result.
+
+use serde_json::{Map, Value, json};
+use std::io::Read;
+use std::process::{Command, Stdio};
+
+use super::calls::Calls;
+use super::catalog::Tool;
+
+const CANCELLED: &str = "Cancelled";
+
+/// Runs `tool` with `arguments` for request `id`, prefixed by the server's own global flags, and returns a
+/// `CallToolResult`. A cancelled call returns early; the caller sends no response for it.
+pub(crate) fn call(
+ tool: &Tool,
+ arguments: &Map<String, Value>,
+ globals: &[String],
+ calls: &Calls,
+ id: &Value,
+) -> Value {
+ let argv = match tool.argv(arguments) {
+ Ok(argv) => argv,
+ Err(message) => return error_result(&message),
+ };
+ let exe = match std::env::current_exe() {
+ Ok(exe) => exe,
+ Err(error) => return error_result(&format!("Cannot locate agent-desktop: {error}")),
+ };
+ let mut command = Command::new(exe);
+ command
+ .args(globals)
+ .args(&argv)
+ .stdin(Stdio::null())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ let (stdout, stderr) = match calls.start(id, &mut command) {
+ None => return error_result(CANCELLED),
+ Some(Err(error)) => return error_result(&format!("Cannot run agent-desktop: {error}")),
+ Some(Ok(pipes)) => pipes,
+ };
+ let (stdout, stderr) = std::thread::scope(|scope| {
+ let stderr = scope.spawn(|| read_all(stderr));
+ (read_all(stdout), stderr.join().unwrap_or_default())
+ });
+ let Some(mut child) = calls.take(id) else {
+ return error_result(CANCELLED);
+ };
+ let status = child
+ .wait()
+ .map_or_else(|error| error.to_string(), |status| status.to_string());
+ match serde_json::from_slice::<Value>(&stdout) {
+ Ok(envelope) => envelope_result(envelope),
+ Err(_) => error_result(&format!(
+ "agent-desktop {} exited with {status} and no JSON envelope: {}",
+ tool.path.join(" "),
+ String::from_utf8_lossy(&stderr).trim()
+ )),
+ }
+}
+
+fn read_all(pipe: Option<impl Read>) -> Vec<u8> {
+ let mut bytes = Vec::new();
+ if let Some(mut pipe) = pipe {
+ let _ = pipe.read_to_end(&mut bytes);
+ }
+ bytes
+}
+
+/// Maps an envelope to a result: the envelope as structured content and text, an image block for inline screenshots.
+pub(crate) fn envelope_result(mut envelope: Value) -> Value {
+ let is_error = envelope["ok"] != Value::Bool(true);
+ let image = take_inline_image(&mut envelope);
+ let mut content = vec![json!({ "type": "text", "text": envelope.to_string() })];
+ content.extend(image);
+ json!({ "content": content, "structuredContent": envelope, "isError": is_error })
+}
+
+fn take_inline_image(envelope: &mut Value) -> Option<Value> {
+ let data = envelope.get_mut("data")?.as_object_mut()?;
+ let mime_type = match data.get("format")?.as_str()? {
+ "png" => "image/png",
+ "jpg" | "jpeg" => "image/jpeg",
+ _ => return None,
+ };
+ if !data.get("data").is_some_and(Value::is_string) {
+ return None;
+ }
+ let Value::String(encoded) = data.remove("data")? else {
+ return None;
+ };
+ Some(json!({ "type": "image", "data": encoded, "mimeType": mime_type }))
+}
+
+fn error_result(message: &str) -> Value {
+ json!({ "content": [{ "type": "text", "text": message }], "isError": true })
+}
diff --git a/src/mcp/calls.rs b/src/mcp/calls.rs
new file mode 100644
index 000000000..e05b86940
--- /dev/null
+++ b/src/mcp/calls.rs
@@ -0,0 +1,99 @@
+//! Tool calls in flight, keyed by JSON-RPC request id, so `notifications/cancelled` can stop one.
+
+use serde_json::Value;
+use std::collections::{HashMap, hash_map::Entry};
+use std::io;
+use std::process::{Child, ChildStderr, ChildStdout, Command};
+use std::sync::{Mutex, MutexGuard, PoisonError};
+use std::time::{Duration, Instant};
+
+const TERMINATE_GRACE: Duration = Duration::from_secs(3);
+const EXIT_POLL: Duration = Duration::from_millis(20);
+
+/// Output pipes of a started call.
+pub(crate) type Pipes = (Option<ChildStdout>, Option<ChildStderr>);
+
+/// Each admitted request id, with the child process its call started once it has started one.
+#[derive(Default)]
+pub(crate) struct Calls(Mutex<HashMap<String, Option<Child>>>);
+
+impl Calls {
+ /// Admits `id` before its call starts; false when a call with that id is already in flight.
+ pub(crate) fn admit(&self, id: &Value) -> bool {
+ match self.lock().entry(id.to_string()) {
+ Entry::Occupied(_) => false,
+ Entry::Vacant(entry) => {
+ entry.insert(None);
+ true
+ }
+ }
+ }
+
+ /// Spawns `command` for `id` and returns its pipes, or `None` when `id` is not admitted or was cancelled.
+ /// The registry stays locked while the child spawns, so a cancel lands either before it, and nothing
+ /// starts, or after it, and the child is killed.
+ pub(crate) fn start(&self, id: &Value, command: &mut Command) -> Option<io::Result<Pipes>> {
+ let mut calls = self.lock();
+ let slot = calls.get_mut(&id.to_string())?;
+ Some(command.spawn().map(|mut child| {
+ let pipes = (child.stdout.take(), child.stderr.take());
+ *slot = Some(child);
+ pipes
+ }))
+ }
+
+ /// Takes back the child of `id` after its output closed, or `None` when `id` was cancelled.
+ pub(crate) fn take(&self, id: &Value) -> Option<Child> {
+ self.lock().get_mut(&id.to_string()).and_then(Option::take)
+ }
+
+ /// Cancels `id`; an unknown id is ignored. A started child is stopped on its own thread by `terminate`.
+ pub(crate) fn cancel(&self, id: &Value) {
+ let child = self.lock().remove(&id.to_string()).flatten();
+ if let Some(child) = child {
+ std::thread::spawn(move || terminate(child));
+ }
+ }
+
+ /// Releases `id` once its call has returned; false when it was cancelled, so no response is due.
+ pub(crate) fn finish(&self, id: &Value) -> bool {
+ self.lock().remove(&id.to_string()).is_some()
+ }
+
+ fn lock(&self) -> MutexGuard<'_, HashMap<String, Option<Child>>> {
+ self.0.lock().unwrap_or_else(PoisonError::into_inner)
+ }
+}
+
+/// Asks `child` to exit with SIGTERM, which lets the CLI release held keys and buttons first (it waits up to
+/// 2 s for that on Linux), and kills it if it is still running after `TERMINATE_GRACE`. Without SIGTERM
+/// (Windows) it kills at once.
+fn terminate(mut child: Child) {
+ if request_exit(&child) {
+ let deadline = Instant::now() + TERMINATE_GRACE;
+ while Instant::now() < deadline {
+ match child.try_wait() {
+ Ok(Some(_)) => return,
+ Ok(None) => std::thread::sleep(EXIT_POLL),
+ Err(_) => break,
+ }
+ }
+ }
+ let _ = child.kill();
+ let _ = child.wait();
+}
+
+#[cfg(unix)]
+fn request_exit(child: &Child) -> bool {
+ libc::pid_t::try_from(child.id())
+ .is_ok_and(|pid| unsafe { libc::kill(pid, libc::SIGTERM) } == 0)
+}
+
+#[cfg(not(unix))]
+fn request_exit(_child: &Child) -> bool {
+ false
+}
+
+#[cfg(test)]
+#[path = "calls_tests.rs"]
+mod tests;
diff --git a/src/mcp/calls_tests.rs b/src/mcp/calls_tests.rs
new file mode 100644
index 000000000..d11584c18
--- /dev/null
+++ b/src/mcp/calls_tests.rs
@@ -0,0 +1,54 @@
+use super::*;
+use serde_json::json;
+
+fn unspawnable() -> Command {
+ Command::new("agent-desktop-calls-test-binary-that-does-not-exist")
+}
+
+#[test]
+fn an_id_is_admitted_once_until_its_call_finishes() {
+ let calls = Calls::default();
+ assert!(calls.admit(&json!(1)));
+ assert!(!calls.admit(&json!(1)));
+ assert!(calls.admit(&json!("1")));
+ assert!(calls.finish(&json!(1)));
+ assert!(calls.admit(&json!(1)));
+}
+
+#[test]
+fn a_call_cancelled_before_it_starts_never_spawns_and_gets_no_response() {
+ let calls = Calls::default();
+ assert!(calls.admit(&json!(7)));
+ calls.cancel(&json!(7));
+ assert!(calls.start(&json!(7), &mut unspawnable()).is_none());
+ assert!(!calls.finish(&json!(7)));
+}
+
+#[cfg(unix)]
+#[test]
+fn a_cancelled_child_gets_sigterm_before_any_kill() {
+ use std::io::Read;
+ use std::process::Stdio;
+
+ let calls = Calls::default();
+ let id = json!(3);
+ assert!(calls.admit(&id));
+ let mut command = Command::new("sh");
+ command
+ .args([
+ "-c",
+ "trap 'echo released; exit 0' TERM; echo started; while :; do sleep 0.05; done",
+ ])
+ .stdout(Stdio::piped());
+ let (stdout, _) = calls
+ .start(&id, &mut command)
+ .expect("admitted")
+ .expect("sh starts");
+ let mut stdout = stdout.expect("stdout is piped");
+ let mut started = [0_u8; 8];
+ stdout.read_exact(&mut started).expect("child started");
+ calls.cancel(&id);
+ let mut rest = String::new();
+ stdout.read_to_string(&mut rest).expect("child exits");
+ assert_eq!(rest, "released\n");
+}
diff --git a/src/mcp/catalog.rs b/src/mcp/catalog.rs
new file mode 100644
index 000000000..b4a2a69e6
--- /dev/null
+++ b/src/mcp/catalog.rs
@@ -0,0 +1,257 @@
+//! MCP tools derived from the clap command tree, so the CLI stays the only definition of a command.
+
+use clap::{Arg, ArgAction, Command, CommandFactory};
+use serde_json::{Map, Value, json};
+use std::any::TypeId;
+
+use crate::cli::Cli;
+
+const TOOL_PREFIX: &str = "desktop";
+const CLAP_HELP_SUBCOMMAND: &str = "help";
+const MAX_COUNT: u64 = 16;
+
+/// One leaf CLI command exposed as an MCP tool.
+pub(crate) struct Tool {
+ pub name: String,
+ pub path: Vec<String>,
+ command: Command,
+}
+
+/// Every leaf command of the CLI, in declaration order.
+pub(crate) fn tools() -> Vec<Tool> {
+ let mut root = Cli::command();
+ root.build();
+ let mut found = Vec::new();
+ for sub in commands(&root) {
+ collect(sub, Vec::new(), &mut found);
+ }
+ found
+}
+
+fn commands(parent: &Command) -> impl Iterator<Item = &Command> {
+ parent
+ .get_subcommands()
+ .filter(|sub| sub.get_name() != CLAP_HELP_SUBCOMMAND)
+}
+
+fn collect(command: &Command, mut path: Vec<String>, found: &mut Vec<Tool>) {
+ path.push(command.get_name().to_string());
+ if command.has_subcommands() {
+ for sub in commands(command) {
+ collect(sub, path.clone(), found);
+ }
+ return;
+ }
+ let name = std::iter::once(TOOL_PREFIX)
+ .chain(path.iter().map(String::as_str))
+ .collect::<Vec<_>>()
+ .join("_")
+ .replace('-', "_");
+ found.push(Tool {
+ name,
+ path,
+ command: command.clone(),
+ });
+}
+
+impl Tool {
+ /// The MCP `Tool` object advertised by `tools/list`.
+ pub(crate) fn definition(&self) -> Value {
+ let mut properties = Map::new();
+ let mut required = Vec::new();
+ for arg in self.args() {
+ properties.insert(property_name(arg), property(arg));
+ if arg.is_required_set() {
+ required.push(Value::from(property_name(arg)));
+ }
+ }
+ let mut schema =
+ json!({ "type": "object", "properties": properties, "additionalProperties": false });
+ if !required.is_empty() {
+ schema["required"] = Value::Array(required);
+ }
+ json!({ "name": self.name, "description": self.description(), "inputSchema": schema })
+ }
+
+ /// Builds the CLI arguments, after the binary name, that run this command with `arguments`; a null value counts as omitted.
+ pub(crate) fn argv(&self, arguments: &Map<String, Value>) -> Result<Vec<String>, String> {
+ let mut argv = self.path.clone();
+ let mut positionals = Vec::new();
+ for (key, value) in arguments.iter().filter(|(_, value)| !value.is_null()) {
+ let arg = self
+ .args()
+ .find(|arg| property_name(arg) == *key)
+ .ok_or_else(|| self.unknown_argument(key))?;
+ if arg.is_positional() {
+ positionals.push((arg.get_index().unwrap_or(usize::MAX), scalars(key, value)?));
+ } else {
+ push_option(&mut argv, arg, key, value)?;
+ }
+ }
+ if !positionals.is_empty() {
+ positionals.sort_by_key(|(index, _)| *index);
+ argv.push("--".to_string());
+ argv.extend(positionals.into_iter().flat_map(|(_, values)| values));
+ }
+ Ok(argv)
+ }
+
+ fn args(&self) -> impl Iterator<Item = &Arg> {
+ self.command.get_arguments().filter(|arg| {
+ !arg.is_global_set()
+ && !arg.is_hide_set()
+ && !matches!(
+ arg.get_action(),
+ ArgAction::Help
+ | ArgAction::HelpShort
+ | ArgAction::HelpLong
+ | ArgAction::Version
+ )
+ })
+ }
+
+ fn description(&self) -> String {
+ let about = self
+ .command
+ .get_long_about()
+ .or_else(|| self.command.get_about())
+ .map(ToString::to_string)
+ .unwrap_or_default();
+ format!("agent-desktop {}: {about}", self.path.join(" "))
+ }
+
+ fn unknown_argument(&self, key: &str) -> String {
+ let known = self.args().map(property_name).collect::<Vec<_>>();
+ format!(
+ "Unknown argument '{key}' for {}. Known arguments: {}",
+ self.name,
+ known.join(", ")
+ )
+ }
+}
+
+fn property_name(arg: &Arg) -> String {
+ arg.get_id().as_str().replace('-', "_")
+}
+
+fn push_option(argv: &mut Vec<String>, arg: &Arg, key: &str, value: &Value) -> Result<(), String> {
+ let flag = arg
+ .get_long()
+ .map(|long| format!("--{long}"))
+ .or_else(|| arg.get_short().map(|short| format!("-{short}")))
+ .ok_or_else(|| format!("Argument '{key}' has no flag"))?;
+ match arg.get_action() {
+ ArgAction::SetTrue | ArgAction::SetFalse => match value {
+ Value::Bool(true) => argv.push(flag),
+ Value::Bool(false) => {}
+ _ => return Err(format!("Argument '{key}' must be a boolean")),
+ },
+ ArgAction::Count => {
+ let count = value
+ .as_u64()
+ .filter(|count| *count <= MAX_COUNT)
+ .ok_or_else(|| {
+ format!("Argument '{key}' must be an integer from 0 to {MAX_COUNT}")
+ })?;
+ argv.extend((0..count).map(|_| flag.clone()));
+ }
+ _ => {
+ for scalar in scalars(key, value)? {
+ argv.push(format!("{flag}={scalar}"));
+ }
+ }
+ }
+ Ok(())
+}
+
+fn scalars(key: &str, value: &Value) -> Result<Vec<String>, String> {
+ let items = match value {
+ Value::Array(items) => items.iter().collect(),
+ other => vec![other],
+ };
+ items
+ .into_iter()
+ .map(|item| match item {
+ Value::String(text) => Ok(text.clone()),
+ Value::Number(number) => Ok(number.to_string()),
+ Value::Bool(flag) => Ok(flag.to_string()),
+ _ => Err(format!(
+ "Argument '{key}' must be a string, number, boolean or an array of them"
+ )),
+ })
+ .collect()
+}
+
+fn property(arg: &Arg) -> Value {
+ let mut schema = match arg.get_action() {
+ ArgAction::SetTrue | ArgAction::SetFalse => json!({ "type": "boolean" }),
+ ArgAction::Count => json!({ "type": "integer", "minimum": 0, "maximum": MAX_COUNT }),
+ _ => value_schema(arg),
+ };
+ if let Some(help) = arg.get_long_help().or_else(|| arg.get_help()) {
+ schema["description"] = Value::from(help.to_string());
+ }
+ schema
+}
+
+fn value_schema(arg: &Arg) -> Value {
+ let mut item = json!({ "type": json_type(arg) });
+ let choices = arg
+ .get_possible_values()
+ .iter()
+ .filter(|value| !value.is_hide_set())
+ .map(|value| Value::from(value.get_name()))
+ .collect::<Vec<_>>();
+ if !choices.is_empty() {
+ item["enum"] = Value::Array(choices);
+ }
+ if let [default] = arg.get_default_values() {
+ let default = default.to_string_lossy();
+ let typed = match item["type"].as_str() {
+ Some("integer") => default.parse::<i64>().ok().map(Value::from),
+ Some("number") => default.parse::<f64>().ok().map(Value::from),
+ _ => Some(Value::from(default.as_ref())),
+ };
+ if let Some(typed) = typed {
+ item["default"] = typed;
+ }
+ }
+ let multiple = matches!(arg.get_action(), ArgAction::Append)
+ || arg
+ .get_num_args()
+ .is_some_and(|range| range.max_values() > 1);
+ if multiple {
+ json!({ "type": "array", "items": item })
+ } else {
+ item
+ }
+}
+
+fn json_type(arg: &Arg) -> &'static str {
+ let id = arg.get_value_parser().type_id();
+ let is = |types: &[TypeId]| types.iter().any(|type_id| id == *type_id);
+ if is(&[TypeId::of::<bool>()]) {
+ "boolean"
+ } else if is(&[
+ TypeId::of::<u8>(),
+ TypeId::of::<u16>(),
+ TypeId::of::<u32>(),
+ TypeId::of::<u64>(),
+ TypeId::of::<usize>(),
+ TypeId::of::<i8>(),
+ TypeId::of::<i16>(),
+ TypeId::of::<i32>(),
+ TypeId::of::<i64>(),
+ TypeId::of::<isize>(),
+ ]) {
+ "integer"
+ } else if is(&[TypeId::of::<f32>(), TypeId::of::<f64>()]) {
+ "number"
+ } else {
+ "string"
+ }
+}
+
+#[cfg(test)]
+#[path = "catalog_tests.rs"]
+mod tests;
diff --git a/src/mcp/catalog_tests.rs b/src/mcp/catalog_tests.rs
new file mode 100644
index 000000000..5214a4861
--- /dev/null
+++ b/src/mcp/catalog_tests.rs
@@ -0,0 +1,170 @@
+use super::*;
+use clap::Parser;
+use clap::error::ErrorKind;
+
+fn sample(schema: &Value) -> Value {
+ let item = if schema["type"] == "array" {
+ &schema["items"]
+ } else {
+ schema
+ };
+ let value = match (item["type"].as_str(), item["enum"].get(0)) {
+ (_, Some(first)) => first.clone(),
+ (Some("boolean"), _) => Value::Bool(true),
+ (Some("integer" | "number"), _) => Value::from(1),
+ _ => Value::from("x"),
+ };
+ if schema["type"] == "array" {
+ Value::Array(vec![value])
+ } else {
+ value
+ }
+}
+
+fn parse(tool: &Tool, arguments: &Map<String, Value>) -> Result<Cli, clap::Error> {
+ let argv = tool
+ .argv(arguments)
+ .expect("schema-shaped arguments build argv");
+ Cli::try_parse_from(std::iter::once("agent-desktop".to_string()).chain(argv))
+}
+
+#[test]
+fn every_schema_property_is_accepted_by_the_cli_parser() {
+ let mut checked = 0;
+ for tool in tools() {
+ let definition = tool.definition();
+ let properties = definition["inputSchema"]["properties"]
+ .as_object()
+ .expect("properties")
+ .clone();
+ for (key, schema) in &properties {
+ let mut arguments = Map::new();
+ arguments.insert(key.clone(), sample(schema));
+ let Err(error) = parse(&tool, &arguments) else {
+ checked += 1;
+ continue;
+ };
+ let plain_string = schema["type"] == "string" && schema.get("enum").is_none();
+ let tolerated = matches!(
+ error.kind(),
+ ErrorKind::MissingRequiredArgument | ErrorKind::ArgumentConflict
+ ) || (plain_string && error.kind() == ErrorKind::ValueValidation);
+ assert!(
+ tolerated,
+ "{} rejected its own schema property '{key}': {error}",
+ tool.name
+ );
+ checked += 1;
+ }
+ }
+ assert!(checked > 100, "only {checked} properties were checked");
+}
+
+#[test]
+fn every_tool_runs_the_command_it_is_named_after() {
+ for tool in tools() {
+ let error = match parse(&tool, &Map::new()) {
+ Ok(cli) => {
+ let command = cli.command.expect("a command");
+ assert_eq!(command.name(), tool.path[0], "{}", tool.name);
+ continue;
+ }
+ Err(error) => error,
+ };
+ assert!(
+ error.kind() == ErrorKind::MissingRequiredArgument,
+ "{} failed to parse with no arguments: {error}",
+ tool.name
+ );
+ }
+}
+
+#[test]
+fn tool_names_are_unique_and_valid_for_every_major_client() {
+ let names = tools()
+ .into_iter()
+ .map(|tool| tool.name)
+ .collect::<Vec<_>>();
+ let unique = names.iter().collect::<std::collections::BTreeSet<_>>();
+ assert_eq!(unique.len(), names.len(), "duplicate tool names: {names:?}");
+ for name in &names {
+ assert!(
+ name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),
+ "{name} is not a portable tool name"
+ );
+ }
+}
+
+#[test]
+fn unknown_arguments_and_wrong_types_are_reported_not_passed_through() {
+ let tool = tools()
+ .into_iter()
+ .find(|tool| tool.path == ["skills", "get"])
+ .expect("skills get tool");
+ let mut arguments = Map::new();
+ arguments.insert("name".into(), Value::from("desktop"));
+ arguments.insert("full".into(), Value::from(true));
+ arguments.insert("reference".into(), Value::Null);
+ assert_eq!(
+ tool.argv(&arguments).unwrap(),
+ ["skills", "get", "--full", "--", "desktop"]
+ );
+ arguments.insert("full".into(), Value::from("yes"));
+ assert!(tool.argv(&arguments).unwrap_err().contains("boolean"));
+ arguments.remove("full");
+ arguments.insert("headed".into(), Value::from(true));
+ assert!(
+ tool.argv(&arguments)
+ .unwrap_err()
+ .contains("Unknown argument 'headed'")
+ );
+}
+
+fn tool_at(path: &[&str]) -> Tool {
+ tools()
+ .into_iter()
+ .find(|tool| tool.path == path)
+ .expect("tool exists")
+}
+
+#[test]
+fn flag_shaped_values_stay_values_and_never_become_flags() {
+ let hostile = "--headed --trace=/tmp/owned -- --session=x";
+ let mut arguments = Map::new();
+ arguments.insert("app".into(), Value::from(hostile));
+ let cli = parse(&tool_at(&["snapshot"]), &arguments).expect("parses");
+ assert!(!cli.interaction.headed && cli.trace.is_none() && cli.identity.session.is_none());
+ let Some(crate::cli::Commands::Snapshot(snapshot)) = cli.command else {
+ panic!("snapshot");
+ };
+ assert_eq!(snapshot.scope.app.as_deref(), Some(hostile));
+
+ let mut arguments = Map::new();
+ arguments.insert("ref_id".into(), Value::from("@s8f3k2p9:e1"));
+ arguments.insert("text".into(), Value::from(hostile));
+ let cli = parse(&tool_at(&["type"]), &arguments).expect("parses");
+ assert!(!cli.interaction.headed && cli.trace.is_none() && cli.identity.session.is_none());
+ let Some(crate::cli::Commands::Type(typed)) = cli.command else {
+ panic!("type");
+ };
+ assert_eq!(typed.text, hostile);
+}
+
+#[test]
+fn global_flags_cannot_be_set_per_call() {
+ let tool = tool_at(&["snapshot"]);
+ for global in [
+ "headed",
+ "session",
+ "agent_id",
+ "trace",
+ "trace_strict",
+ "wait_for",
+ "debug",
+ ] {
+ let mut arguments = Map::new();
+ arguments.insert(global.into(), Value::from("x"));
+ let error = tool.argv(&arguments).expect_err(global);
+ assert!(error.contains("Unknown argument"), "{global}: {error}");
+ }
+}
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
new file mode 100644
index 000000000..f1318ae18
--- /dev/null
+++ b/src/mcp/mod.rs
@@ -0,0 +1,305 @@
+//! Stdio MCP server. Every leaf CLI command is one tool, and every call runs that command through the CLI.
+
+mod call;
+mod calls;
+mod catalog;
+
+use clap::{ArgAction, ArgMatches, Command, CommandFactory, parser::ValueSource};
+use serde_json::{Map, Value, json};
+use std::io::{BufRead, Write};
+use std::process::ExitCode;
+use std::sync::{Arc, Mutex};
+
+use crate::cli::Cli;
+
+const MODERN_VERSION: &str = "2026-07-28";
+const LEGACY_VERSIONS: &[&str] = &["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"];
+const PROTOCOL_VERSION_META: &str = "io.modelcontextprotocol/protocolVersion";
+const SERVER_INFO_META: &str = "io.modelcontextprotocol/serverInfo";
+const TOOLS_TTL_MS: u64 = 86_400_000;
+const MAX_CONCURRENT_CALLS: usize = 8;
+const MAX_MESSAGE_BYTES: usize = 4 * 1024 * 1024;
+const INSTRUCTIONS: &str = "\
+agent-desktop reads native accessibility trees and operates desktop apps. Each tool runs the \
+agent-desktop CLI command of the same name and returns its JSON envelope: ok with data, or ok \
+false with error; a call rejected before the command runs returns plain text. Read \
+desktop_skills_get with name \"desktop\" first for the observe-act loop, and with name \
+\"platform\" for what differs on this OS. The skills use CLI syntax: `agent-desktop snapshot \
+--app Finder` is desktop_snapshot with {\"app\": \"Finder\"}, and the input schema replaces \
+--help. Global flags (--session, --agent-id, --headed, --wait-for, --trace) are fixed \
+by how this server was started and cannot be passed per call. Refs such as @s8f3k2p9:e1 come from \
+desktop_snapshot and go stale when the UI changes: on STALE_REF or AMBIGUOUS_TARGET, snapshot \
+again. Repeat an action only when its disposition.retry is \"safe\".";
+
+/// The `mcp` subcommand; it lives outside `Commands` because it serves commands rather than being one.
+pub(crate) fn command() -> Command {
+ Command::new("mcp").about(
+ "Serve every command as an MCP tool over stdio; global flags given here apply to every call",
+ )
+}
+
+/// Serves MCP over stdin and stdout until stdin closes, then finishes the tool calls already running.
+/// At most `MAX_CONCURRENT_CALLS` calls run at once, and a message longer than `MAX_MESSAGE_BYTES` is refused unread.
+pub(crate) fn serve(matches: &ArgMatches) -> ExitCode {
+ let server = Arc::new(Server {
+ tools: catalog::tools(),
+ globals: forwarded_globals(matches),
+ calls: calls::Calls::default(),
+ });
+ let out = Arc::new(Mutex::new(std::io::stdout()));
+ let mut input = std::io::stdin().lock();
+ let mut running = Vec::new();
+ while let Some(line) = read_message(&mut input) {
+ let message = match line.map(|line| serde_json::from_slice::<Value>(&line)) {
+ Ok(Ok(message)) if message.is_object() => message,
+ Ok(Ok(_)) => {
+ let error = RpcError::new(-32600, "Invalid Request: expected one JSON-RPC object");
+ write_line(&out, &error.response(Value::Null));
+ continue;
+ }
+ Ok(Err(error)) => {
+ let error = RpcError::new(-32700, format!("Parse error: {error}"));
+ write_line(&out, &error.response(Value::Null));
+ continue;
+ }
+ Err(error) => {
+ write_line(&out, &error.response(Value::Null));
+ continue;
+ }
+ };
+ let server = Arc::clone(&server);
+ let out = Arc::clone(&out);
+ if message["method"] != "tools/call" {
+ server.respond(&out, &message);
+ continue;
+ }
+ running.retain(|call: &std::thread::JoinHandle<()>| !call.is_finished());
+ if running.len() >= MAX_CONCURRENT_CALLS {
+ server.respond_busy(&out, &message);
+ continue;
+ }
+ if let Some(id) = message.get("id") {
+ if !server.calls.admit(id) {
+ let error =
+ RpcError::new(-32600, "Invalid Request: a call with this id is running");
+ write_line(&out, &error.response(id.clone()));
+ continue;
+ }
+ }
+ running.push(std::thread::spawn(move || server.respond(&out, &message)));
+ }
+ for call in running {
+ let _ = call.join();
+ }
+ ExitCode::SUCCESS
+}
+
+fn read_message(input: &mut impl BufRead) -> Option<Result<Vec<u8>, RpcError>> {
+ let mut line = Vec::new();
+ loop {
+ line.clear();
+ let limit = u64::try_from(MAX_MESSAGE_BYTES).unwrap_or(u64::MAX) + 1;
+ let read = std::io::Read::take(&mut *input, limit)
+ .read_until(b'\n', &mut line)
+ .ok()?;
+ if read == 0 {
+ return None;
+ }
+ if line.len() > MAX_MESSAGE_BYTES && line.last() != Some(&b'\n') {
+ input.skip_until(b'\n').ok()?;
+ return Some(Err(RpcError::new(
+ -32600,
+ format!("Invalid Request: message exceeds {MAX_MESSAGE_BYTES} bytes"),
+ )));
+ }
+ if !line.trim_ascii().is_empty() {
+ return Some(Ok(line));
+ }
+ }
+}
+
+struct Server {
+ tools: Vec<catalog::Tool>,
+ globals: Vec<String>,
+ calls: calls::Calls,
+}
+
+impl Server {
+ fn respond(&self, out: &Mutex<std::io::Stdout>, message: &Value) {
+ if message["method"] == "notifications/cancelled" {
+ if let Some(id) = message["params"].get("requestId") {
+ self.calls.cancel(id);
+ }
+ return;
+ }
+ let Some(id) = message.get("id").cloned() else {
+ return;
+ };
+ let method = message["method"].as_str().unwrap_or_default();
+ let params = message.get("params").cloned().unwrap_or_else(|| json!({}));
+ let result = self.handle(&id, method, &params);
+ if method == "tools/call" && !self.calls.finish(&id) {
+ return;
+ }
+ let response = match result {
+ Ok(result) => json!({ "jsonrpc": "2.0", "id": id, "result": result }),
+ Err(error) => error.response(id),
+ };
+ write_line(out, &response);
+ }
+
+ fn respond_busy(&self, out: &Mutex<std::io::Stdout>, message: &Value) {
+ let Some(id) = message.get("id").cloned() else {
+ return;
+ };
+ let text = format!(
+ "{MAX_CONCURRENT_CALLS} tool calls are already running; retry when one finishes"
+ );
+ let result = json!({
+ "content": [{ "type": "text", "text": text }],
+ "isError": true,
+ "resultType": "complete",
+ });
+ write_line(
+ out,
+ &json!({ "jsonrpc": "2.0", "id": id, "result": result }),
+ );
+ }
+
+ fn handle(&self, id: &Value, method: &str, params: &Value) -> Result<Value, RpcError> {
+ if let Some(requested) = params["_meta"][PROTOCOL_VERSION_META].as_str() {
+ if requested != MODERN_VERSION {
+ return Err(
+ RpcError::new(-32022, "Unsupported protocol version").with_data(
+ json!({ "supported": supported_versions(), "requested": requested }),
+ ),
+ );
+ }
+ }
+ let mut result = match method {
+ "initialize" => initialize(params),
+ "server/discover" => json!({
+ "supportedVersions": supported_versions(),
+ "capabilities": { "tools": {} },
+ "instructions": INSTRUCTIONS,
+ "ttlMs": TOOLS_TTL_MS,
+ "cacheScope": "public",
+ }),
+ "ping" => json!({}),
+ "tools/list" => json!({
+ "tools": self.tools.iter().map(catalog::Tool::definition).collect::<Vec<_>>(),
+ "ttlMs": TOOLS_TTL_MS,
+ "cacheScope": "public",
+ }),
+ "tools/call" => self.call(id, params)?,
+ other => return Err(RpcError::new(-32601, format!("Method not found: {other}"))),
+ };
+ result["resultType"] = Value::from("complete");
+ result["_meta"] = json!({ SERVER_INFO_META: server_info() });
+ Ok(result)
+ }
+
+ fn call(&self, id: &Value, params: &Value) -> Result<Value, RpcError> {
+ let name = params["name"]
+ .as_str()
+ .ok_or_else(|| RpcError::new(-32602, "tools/call requires a tool name"))?;
+ let tool = self
+ .tools
+ .iter()
+ .find(|tool| tool.name == name)
+ .ok_or_else(|| RpcError::new(-32602, format!("Unknown tool: {name}")))?;
+ let arguments = match params.get("arguments") {
+ None | Some(Value::Null) => Map::new(),
+ Some(Value::Object(arguments)) => arguments.clone(),
+ Some(_) => return Err(RpcError::new(-32602, "Tool arguments must be an object")),
+ };
+ Ok(call::call(tool, &arguments, &self.globals, &self.calls, id))
+ }
+}
+
+fn initialize(params: &Value) -> Value {
+ let version = params["protocolVersion"]
+ .as_str()
+ .and_then(|requested| LEGACY_VERSIONS.iter().find(|known| **known == requested))
+ .unwrap_or(&LEGACY_VERSIONS[0]);
+ json!({
+ "protocolVersion": version,
+ "capabilities": { "tools": {} },
+ "serverInfo": server_info(),
+ "instructions": INSTRUCTIONS,
+ })
+}
+
+fn supported_versions() -> Vec<&'static str> {
+ std::iter::once(MODERN_VERSION)
+ .chain(LEGACY_VERSIONS.iter().copied())
+ .collect()
+}
+
+fn server_info() -> Value {
+ json!({ "name": "agent-desktop", "version": env!("CARGO_PKG_VERSION") })
+}
+
+fn forwarded_globals(matches: &ArgMatches) -> Vec<String> {
+ let root = Cli::command();
+ let mut globals = Vec::new();
+ for arg in root.get_arguments().filter(|arg| arg.is_global_set()) {
+ let id = arg.get_id().as_str();
+ let Some(long) = arg.get_long() else { continue };
+ if matches.value_source(id) != Some(ValueSource::CommandLine) {
+ continue;
+ }
+ if matches!(arg.get_action(), ArgAction::SetTrue) {
+ globals.push(format!("--{long}"));
+ } else if let Some(values) = matches.get_raw(id) {
+ globals.extend(values.map(|value| format!("--{long}={}", value.to_string_lossy())));
+ }
+ }
+ globals
+}
+
+fn write_line(out: &Mutex<std::io::Stdout>, message: &Value) {
+ let Ok(mut out) = out.lock() else { return };
+ let mut line = message.to_string();
+ line.push('\n');
+ if out
+ .write_all(line.as_bytes())
+ .and_then(|()| out.flush())
+ .is_err()
+ {
+ eprintln!("agent-desktop mcp: failed to write to stdout");
+ }
+}
+
+struct RpcError {
+ code: i64,
+ message: String,
+ data: Option<Value>,
+}
+
+impl RpcError {
+ fn new(code: i64, message: impl Into<String>) -> Self {
+ Self {
+ code,
+ message: message.into(),
+ data: None,
+ }
+ }
+
+ fn with_data(mut self, data: Value) -> Self {
+ self.data = Some(data);
+ self
+ }
+
+ fn response(&self, id: Value) -> Value {
+ let mut error = json!({ "code": self.code, "message": self.message });
+ if let Some(data) = &self.data {
+ error["data"] = data.clone();
+ }
+ json!({ "jsonrpc": "2.0", "id": id, "error": error })
+ }
+}
+
+#[cfg(test)]
+#[path = "mod_tests.rs"]
+mod tests;
diff --git a/src/mcp/mod_tests.rs b/src/mcp/mod_tests.rs
new file mode 100644
index 000000000..993552911
--- /dev/null
+++ b/src/mcp/mod_tests.rs
@@ -0,0 +1,115 @@
+use super::*;
+
+fn server() -> Server {
+ Server {
+ tools: catalog::tools(),
+ globals: Vec::new(),
+ calls: calls::Calls::default(),
+ }
+}
+
+#[test]
+fn legacy_initialize_echoes_a_supported_version_and_falls_back_to_the_newest() {
+ let server = server();
+ let echoed = server
+ .handle(
+ &Value::Null,
+ "initialize",
+ &json!({ "protocolVersion": "2025-06-18" }),
+ )
+ .unwrap_or_else(|_| panic!("initialize"));
+ assert_eq!(echoed["protocolVersion"], "2025-06-18");
+ let fallback = server
+ .handle(
+ &Value::Null,
+ "initialize",
+ &json!({ "protocolVersion": "1999-01-01" }),
+ )
+ .unwrap_or_else(|_| panic!("initialize"));
+ assert_eq!(fallback["protocolVersion"], LEGACY_VERSIONS[0]);
+ assert_eq!(fallback["capabilities"], json!({ "tools": {} }));
+}
+
+#[test]
+fn modern_requests_with_an_unknown_version_get_the_supported_list() {
+ let params = json!({ "_meta": { PROTOCOL_VERSION_META: "1999-01-01" } });
+ let Err(error) = server().handle(&Value::Null, "tools/list", &params) else {
+ panic!("an unknown modern version must be refused");
+ };
+ assert_eq!(error.code, -32022);
+ assert_eq!(error.data.unwrap()["supported"][0], MODERN_VERSION);
+}
+
+#[test]
+fn modern_tools_list_is_cacheable_and_complete() {
+ let params = json!({ "_meta": { PROTOCOL_VERSION_META: MODERN_VERSION } });
+ let result = server()
+ .handle(&Value::Null, "tools/list", &params)
+ .unwrap_or_else(|_| panic!("tools/list"));
+ assert_eq!(result["resultType"], "complete");
+ assert_eq!(result["cacheScope"], "public");
+ assert_eq!(
+ result["tools"].as_array().unwrap().len(),
+ catalog::tools().len()
+ );
+}
+
+#[test]
+fn unknown_tools_are_protocol_errors() {
+ let Err(error) = server().handle(
+ &Value::Null,
+ "tools/call",
+ &json!({ "name": "desktop_nope" }),
+ ) else {
+ panic!("unknown tool must be refused");
+ };
+ assert_eq!(error.code, -32602);
+}
+
+#[test]
+fn instructions_name_only_tools_that_exist() {
+ let names = catalog::tools()
+ .into_iter()
+ .map(|tool| tool.name)
+ .collect::<Vec<_>>();
+ let mentioned = INSTRUCTIONS
+ .split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
+ .filter(|word| word.starts_with("desktop_"))
+ .collect::<Vec<_>>();
+ assert!(!mentioned.is_empty());
+ for word in mentioned {
+ assert!(
+ names.iter().any(|name| name == word),
+ "instructions name {word}"
+ );
+ }
+}
+
+#[test]
+fn inline_screenshots_become_image_content() {
+ let envelope = json!({ "ok": true, "command": "screenshot", "data": { "data": "iVBORw0K", "format": "png", "width": 1 } });
+ let result = call::envelope_result(envelope);
+ assert_eq!(result["isError"], false);
+ assert_eq!(result["content"][1]["type"], "image");
+ assert_eq!(result["content"][1]["mimeType"], "image/png");
+ assert!(result["structuredContent"]["data"].get("data").is_none());
+ let failed = call::envelope_result(json!({ "ok": false, "command": "click" }));
+ assert_eq!(failed["isError"], true);
+}
+
+#[test]
+fn oversized_messages_are_refused_and_the_next_message_still_reads() {
+ let mut input = Vec::new();
+ input.extend(std::iter::repeat_n(b'x', MAX_MESSAGE_BYTES + 10));
+ input.extend(b"\n\n{\"id\":1}\n");
+ let mut reader = std::io::Cursor::new(input);
+ let Some(Err(error)) = read_message(&mut reader) else {
+ panic!("an oversized message must be refused");
+ };
+ assert_eq!(error.code, -32600);
+ let Some(Ok(next)) = read_message(&mut reader) else {
+ panic!("the following message must still be read");
+ };
+ assert_eq!(next, b"{\"id\":1}\n");
+ assert!(read_message(&mut reader).is_none());
+}
diff --git a/src/tests/mcp_process.rs b/src/tests/mcp_process.rs
new file mode 100644
index 000000000..5c5460e80
--- /dev/null
+++ b/src/tests/mcp_process.rs
@@ -0,0 +1,116 @@
+use serde_json::{Value, json};
+use std::io::Write;
+use std::process::{Command, Stdio};
+
+fn binary() -> Command {
+ Command::new(env!("CARGO_BIN_EXE_agent-desktop"))
+}
+
+fn serve(requests: &[Value], args: &[&str]) -> Vec<Value> {
+ let mut child = binary()
+ .arg("mcp")
+ .args(args)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .spawn()
+ .expect("binary starts");
+ let mut stdin = child.stdin.take().expect("stdin");
+ for request in requests {
+ writeln!(stdin, "{request}").expect("request written");
+ }
+ drop(stdin);
+ let output = child
+ .wait_with_output()
+ .expect("server exits after stdin closes");
+ assert!(output.status.success());
+ let mut responses = String::from_utf8(output.stdout)
+ .expect("utf-8")
+ .lines()
+ .map(|line| serde_json::from_str::<Value>(line).expect("one JSON-RPC message per line"))
+ .collect::<Vec<_>>();
+ responses.sort_by_key(|response| response["id"].as_i64());
+ responses
+}
+
+fn call(id: i64, name: &str, arguments: Value) -> Value {
+ json!({ "jsonrpc": "2.0", "id": id, "method": "tools/call",
+ "params": { "name": name, "arguments": arguments } })
+}
+
+#[test]
+fn mcp_tool_calls_run_the_cli_command_and_return_its_envelope() {
+ let responses = serve(
+ &[
+ json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize",
+ "params": { "protocolVersion": "2025-11-25", "capabilities": {},
+ "clientInfo": { "name": "test", "version": "0" } } }),
+ json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }),
+ call(2, "desktop_version", json!({})),
+ call(
+ 3,
+ "desktop_skills_get",
+ json!({ "name": "desktop", "reference": null }),
+ ),
+ ],
+ &[],
+ );
+ assert_eq!(responses.len(), 3, "{responses:?}");
+ assert_eq!(responses[0]["result"]["protocolVersion"], "2025-11-25");
+ let version = &responses[1]["result"];
+ assert_eq!(version["isError"], false, "{version}");
+ assert_eq!(version["structuredContent"]["command"], "version");
+ assert_eq!(
+ version["structuredContent"]["data"]["version"],
+ env!("CARGO_PKG_VERSION")
+ );
+ let skill = &responses[2]["result"];
+ assert_eq!(skill["isError"], false, "{skill}");
+ assert!(
+ skill["structuredContent"]["data"]["content"]
+ .as_str()
+ .is_some_and(|text| !text.is_empty())
+ );
+}
+
+#[test]
+fn mcp_server_global_flags_reach_every_call() {
+ let responses = serve(
+ &[call(1, "desktop_session_list", json!({}))],
+ &["--debug", "--screenshot", "x.html"],
+ );
+ let result = &responses[0]["result"];
+ assert_eq!(result["isError"], true, "{result}");
+ assert_eq!(
+ result["structuredContent"]["error"]["message"],
+ "--debug supports snapshot and click only"
+ );
+}
+
+#[test]
+fn malformed_messages_get_errors_and_the_server_keeps_serving() {
+ let responses = serve(
+ &[
+ json!([{ "jsonrpc": "2.0", "id": 9, "method": "tools/list" }]),
+ json!(42),
+ json!({ "jsonrpc": "2.0", "id": 2, "method": "no/such/method" }),
+ call(4, "desktop_skills_get", json!({ "name": "a\u{0}b" })),
+ call(5, "desktop_version", json!({})),
+ ],
+ &[],
+ );
+ let codes = responses
+ .iter()
+ .map(|response| (response["id"].clone(), response["error"]["code"].clone()))
+ .collect::<Vec<_>>();
+ assert_eq!(codes[0], (Value::Null, json!(-32600)), "{responses:?}");
+ assert_eq!(codes[1], (Value::Null, json!(-32600)), "{responses:?}");
+ assert_eq!(codes[2], (json!(2), json!(-32601)), "{responses:?}");
+ let nul = &responses[3]["result"];
+ assert!(
+ nul["content"][0]["text"]
+ .as_str()
+ .is_some_and(|text| text.starts_with("Cannot run agent-desktop")),
+ "{nul}"
+ );
+ assert_eq!(responses[4]["result"]["isError"], false);
+}