From 6d537865aa7209cad42a1008932e8fed7add18ea Mon Sep 17 00:00:00 2001 From: gshost1 Date: Sun, 8 Nov 2026 04:22:05 -0800 Subject: [PATCH 1/2] fix(mcp): forward only server-wide globals and refuse per-command ones `mcp` forwarded every global flag given on its command line to each tool call's child. Flags that describe one command broke the server: `mcp --debug --screenshot x.html` failed every tool other than snapshot and click from the first call (including `desktop_skills_get`, which the server instructions say to read first), and every snapshot or click after the first, because the debug file is create-once. `mcp --wait-for` failed every tool without a post-action wait the same way. Each global now has an explicit scope. Server-wide flags (--session, --agent-id, --headed, --trace, --trace-strict, --verbose) are forwarded as before. Per-command flags (--debug, --screenshot, --wait-for, --wait-for-gone, --wait-timeout) and any global without a scope make `mcp` print an INVALID_ARGS envelope with a suggestion and exit 1 before it serves anything. A test fails when a new global flag has no scope. The process test that used --debug to show globals reach every call now uses an invalid --agent-id, and the server instructions no longer list --wait-for as a server flag. Item 11 of the upstream register `#602`. --- AGENTS.md | 3 +- README.md | 2 +- apps/docs/content/docs/guides/mcp.mdx | 6 +- src/mcp/global_scope.rs | 26 +++++++ src/mcp/globals.rs | 61 +++++++++++++++ src/mcp/globals_tests.rs | 107 ++++++++++++++++++++++++++ src/mcp/mod.rs | 37 +++------ src/tests/mcp_process.rs | 38 ++++++++- 8 files changed, 249 insertions(+), 31 deletions(-) create mode 100644 src/mcp/global_scope.rs create mode 100644 src/mcp/globals.rs create mode 100644 src/mcp/globals_tests.rs diff --git a/AGENTS.md b/AGENTS.md index 442e457131..de8ad9329c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -131,7 +131,8 @@ 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, per-command flags make `mcp` refuse to start. **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..a3e7947723 100644 --- a/apps/docs/content/docs/guides/mcp.mdx +++ b/apps/docs/content/docs/guides/mcp.mdx @@ -37,15 +37,17 @@ 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`, `--trace-strict` and `--verbose`. ```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. `mcp` refuses them: it prints an `INVALID_ARGS` envelope, exits with code `1` and serves nothing. Run visual debug from the CLI, and call `desktop_wait` to wait for an element. + `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/src/mcp/global_scope.rs b/src/mcp/global_scope.rs new file mode 100644 index 0000000000..80feaca96f --- /dev/null +++ b/src/mcp/global_scope.rs @@ -0,0 +1,26 @@ +//! Whether a global flag given to `mcp` describes the whole server or a single command. + +/// `ServerWide` flags hold for every call the server runs, so the server forwards them to each child. +/// `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, + 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 { + "verbose" | "session" | "agent_id" | "trace" | "trace_strict" | "headed" => { + Some(Self::ServerWide) + } + "debug" | "screenshot" | "wait_for" | "wait_for_gone" | "wait_timeout" => { + Some(Self::PerCommand) + } + _ => None, + } + } +} diff --git a/src/mcp/globals.rs b/src/mcp/globals.rs new file mode 100644 index 0000000000..bdc994770b --- /dev/null +++ b/src/mcp/globals.rs @@ -0,0 +1,61 @@ +//! The global flags `mcp` was started with, split into the ones every call inherits and the ones it refuses. + +use agent_desktop_core::{ + AppError, + response::output::{ErrorPayload, Response}, +}; +use clap::{ArgAction, ArgMatches, CommandFactory, parser::ValueSource}; +use std::process::ExitCode; +use std::sync::Mutex; + +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. Any per-command or +/// unknown global given there is refused with `INVALID_ARGS`, since the server would pass it to every call. +pub(crate) fn forwarded_globals(matches: &ArgMatches) -> Result, AppError> { + let root = Cli::command(); + let mut globals = Vec::new(); + let mut refused = 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 GlobalScope::of(id) != Some(GlobalScope::ServerWide) { + refused.push(format!("--{long}")); + } else 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()))); + } + } + if refused.is_empty() { + return Ok(globals); + } + Err(AppError::invalid_input_with_suggestion( + format!( + "mcp cannot apply {} to every call: each applies to a single command", + refused.join(", ") + ), + SUGGESTION, + )) +} + +/// Prints `error` as the `mcp` command's JSON envelope and returns the structured-error exit code. +pub(crate) fn refuse_start(error: &AppError) -> ExitCode { + let response = Response::err("mcp", ErrorPayload::from_app_error(error)); + match serde_json::to_value(&response) { + Ok(envelope) => super::write_line(&Mutex::new(std::io::stdout()), &envelope), + Err(error) => eprintln!("agent-desktop mcp: {error}"), + } + ExitCode::FAILURE +} + +#[cfg(test)] +#[path = "globals_tests.rs"] +mod tests; diff --git a/src/mcp/globals_tests.rs b/src/mcp/globals_tests.rs new file mode 100644 index 0000000000..faf977bc41 --- /dev/null +++ b/src/mcp/globals_tests.rs @@ -0,0 +1,107 @@ +use super::*; + +fn globals(words: &[&str]) -> Result, AppError> { + let matches = crate::root_command() + .try_get_matches_from(words) + .unwrap_or_else(|error| panic!("{words:?} must parse: {error}")); + let Some(("mcp", mcp)) = matches.subcommand() else { + panic!("{words:?} must name mcp"); + }; + forwarded_globals(mcp) +} + +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_and_never_forwarded() { + let words = [ + "agent-desktop", + "--debug", + "--screenshot", + "/tmp/x.html", + "mcp", + ]; + let forwarded = globals(&words).unwrap_or_default(); + assert!( + !forwarded + .iter() + .any(|flag| flag.starts_with("--debug") || flag.starts_with("--screenshot")), + "{forwarded:?}" + ); + let message = refusal(&words); + 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 server_wide_flags_are_forwarded_in_order() { + 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, + [ + "--verbose", + "--session=s1", + "--agent-id=agent-a", + "--trace=/tmp/t.jsonl", + "--trace-strict", + "--headed", + ] + ); + 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() + ); + } +} diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs index 07464dae9b..998a15389e 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_scope; +mod globals; 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,15 @@ 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. pub(crate) fn serve(matches: &ArgMatches) -> ExitCode { + let globals = match globals::forwarded_globals(matches) { + Ok(globals) => globals, + Err(error) => return globals::refuse_start(&error), + }; 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 +301,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..807b13012a 100644 --- a/src/tests/mcp_process.rs +++ b/src/tests/mcp_process.rs @@ -76,16 +76,50 @@ fn mcp_tool_calls_run_the_cli_command_and_return_its_envelope() { fn mcp_server_global_flags_reach_every_call() { let responses = serve( &[call(1, "desktop_session_list", json!({}))], - &["--debug", "--screenshot", "x.html"], + &["--agent-id", "not a valid id"], ); let result = &responses[0]["result"]; assert_eq!(result["isError"], true, "{result}"); assert_eq!( result["structuredContent"]["error"]["message"], - "--debug supports snapshot and click only" + "Agent id must be 1-64 chars using letters, numbers, '-' or '_'" ); } +#[test] +fn mcp_refuses_per_command_global_flags_before_serving() { + let dir = std::env::temp_dir().join(format!("agent-desktop-mcp-refuse-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let html = dir.join("debug.html"); + let html_arg = html.to_str().expect("utf-8 path"); + for args in [ + &["--debug", "--screenshot", html_arg][..], + &["--wait-for", "button:OK"], + &["--wait-timeout", "5"], + ] { + let output = binary() + .arg("mcp") + .args(args) + .stdin(Stdio::null()) + .output() + .expect("binary runs"); + assert_eq!(output.status.code(), Some(1), "{args:?}"); + let envelope: Value = serde_json::from_slice(&output.stdout).expect("one JSON envelope"); + 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(args[0])), + "{envelope}" + ); + } + assert!(!html.exists()); + let _ = std::fs::remove_dir_all(&dir); +} + #[test] fn malformed_messages_get_errors_and_the_server_keeps_serving() { let responses = serve( From bab3f4d58c3a60f104d15df1742e70000dd79e2c Mon Sep 17 00:00:00 2001 From: gshost1 Date: Sun, 8 Nov 2026 04:55:59 -0800 Subject: [PATCH 2/2] fix(mcp): refuse bad startup flags on stderr with exit 2 and stop forwarding --verbose Review of the first change found gaps in how `mcp` refuses its flags: - The refusal envelope went to stdout, which an MCP client reads as JSON-RPC, so the user never saw why the server exited. It now goes to stderr through the same JSON writer the CLI uses, and an argument error exits 2 like every other argument error. - An invalid --session or --agent-id was forwarded and failed every call. `mcp` now checks both once with the child's own validators. - A non-UTF-8 value was forwarded after a lossy conversion, which could point a child at a different --trace file. It is now refused. - The long-name check ran before the scope check, so a short-only global would have been dropped silently, and a global missing from the scope table got the per-command message. Both are now an internal error that says the flag is not classified for mcp. - --verbose only produced child stderr that the server buffers and then discards. It is now server-only: it turns on the server's own debug log and is not forwarded. The tests now check the refusal while stdin is still open, prove valid values reach the child through the trace it writes, and clean up their scratch directory. The module is renamed to global_forward and its entry point to collect_forwarded_globals. main.rs gains a small write_response helper so the refusal reuses the envelope writer instead of copying it. --- AGENTS.md | 3 +- apps/docs/content/docs/guides/mcp.mdx | 6 +- docs/json-output.md | 2 +- src/main.rs | 8 +- src/mcp/global_forward.rs | 117 +++++++++++++++++++ src/mcp/global_forward_tests.rs | 157 ++++++++++++++++++++++++++ src/mcp/global_scope.rs | 9 +- src/mcp/globals.rs | 61 ---------- src/mcp/globals_tests.rs | 107 ------------------ src/mcp/mod.rs | 10 +- src/tests/mcp_process.rs | 86 ++++++++++---- 11 files changed, 361 insertions(+), 205 deletions(-) create mode 100644 src/mcp/global_forward.rs create mode 100644 src/mcp/global_forward_tests.rs delete mode 100644 src/mcp/globals.rs delete mode 100644 src/mcp/globals_tests.rs diff --git a/AGENTS.md b/AGENTS.md index de8ad9329c..d7c0ec02e5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -132,7 +132,8 @@ each leaf command is one tool, its schema comes from the command's clap argument 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. A new global flag needs a scope in -`src/mcp/global_scope.rs`: server-wide flags are forwarded to every call, per-command flags make `mcp` refuse to start. +`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/apps/docs/content/docs/guides/mcp.mdx b/apps/docs/content/docs/guides/mcp.mdx index a3e7947723..ee102a8e9f 100644 --- a/apps/docs/content/docs/guides/mcp.mdx +++ b/apps/docs/content/docs/guides/mcp.mdx @@ -37,13 +37,15 @@ The tool list is read from the CLI's own command definitions, so it always match ## Apply global flags once -Server-wide global flags given to `mcp` apply to every call: `--session`, `--agent-id`, `--headed`, `--trace`, `--trace-strict` and `--verbose`. +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. `mcp` refuses them: it prints an `INVALID_ARGS` envelope, exits with code `1` and serves nothing. Run visual debug from the CLI, and call `desktop_wait` to wait for an element. +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. diff --git a/docs/json-output.md b/docs/json-output.md index 4f0d95dad2..6f991d7c26 100644 --- a/docs/json-output.md +++ b/docs/json-output.md @@ -284,4 +284,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 index 80feaca96f..9f09762349 100644 --- a/src/mcp/global_scope.rs +++ b/src/mcp/global_scope.rs @@ -1,11 +1,13 @@ -//! Whether a global flag given to `mcp` describes the whole server or a single command. +//! 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, } @@ -14,9 +16,8 @@ impl GlobalScope { /// which `mcp` refuses rather than forwards. pub(crate) fn of(id: &str) -> Option { match id { - "verbose" | "session" | "agent_id" | "trace" | "trace_strict" | "headed" => { - Some(Self::ServerWide) - } + "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) } diff --git a/src/mcp/globals.rs b/src/mcp/globals.rs deleted file mode 100644 index bdc994770b..0000000000 --- a/src/mcp/globals.rs +++ /dev/null @@ -1,61 +0,0 @@ -//! The global flags `mcp` was started with, split into the ones every call inherits and the ones it refuses. - -use agent_desktop_core::{ - AppError, - response::output::{ErrorPayload, Response}, -}; -use clap::{ArgAction, ArgMatches, CommandFactory, parser::ValueSource}; -use std::process::ExitCode; -use std::sync::Mutex; - -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. Any per-command or -/// unknown global given there is refused with `INVALID_ARGS`, since the server would pass it to every call. -pub(crate) fn forwarded_globals(matches: &ArgMatches) -> Result, AppError> { - let root = Cli::command(); - let mut globals = Vec::new(); - let mut refused = 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 GlobalScope::of(id) != Some(GlobalScope::ServerWide) { - refused.push(format!("--{long}")); - } else 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()))); - } - } - if refused.is_empty() { - return Ok(globals); - } - Err(AppError::invalid_input_with_suggestion( - format!( - "mcp cannot apply {} to every call: each applies to a single command", - refused.join(", ") - ), - SUGGESTION, - )) -} - -/// Prints `error` as the `mcp` command's JSON envelope and returns the structured-error exit code. -pub(crate) fn refuse_start(error: &AppError) -> ExitCode { - let response = Response::err("mcp", ErrorPayload::from_app_error(error)); - match serde_json::to_value(&response) { - Ok(envelope) => super::write_line(&Mutex::new(std::io::stdout()), &envelope), - Err(error) => eprintln!("agent-desktop mcp: {error}"), - } - ExitCode::FAILURE -} - -#[cfg(test)] -#[path = "globals_tests.rs"] -mod tests; diff --git a/src/mcp/globals_tests.rs b/src/mcp/globals_tests.rs deleted file mode 100644 index faf977bc41..0000000000 --- a/src/mcp/globals_tests.rs +++ /dev/null @@ -1,107 +0,0 @@ -use super::*; - -fn globals(words: &[&str]) -> Result, AppError> { - let matches = crate::root_command() - .try_get_matches_from(words) - .unwrap_or_else(|error| panic!("{words:?} must parse: {error}")); - let Some(("mcp", mcp)) = matches.subcommand() else { - panic!("{words:?} must name mcp"); - }; - forwarded_globals(mcp) -} - -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_and_never_forwarded() { - let words = [ - "agent-desktop", - "--debug", - "--screenshot", - "/tmp/x.html", - "mcp", - ]; - let forwarded = globals(&words).unwrap_or_default(); - assert!( - !forwarded - .iter() - .any(|flag| flag.starts_with("--debug") || flag.starts_with("--screenshot")), - "{forwarded:?}" - ); - let message = refusal(&words); - 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 server_wide_flags_are_forwarded_in_order() { - 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, - [ - "--verbose", - "--session=s1", - "--agent-id=agent-a", - "--trace=/tmp/t.jsonl", - "--trace-strict", - "--headed", - ] - ); - 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() - ); - } -} diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs index 998a15389e..12bdeb3ee7 100644 --- a/src/mcp/mod.rs +++ b/src/mcp/mod.rs @@ -4,8 +4,8 @@ mod call; mod calls; mod catalog; mod child_lease; +mod global_forward; mod global_scope; -mod globals; mod inherited_lease; mod lease_inheritance; mod lease_refusal; @@ -51,12 +51,14 @@ 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. +/// 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 globals::forwarded_globals(matches) { + let globals = match global_forward::collect_forwarded_globals(matches) { Ok(globals) => globals, - Err(error) => return globals::refuse_start(&error), + Err(error) => return global_forward::refuse_start(&error), }; + global_forward::init_server_logging(matches); let server = Arc::new(Server { tools: catalog::tools(), globals, diff --git a/src/tests/mcp_process.rs b/src/tests/mcp_process.rs index 807b13012a..e480c4044f 100644 --- a/src/tests/mcp_process.rs +++ b/src/tests/mcp_process.rs @@ -72,39 +72,81 @@ 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!({}))], - &["--agent-id", "not a valid id"], + &["--trace", trace_arg, "--session", "mcp-forward-s1"], ); let result = &responses[0]["result"]; - assert_eq!(result["isError"], true, "{result}"); - assert_eq!( - result["structuredContent"]["error"]["message"], - "Agent id must be 1-64 chars using letters, numbers, '-' or '_'" + 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_global_flags_before_serving() { - let dir = std::env::temp_dir().join(format!("agent-desktop-mcp-refuse-{}", std::process::id())); - std::fs::create_dir_all(&dir).expect("scratch dir"); - let html = dir.join("debug.html"); - let html_arg = html.to_str().expect("utf-8 path"); - for args in [ - &["--debug", "--screenshot", html_arg][..], - &["--wait-for", "button:OK"], - &["--wait-timeout", "5"], +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 output = binary() + let mut child = binary() .arg("mcp") .args(args) - .stdin(Stdio::null()) - .output() - .expect("binary runs"); - assert_eq!(output.status.code(), Some(1), "{args:?}"); - let envelope: Value = serde_json::from_slice(&output.stdout).expect("one JSON envelope"); + .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}"); @@ -112,12 +154,10 @@ fn mcp_refuses_per_command_global_flags_before_serving() { assert!( envelope["error"]["message"] .as_str() - .is_some_and(|message| message.contains(args[0])), + .is_some_and(|message| message.contains(named)), "{envelope}" ); } - assert!(!html.exists()); - let _ = std::fs::remove_dir_all(&dir); } #[test]