use openmoat_hosts::McpCommandForm;
use serde_json::Value;
fn kind(entry: &Value) -> Option<&str> {
entry.get("type").and_then(Value::as_str)
}
fn strings(value: &Value) -> Option<Vec<String>> {
value
.as_array()?
.iter()
.map(|item| item.as_str().map(str::to_owned))
.collect()
}
fn args_of(entry: &Value) -> Option<Vec<String>> {
match entry.get("args") {
None | Some(Value::Null) => Some(Vec::new()),
Some(args) => strings(args),
}
}
pub(super) fn parts(entry: &Value, form: McpCommandForm) -> Option<(String, Vec<String>)> {
match form {
McpCommandForm::CommandArgs => {
if kind(entry).is_some_and(|t| t != "stdio" && t != "local") {
return None;
}
let command = entry.get("command")?.as_str()?.to_owned();
Some((command, args_of(entry)?))
}
McpCommandForm::CommandList => {
if kind(entry) != Some("local") || entry.get("cmd").is_some() {
return None;
}
let mut line = strings(entry.get("command")?)?;
if line.is_empty() {
return None;
}
let program = line.remove(0);
Some((program, line))
}
McpCommandForm::CmdArgs => {
if kind(entry) != Some("stdio") || entry.get("command").is_some() {
return None;
}
let command = entry.get("cmd")?.as_str()?.to_owned();
Some((command, args_of(entry)?))
}
}
}
pub(super) fn written(
entry: &Value,
form: McpCommandForm,
program: String,
args: Vec<String>,
) -> Value {
let mut out = entry.clone();
match form {
McpCommandForm::CommandArgs => {
out["command"] = Value::String(program);
out["args"] = Value::from(args);
}
McpCommandForm::CommandList => {
let mut line = vec![program];
line.extend(args);
out["command"] = Value::from(line);
}
McpCommandForm::CmdArgs => {
out["cmd"] = Value::String(program);
out["args"] = Value::from(args);
}
}
out
}
pub fn not_wrappable(entry: &Value, form: McpCommandForm) -> Option<&'static str> {
if parts(entry, form).is_some() {
return None;
}
match (form, kind(entry)) {
(McpCommandForm::CommandList, Some("remote")) | (McpCommandForm::CommandArgs, _) => None,
(McpCommandForm::CommandList, _) if entry.get("command").is_none() => None,
(McpCommandForm::CommandList, _) => {
Some("its `command` is not a list of strings under `type: local`")
}
(McpCommandForm::CmdArgs, Some("stdio")) => {
Some("its `cmd` and `args` are not one program and a list of strings")
}
(McpCommandForm::CmdArgs, Some("inline_python")) => {
Some("it is inline Python, which has no command to run through the proxy")
}
(McpCommandForm::CmdArgs, _) => None,
}
}
pub fn cannot_wrap_advice(why: &str) -> String {
format!(
"`openmoat mcp wrap` cannot change that: {why}; remove it from the agent's configuration \
if you do not want it to run"
)
}
pub(super) fn program_key(form: McpCommandForm) -> &'static str {
match form {
McpCommandForm::CmdArgs => "cmd",
McpCommandForm::CommandArgs | McpCommandForm::CommandList => "command",
}
}
#[cfg(test)]
mod tests;