Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<name>.rs` with an `execute()` function, its tests in `<name>_tests.rs`, and
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
8 changes: 6 additions & 2 deletions apps/docs/content/docs/guides/mcp.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/json-output.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
8 changes: 6 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
117 changes: 117 additions & 0 deletions src/mcp/global_forward.rs
Original file line number Diff line number Diff line change
@@ -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<Vec<String>, AppError> {
let globals = collect_from(&Cli::command(), matches)?;
if let Ok(Some(session)) = matches.try_get_one::<String>("session") {
resolve_active_session(Some(session), None)?;
}
if let Ok(Some(agent_id)) = matches.try_get_one::<String>("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::<bool>("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<Vec<String>, 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<Vec<String>, 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;
157 changes: 157 additions & 0 deletions src/mcp/global_forward_tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
use super::*;
use std::ffi::OsString;

fn mcp_matches(words: impl IntoIterator<Item = impl Into<OsString> + 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<Vec<String>, 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}");
}
}
27 changes: 27 additions & 0 deletions src/mcp/global_scope.rs
Original file line number Diff line number Diff line change
@@ -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<Self> {
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,
}
}
}
Loading
Loading