Skip to main content

vtcode_core/mcp/cli/
args.rs

1//! Clap argument types for the `vtcode mcp` subcommands.
2
3use crate::cli::input_hardening::validate_agent_safe_text;
4use anyhow::{Result, bail};
5use clap::{ArgGroup, Args};
6
7/// Arguments for the `list` subcommand.
8#[derive(Debug, Clone, Args)]
9pub struct ListArgs {
10    /// Output the configured providers as JSON.
11    #[arg(long)]
12    pub json: bool,
13}
14
15/// Arguments for the `get` subcommand.
16#[derive(Debug, Clone, Args)]
17pub struct GetArgs {
18    /// Name of the provider to display.
19    pub name: String,
20
21    /// Output the provider configuration as JSON.
22    #[arg(long)]
23    pub json: bool,
24}
25
26/// Arguments for the `add` subcommand.
27#[derive(Debug, Clone, Args)]
28pub struct AddArgs {
29    /// Name for the provider configuration.
30    pub name: String,
31
32    #[command(flatten)]
33    pub transport_args: AddMcpTransportArgs,
34
35    /// Maximum concurrent requests handled by the provider.
36    #[arg(long)]
37    pub max_concurrent_requests: Option<usize>,
38
39    /// Persist the provider in a disabled state.
40    #[arg(long)]
41    pub disabled: bool,
42}
43
44/// Mutually exclusive transport arguments for MCP providers.
45#[derive(Debug, Clone, Args)]
46#[command(
47    group(
48        ArgGroup::new("transport")
49            .args(["command", "url"])
50            .required(true)
51            .multiple(false)
52    )
53)]
54pub struct AddMcpTransportArgs {
55    #[command(flatten)]
56    pub stdio: Option<AddMcpStdioArgs>,
57
58    #[command(flatten)]
59    pub streamable_http: Option<AddMcpStreamableHttpArgs>,
60}
61
62/// stdio transport arguments for MCP providers.
63#[derive(Debug, Clone, Args)]
64pub struct AddMcpStdioArgs {
65    /// Command to launch the MCP server. Use `--url` for HTTP servers.
66    #[arg(long = "command", num_args = 1.., allow_hyphen_values = true, value_name = "COMMAND")]
67    pub command: Vec<String>,
68
69    /// Environment variables to export when launching the server.
70    #[arg(long, value_parser = parse_env_pair, value_name = "KEY=VALUE")]
71    pub env: Vec<(String, String)>,
72
73    /// Optional working directory for the command.
74    #[arg(long, value_name = "PATH")]
75    pub working_directory: Option<String>,
76}
77
78/// Streamable HTTP transport arguments for MCP providers.
79#[derive(Debug, Clone, Args)]
80pub struct AddMcpStreamableHttpArgs {
81    /// URL for the streamable HTTP MCP server.
82    #[arg(long)]
83    pub url: String,
84
85    /// Optional environment variable containing the Bearer [REDACTED]
86    #[arg(long = "bearer-token-env-var", value_name = "ENV_VAR", requires = "url")]
87    pub bearer_token_env_var: Option<String>,
88
89    /// Additional headers to send with each request (KEY=VALUE form).
90    #[arg(long, value_parser = parse_env_pair, value_name = "KEY=VALUE")]
91    pub header: Vec<(String, String)>,
92
93    /// Headers whose values are sourced from environment variables (KEY=ENV_VAR form).
94    #[arg(long, value_parser = parse_env_pair, value_name = "KEY=ENV_VAR")]
95    pub env_header: Vec<(String, String)>,
96}
97
98/// Arguments for the `remove` subcommand.
99#[derive(Debug, Clone, Args)]
100pub struct RemoveArgs {
101    /// Name of the provider to remove.
102    pub name: String,
103}
104
105/// Arguments for the `login` subcommand.
106#[derive(Debug, Clone, Args)]
107pub struct LoginArgs {
108    /// Name of the provider to authenticate.
109    pub name: String,
110}
111
112/// Arguments for the `logout` subcommand.
113#[derive(Debug, Clone, Args)]
114pub struct LogoutArgs {
115    /// Name of the provider to deauthenticate.
116    pub name: String,
117}
118
119/// Arguments for the `resources` subcommand.
120#[derive(Debug, Clone, Args)]
121pub struct ResourcesArgs {
122    /// Only show resources from this provider.
123    #[arg(long)]
124    pub provider: Option<String>,
125
126    /// Output the resources as JSON.
127    #[arg(long)]
128    pub json: bool,
129}
130
131/// Arguments for the `app` subcommand.
132#[derive(Debug, Clone, Args)]
133pub struct AppArgs {
134    /// Resource URI to inspect (e.g. `ui://server/page.html`).
135    pub uri: String,
136
137    /// Print the raw resource body (e.g. HTML source) instead of the summary.
138    #[arg(long, conflicts_with = "json")]
139    pub html: bool,
140
141    /// Output the inspection as JSON.
142    #[arg(long)]
143    pub json: bool,
144}
145
146fn parse_env_pair(raw: &str) -> Result<(String, String), String> {
147    let mut parts = raw.splitn(2, '=');
148    let key = parts
149        .next()
150        .map(str::trim)
151        .filter(|s| !s.is_empty())
152        .ok_or_else(|| "entries must be in KEY=VALUE form".to_owned())?;
153    let value = parts
154        .next()
155        .map(str::to_owned)
156        .ok_or_else(|| "entries must be in KEY=VALUE form".to_owned())?;
157    validate_agent_safe_text("env key", key).map_err(|err| err.to_string())?;
158    validate_agent_safe_text("env value", &value).map_err(|err| err.to_string())?;
159    Ok((key.to_owned(), value))
160}
161
162pub(crate) fn validate_provider_name(name: &str) -> Result<()> {
163    validate_agent_safe_text("provider name", name)?;
164    let is_valid = !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
165
166    if is_valid {
167        Ok(())
168    } else {
169        bail!("invalid provider name '{name}' (use letters, numbers, '-', '_')");
170    }
171}
172
173#[cfg(test)]
174mod tests {
175    use super::{
176        AddArgs, AddMcpStdioArgs, AddMcpTransportArgs, AppArgs, ResourcesArgs, parse_env_pair, validate_provider_name,
177    };
178    use clap::{Args, Command, FromArgMatches};
179
180    #[test]
181    fn add_args_accepts_documented_command_flag() {
182        let command = AddArgs::augment_args(Command::new("add"));
183        let matches = command
184            .try_get_matches_from([
185                "add",
186                "test-provider",
187                "--command",
188                "uvx",
189                "mcp-server-time",
190                "--local-timezone=Asia/Ho_Chi_Minh",
191            ])
192            .expect("documented --command form should parse");
193        let args = AddArgs::from_arg_matches(&matches).expect("parsed matches should map to AddArgs");
194
195        let AddMcpTransportArgs { stdio: Some(stdio), streamable_http: None } = args.transport_args else {
196            panic!("stdio transport should be selected");
197        };
198        let AddMcpStdioArgs { command, env, working_directory } = stdio;
199        assert_eq!(command, ["uvx", "mcp-server-time", "--local-timezone=Asia/Ho_Chi_Minh"]);
200        assert!(env.is_empty());
201        assert_eq!(working_directory, None);
202    }
203
204    #[test]
205    fn parse_env_pair_accepts_valid_input() {
206        let parsed = parse_env_pair("FOO=bar").expect("valid env pair");
207        assert_eq!(parsed.0, "FOO");
208        assert_eq!(parsed.1, "bar");
209    }
210
211    #[test]
212    fn parse_env_pair_rejects_control_chars() {
213        let err = parse_env_pair("FOO=bad\u{0000}value").expect_err("nul must be rejected");
214        assert!(err.contains("U+0000"));
215    }
216
217    #[test]
218    fn validate_provider_name_rejects_control_chars() {
219        let err = validate_provider_name("bad\u{0007}name").expect_err("control chars rejected");
220        assert!(err.to_string().contains("U+0007"));
221    }
222
223    #[test]
224    fn resources_args_accepts_provider_filter_and_json() {
225        let command = ResourcesArgs::augment_args(Command::new("resources"));
226        let matches = command
227            .try_get_matches_from(["resources", "--provider", "demo", "--json"])
228            .expect("documented resources flags should parse");
229        let args = ResourcesArgs::from_arg_matches(&matches).expect("parsed matches should map to ResourcesArgs");
230        assert_eq!(args.provider.as_deref(), Some("demo"));
231        assert!(args.json);
232    }
233
234    #[test]
235    fn app_args_accepts_uri_with_html() {
236        let command = AppArgs::augment_args(Command::new("app"));
237        let matches = command
238            .try_get_matches_from(["app", "ui://demo/app.html", "--html"])
239            .expect("documented app flags should parse");
240        let args = AppArgs::from_arg_matches(&matches).expect("parsed matches should map to AppArgs");
241        assert_eq!(args.uri, "ui://demo/app.html");
242        assert!(args.html);
243        assert!(!args.json);
244    }
245
246    #[test]
247    fn app_args_rejects_html_with_json() {
248        let command = AppArgs::augment_args(Command::new("app"));
249        command
250            .try_get_matches_from(["app", "ui://demo/app.html", "--html", "--json"])
251            .expect_err("html and json conflict");
252    }
253}