diff --git a/AGENTS.md b/AGENTS.md index 442e457131..d7c0ec02e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,7 +131,9 @@ JSON entries into the same `Commands` enum, runs the same `CommandPolicy` prefli 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. +`Commands`, so it is never a tool, a batch entry or a counted command. A new global flag needs a scope in +`src/mcp/global_scope.rs`: server-wide flags are forwarded to every call, server-only flags configure the server +process, and per-command flags make `mcp` refuse to start with exit code 2. **Adding a command.** 1. Create `crates/core/src/commands/.rs` with an `execute()` function, its tests in `_tests.rs`, and diff --git a/README.md b/README.md index 0c8b2ffae6..c4b807e665 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ Retry a failed command only when `error.disposition.retry` is `safe`. See [JSON { "mcpServers": { "agent-desktop": { "command": "agent-desktop", "args": ["mcp"] } } } ``` -Global flags given to `mcp`, such as `--session`, `--headed` or `--trace`, apply to every call. +Server-wide global flags given to `mcp`, such as `--session`, `--headed` or `--trace`, apply to every call. `mcp` refuses flags that describe a single command, such as `--debug` or `--wait-for`. ## Commands diff --git a/apps/docs/content/docs/guides/mcp.mdx b/apps/docs/content/docs/guides/mcp.mdx index 79c960aba8..ee102a8e9f 100644 --- a/apps/docs/content/docs/guides/mcp.mdx +++ b/apps/docs/content/docs/guides/mcp.mdx @@ -37,15 +37,19 @@ The tool list is read from the CLI's own command definitions, so it always match ## Apply global flags once -Global flags given to `mcp` apply to every call: +Server-wide global flags given to `mcp` apply to every call: `--session`, `--agent-id`, `--headed`, `--trace` and `--trace-strict`. `--verbose` turns on the server's own debug log on stderr and is not passed to calls. ```bash agent-desktop mcp --session s1 --headed ``` +Flags that describe a single command, `--debug`, `--screenshot`, `--wait-for`, `--wait-for-gone` and `--wait-timeout`, cannot apply to every call. Run visual debug from the CLI, and call `desktop_wait` to wait for an element. + +`mcp` refuses to start with one of those flags, with an invalid `--session` or `--agent-id`, or with a flag value that is not UTF-8. It writes an `INVALID_ARGS` envelope to stderr, because stdout carries only JSON-RPC, exits with code `2` and serves nothing. + `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. +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, and headed-only commands need `mcp --headed`. ## Read results diff --git a/docs/json-output.md b/docs/json-output.md index 47575732ba..983ff1ea52 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -317,4 +317,4 @@ A refusal without `details.retryable: true` ends every wait at once. With it, wh ## Exit codes -`0` success, `1` structured error (JSON on stdout), `2` command-line parse error (the envelope is still printed, with `INVALID_ARGS`). +`0` success, `1` structured error (JSON on stdout), `2` command-line parse error (the envelope is still printed, with `INVALID_ARGS`). `mcp` also exits `2` when it refuses its startup flags, and writes that envelope to stderr, since its stdout carries only JSON-RPC. diff --git a/src/main.rs b/src/main.rs index 3caa9acb65..8a1f02f3af 100644 --- a/src/main.rs +++ b/src/main.rs @@ -331,8 +331,12 @@ fn report_output_failure(write_err: std::io::Error) -> ExitCode { } fn emit_response(response: &impl serde::Serialize) -> std::io::Result<()> { - let stdout = std::io::stdout(); - let mut writer = BufWriter::new(stdout.lock()); + write_response(std::io::stdout().lock(), response) +} + +/// Writes `response` to `out` as one JSON line and flushes it. +fn write_response(out: impl Write, response: &impl serde::Serialize) -> std::io::Result<()> { + let mut writer = BufWriter::new(out); serde_json::to_writer(&mut writer, response).map_err(std::io::Error::other)?; writer.write_all(b"\n")?; writer.flush() diff --git a/src/mcp/global_forward.rs b/src/mcp/global_forward.rs new file mode 100644 index 0000000000..5a7bb6a218 --- /dev/null +++ b/src/mcp/global_forward.rs @@ -0,0 +1,117 @@ +//! The global flags `mcp` was started with: checked once, then turned into the arguments every call inherits. + +use agent_desktop_core::{ + AppError, ErrorCode, + response::output::{ErrorPayload, Response}, + session::{resolve_active_session, validate_agent_id}, +}; +use clap::{Arg, ArgAction, ArgMatches, Command, CommandFactory, parser::ValueSource}; +use std::process::ExitCode; + +use super::global_scope::GlobalScope; +use crate::cli::Cli; + +const SUGGESTION: &str = "Start mcp without them. For visual debug, run snapshot or click with \ +--debug --screenshot PATH.html from the CLI; to wait for an element, call desktop_wait."; + +/// The server-wide globals given on the command line, as the arguments each child gets. A per-command +/// global, an invalid `--session` or `--agent-id`, or a value that is not UTF-8 is refused with +/// `INVALID_ARGS`, since every call would fail on it; a global without a scope is an internal error. +pub(crate) fn collect_forwarded_globals(matches: &ArgMatches) -> Result, AppError> { + let globals = collect_from(&Cli::command(), matches)?; + if let Ok(Some(session)) = matches.try_get_one::("session") { + resolve_active_session(Some(session), None)?; + } + if let Ok(Some(agent_id)) = matches.try_get_one::("agent_id") { + validate_agent_id(agent_id)?; + } + Ok(globals) +} + +/// Turns on the server's own debug logging to stderr when `mcp` was given `--verbose`. +pub(crate) fn init_server_logging(matches: &ArgMatches) { + if let Ok(Some(true)) = matches.try_get_one::("verbose") { + crate::init_tracing(true); + } +} + +/// Writes `error` to stderr as the `mcp` command's JSON envelope, leaving stdout to JSON-RPC, and returns +/// exit code 2 for an argument error, 1 otherwise. +pub(crate) fn refuse_start(error: &AppError) -> ExitCode { + let response = Response::err("mcp", ErrorPayload::from_app_error(error)); + let _ = crate::write_response(std::io::stderr().lock(), &response); + if error.code() == ErrorCode::InvalidArgs.as_str() { + ExitCode::from(crate::EXIT_INVALID_ARGS) + } else { + ExitCode::FAILURE + } +} + +fn collect_from(root: &Command, matches: &ArgMatches) -> Result, AppError> { + let mut globals = Vec::new(); + let mut per_command = Vec::new(); + let mut unclassified = Vec::new(); + for arg in root.get_arguments().filter(|arg| arg.is_global_set()) { + if matches.value_source(arg.get_id().as_str()) != Some(ValueSource::CommandLine) { + continue; + } + match (GlobalScope::of(arg.get_id().as_str()), arg.get_long()) { + (Some(GlobalScope::ServerOnly), _) => {} + (Some(GlobalScope::PerCommand), _) => per_command.push(flag_name(arg)), + (Some(GlobalScope::ServerWide), Some(long)) => { + globals.extend(forward(arg, long, matches)?); + } + (Some(GlobalScope::ServerWide), None) | (None, _) => unclassified.push(flag_name(arg)), + } + } + if !unclassified.is_empty() { + return Err(AppError::Internal(format!( + "mcp: global flag {} is not classified for mcp; give it a forwardable scope in src/mcp/global_scope.rs", + unclassified.join(", ") + ))); + } + if !per_command.is_empty() { + return Err(AppError::invalid_input_with_suggestion( + format!( + "mcp cannot apply {} to every call: each applies to a single command", + per_command.join(", ") + ), + SUGGESTION, + )); + } + Ok(globals) +} + +fn forward(arg: &Arg, long: &str, matches: &ArgMatches) -> Result, AppError> { + if matches!(arg.get_action(), ArgAction::SetTrue) { + return Ok(vec![format!("--{long}")]); + } + let Some(values) = matches.get_raw(arg.get_id().as_str()) else { + return Ok(Vec::new()); + }; + values + .map(|value| { + value + .to_str() + .map(|value| format!("--{long}={value}")) + .ok_or_else(|| { + AppError::invalid_input_with_suggestion( + format!("--{long} must be valid UTF-8 for mcp to pass it to every call"), + format!("Start mcp with a UTF-8 --{long} value."), + ) + }) + }) + .collect() +} + +fn flag_name(arg: &Arg) -> String { + match (arg.get_long(), arg.get_short()) { + (Some(long), _) => format!("--{long}"), + (None, Some(short)) => format!("-{short}"), + (None, None) => arg.get_id().to_string(), + } +} + +#[cfg(test)] +#[path = "global_forward_tests.rs"] +mod tests; diff --git a/src/mcp/global_forward_tests.rs b/src/mcp/global_forward_tests.rs new file mode 100644 index 0000000000..27527ad4fe --- /dev/null +++ b/src/mcp/global_forward_tests.rs @@ -0,0 +1,157 @@ +use super::*; +use std::ffi::OsString; + +fn mcp_matches(words: impl IntoIterator + Clone>) -> ArgMatches { + let matches = crate::root_command() + .try_get_matches_from(words) + .unwrap_or_else(|error| panic!("the words must parse: {error}")); + match matches.subcommand() { + Some(("mcp", mcp)) => mcp.clone(), + _ => panic!("the words must name mcp"), + } +} + +fn globals(words: &[&str]) -> Result, AppError> { + collect_forwarded_globals(&mcp_matches(words)) +} + +fn refusal(words: &[&str]) -> String { + match globals(words) { + Ok(forwarded) => panic!("{words:?} must be refused, forwarded {forwarded:?}"), + Err(error) => { + assert_eq!(error.code(), "INVALID_ARGS", "{words:?}"); + assert!(error.suggestion().is_some(), "{words:?}"); + error.to_string() + } + } +} + +#[test] +fn visual_debug_flags_are_refused_so_nothing_is_forwarded() { + let message = refusal(&[ + "agent-desktop", + "--debug", + "--screenshot", + "/tmp/x.html", + "mcp", + ]); + assert!(message.contains("--debug"), "{message}"); + assert!(message.contains("--screenshot"), "{message}"); +} + +#[test] +fn post_action_wait_flags_are_refused_before_or_after_mcp() { + for words in [ + &["agent-desktop", "--wait-for", "button:OK", "mcp"][..], + &["agent-desktop", "mcp", "--wait-for-gone", "button:OK"], + &[ + "agent-desktop", + "mcp", + "--wait-for", + "button:OK", + "--wait-timeout", + "5", + ], + &["agent-desktop", "mcp", "--wait-timeout", "5"], + ] { + let message = refusal(words); + assert!(message.contains("--wait-"), "{message}"); + } +} + +#[test] +fn invalid_identity_values_are_refused_at_startup() { + let session = refusal(&["agent-desktop", "mcp", "--session", "not a session"]); + assert!(session.to_lowercase().contains("session"), "{session}"); + let agent = refusal(&["agent-desktop", "mcp", "--agent-id", "not a valid id"]); + assert!(agent.contains("Agent id"), "{agent}"); +} + +#[cfg(unix)] +#[test] +fn a_non_utf8_value_is_refused_instead_of_forwarded_lossily() { + use std::os::unix::ffi::OsStringExt; + let path = OsString::from_vec(b"/tmp/trace-\xff.jsonl".to_vec()); + let words: [OsString; 4] = ["agent-desktop".into(), "mcp".into(), "--trace".into(), path]; + let Err(error) = collect_forwarded_globals(&mcp_matches(words)) else { + panic!("a non-UTF-8 --trace must be refused"); + }; + assert_eq!(error.code(), "INVALID_ARGS"); + assert!(error.to_string().contains("--trace"), "{error}"); +} + +#[test] +fn server_wide_flags_are_forwarded_in_order_and_server_only_flags_are_not() { + let forwarded = globals(&[ + "agent-desktop", + "-v", + "--session", + "s1", + "mcp", + "--agent-id", + "agent-a", + "--trace", + "/tmp/t.jsonl", + "--trace-strict", + "--headed", + ]) + .unwrap_or_else(|error| panic!("server-wide flags must be forwarded: {error}")); + assert_eq!( + forwarded, + [ + "--session=s1", + "--agent-id=agent-a", + "--trace=/tmp/t.jsonl", + "--trace-strict", + "--headed", + ] + ); + assert_eq!( + globals(&["agent-desktop", "mcp", "-v"]).ok(), + Some(Vec::new()) + ); + assert_eq!(globals(&["agent-desktop", "mcp"]).ok(), Some(Vec::new())); +} + +#[test] +fn every_global_flag_has_a_scope() { + for arg in Cli::command() + .get_arguments() + .filter(|arg| arg.is_global_set()) + { + assert!( + GlobalScope::of(arg.get_id().as_str()).is_some(), + "classify --{:?} in GlobalScope::of", + arg.get_long() + ); + } +} + +#[test] +fn an_unclassified_or_short_only_global_is_an_internal_error_not_a_silent_drop() { + for (id, short) in [("mystery", 'm'), ("headed", 'H')] { + let root = Command::new("agent-desktop") + .arg( + Arg::new(id) + .short(short) + .global(true) + .action(ArgAction::SetTrue), + ) + .subcommand(Command::new("mcp")); + let flag = format!("-{short}"); + let matches = root + .clone() + .try_get_matches_from(["agent-desktop", "mcp", flag.as_str()]) + .unwrap_or_else(|error| panic!("{error}")); + let Some(("mcp", mcp)) = matches.subcommand() else { + panic!("mcp"); + }; + let Err(error) = collect_from(&root, mcp) else { + panic!("{flag} must be refused, not dropped"); + }; + assert_eq!(error.code(), "INTERNAL", "{flag}"); + let message = error.to_string(); + assert!(message.contains("not classified for mcp"), "{message}"); + assert!(message.contains(&flag), "{message}"); + } +} diff --git a/src/mcp/global_scope.rs b/src/mcp/global_scope.rs new file mode 100644 index 0000000000..9f09762349 --- /dev/null +++ b/src/mcp/global_scope.rs @@ -0,0 +1,27 @@ +//! What a global flag given to `mcp` applies to: every call, the server process itself, or a single command. + +/// `ServerWide` flags hold for every call the server runs, so the server forwards them to each child. +/// `ServerOnly` flags configure the server process (its own logging) and are never forwarded. +/// `PerCommand` flags describe one invocation (a create-once visual-debug file, a post-action wait for a +/// selector) and would break every call they do not fit, so `mcp` refuses them before it serves anything. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum GlobalScope { + ServerWide, + ServerOnly, + PerCommand, +} + +impl GlobalScope { + /// The scope of the global argument with clap id `id`; `None` for a global this server does not know, + /// which `mcp` refuses rather than forwards. + pub(crate) fn of(id: &str) -> Option { + match id { + "session" | "agent_id" | "trace" | "trace_strict" | "headed" => Some(Self::ServerWide), + "verbose" => Some(Self::ServerOnly), + "debug" | "screenshot" | "wait_for" | "wait_for_gone" | "wait_timeout" => { + Some(Self::PerCommand) + } + _ => None, + } + } +} diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs index 07464dae9b..12bdeb3ee7 100644 --- a/src/mcp/mod.rs +++ b/src/mcp/mod.rs @@ -4,6 +4,8 @@ mod call; mod calls; mod catalog; mod child_lease; +mod global_forward; +mod global_scope; mod inherited_lease; mod lease_inheritance; mod lease_refusal; @@ -13,14 +15,12 @@ mod queued_ticket; mod slot_holder; mod slot_step; -use clap::{ArgAction, ArgMatches, Command, CommandFactory, parser::ValueSource}; +use clap::{ArgMatches, Command}; 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"; @@ -35,15 +35,15 @@ false with error; a call rejected before the command runs returns plain text. Re 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 \ +--help. Global flags (--session, --agent-id, --headed, --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", + "Serve every command as an MCP tool over stdio; server-wide global flags given here apply to every call", ) } @@ -51,10 +51,17 @@ pub(crate) fn command() -> Command { /// At most `MAX_CONCURRENT_CALLS` calls run at once, and a message longer than `MAX_MESSAGE_BYTES` is refused unread. /// Under an interaction lease inherited from the parent, calls that can inject input or steal focus run one /// at a time, in arrival order, each waiting for its turn at most `inherited_lease::QUEUE_WAIT_BOUND`. +/// Global flags that apply to a single command, such as `--debug` or `--wait-for`, refuse to start it, and so +/// does an invalid `--session` or `--agent-id`. pub(crate) fn serve(matches: &ArgMatches) -> ExitCode { + let globals = match global_forward::collect_forwarded_globals(matches) { + Ok(globals) => globals, + Err(error) => return global_forward::refuse_start(&error), + }; + global_forward::init_server_logging(matches); let server = Arc::new(Server { tools: catalog::tools(), - globals: forwarded_globals(matches), + globals, calls: calls::Calls::default(), lease: Arc::new(lease_inheritance::LeaseInheritance::from_env()), }); @@ -296,24 +303,6 @@ fn server_info() -> Value { json!({ "name": "agent-desktop", "version": env!("CARGO_PKG_VERSION") }) } -fn forwarded_globals(matches: &ArgMatches) -> Vec { - 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, message: &Value) { let Ok(mut out) = out.lock() else { return }; let mut line = message.to_string(); diff --git a/src/tests/mcp_process.rs b/src/tests/mcp_process.rs index 5c5460e804..e480c4044f 100644 --- a/src/tests/mcp_process.rs +++ b/src/tests/mcp_process.rs @@ -72,20 +72,94 @@ fn mcp_tool_calls_run_the_cli_command_and_return_its_envelope() { ); } +struct ScratchDir(std::path::PathBuf); + +impl ScratchDir { + fn new(label: &str) -> Self { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir().join(format!( + "agent-desktop-mcp-{label}-{}-{id}", + std::process::id() + )); + std::fs::create_dir_all(&dir).expect("scratch dir"); + Self(dir) + } +} + +impl Drop for ScratchDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + #[test] fn mcp_server_global_flags_reach_every_call() { + let dir = ScratchDir::new("forward"); + let trace = dir.0.join("trace.jsonl"); + let trace_arg = trace.to_str().expect("utf-8 path"); let responses = serve( &[call(1, "desktop_session_list", json!({}))], - &["--debug", "--screenshot", "x.html"], + &["--trace", trace_arg, "--session", "mcp-forward-s1"], ); let result = &responses[0]["result"]; - assert_eq!(result["isError"], true, "{result}"); - assert_eq!( - result["structuredContent"]["error"]["message"], - "--debug supports snapshot and click only" + assert_eq!(result["isError"], false, "{result}"); + let written = std::fs::read_to_string(&trace).expect("the call wrote the server's trace"); + assert!( + written.contains("\"command\":\"session\"") + && written.contains("\"session_id\":\"mcp-forward-s1\""), + "{written}" ); } +#[test] +fn mcp_refuses_per_command_globals_and_invalid_identity_before_reading_stdin() { + for (args, named) in [ + (&["--debug", "--screenshot", "debug.html"][..], "--debug"), + (&["--wait-for", "button:OK"], "--wait-for"), + (&["--wait-timeout", "5"], "--wait-timeout"), + (&["--agent-id", "not a valid id"], "Agent id"), + ] { + let mut child = binary() + .arg("mcp") + .args(args) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .expect("binary starts"); + let stdin = child.stdin.take().expect("stdin"); + let started = std::time::Instant::now(); + while child.try_wait().expect("child status").is_none() { + if started.elapsed() > std::time::Duration::from_secs(20) { + let _ = child.kill(); + let _ = child.wait(); + panic!("{args:?}: mcp kept serving with stdin open instead of refusing"); + } + std::thread::sleep(std::time::Duration::from_millis(20)); + } + drop(stdin); + let output = child.wait_with_output().expect("refusal output"); + assert_eq!(output.status.code(), Some(2), "{args:?}"); + assert!( + output.stdout.is_empty(), + "{args:?}: stdout is JSON-RPC only" + ); + let envelope: Value = + serde_json::from_slice(&output.stderr).expect("one JSON envelope on stderr"); + assert_eq!(envelope["ok"], false, "{envelope}"); + assert_eq!(envelope["command"], "mcp", "{envelope}"); + assert_eq!(envelope["error"]["code"], "INVALID_ARGS", "{envelope}"); + assert!(envelope["error"]["suggestion"].is_string(), "{envelope}"); + assert!( + envelope["error"]["message"] + .as_str() + .is_some_and(|message| message.contains(named)), + "{envelope}" + ); + } +} + #[test] fn malformed_messages_get_errors_and_the_server_keeps_serving() { let responses = serve(