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
13 changes: 9 additions & 4 deletions apps/rocm/src/chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
//!
//! Callers in other modules, production and test-only, reach the moved items
//! through the `chat::` module boundary, so this module re-exports each one
//! another module reads (`run_internal_mcp_call`,
//! another module reads (`run_internal_mcp_call`, `mcp_call_cli_arguments`,
//! `rocm_chat_tool_system_prompt_for_host`, the tool-policy items, `any_substring`
//! and `ensure_flag`, and the test-only ones under `#[cfg(test)]`).

Expand All @@ -32,8 +32,13 @@ mod turn;
#[cfg(all(test, unix))]
pub(crate) use self::summaries::deterministic_comfyui_tool_summary;
// `run_internal_mcp_call` lives in `mcp_bridge.rs` and stays reachable here as
// `chat::run_internal_mcp_call` for `main.rs` and `dash_seam.rs`.
pub(crate) use self::mcp_bridge::run_internal_mcp_call;
// `chat::run_internal_mcp_call` for `main.rs` and `dash_seam.rs`;
// `mcp_call_cli_arguments` likewise for `main.rs`'s `rocm mcp-call` dispatch.
// `internal_mcp_tool_call` is read only by `dash_seam.rs`'s tests, so its
// re-export is `#[cfg(test)]`.
#[cfg(test)]
pub(crate) use self::mcp_bridge::internal_mcp_tool_call;
pub(crate) use self::mcp_bridge::{mcp_call_cli_arguments, run_internal_mcp_call};
// `rocm_chat_tool_system_prompt_for_host` lives in `turn.rs` and stays
// reachable here as `chat::rocm_chat_tool_system_prompt_for_host` for `dash.rs`.
use self::turn::render_chat_prompt_result_with_progress;
Expand All @@ -49,7 +54,7 @@ pub(crate) use crate::rocm_argv::ensure_flag;
// here as `chat::<item>` for `dash_seam.rs`. `ChatRocmCommandAction`,
// `rocm_chat_tool_requested_args`, `chat_install_driver_action` and
// `chat_rocm_command_action_from_args` are read through `chat::` only by other
// modules' tests (`driver_plan.rs`, `system_packages.rs`), and this module does
// modules' tests (`driver_plan.rs`, `system_packages.rs`, `dash_seam.rs`), and this module does
// not call them itself, so their re-export below is `#[cfg(test)]`.
#[cfg(test)]
pub(crate) use crate::tool_policy::{
Expand Down
193 changes: 178 additions & 15 deletions apps/rocm/src/chat/mcp_bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,12 @@
//! calls back into the turn loop in `chat/turn.rs`, tests included; the turn
//! loop reads this module's items through `super::mcp_bridge`.
//! `run_internal_mcp_call` stays reachable as `chat::run_internal_mcp_call` for
//! `main.rs` and `dash_seam.rs`.
//! `main.rs` and `dash_seam.rs`. It runs the argument object exactly as given,
//! through `internal_mcp_tool_call` (re-exported, test-only, for `dash_seam.rs`'s
//! tests), and never unwraps a nested `arguments` field. Unwrapping a pasted MCP
//! `tools/call` params envelope is the `rocm mcp-call` command's own boundary
//! step, `mcp_call_cli_arguments`, re-exported as `chat::mcp_call_cli_arguments`
//! for `main.rs`.

use super::summaries::managed_service_running_state;
use crate::automations::{render_automations_text, render_daemon_text};
Expand Down Expand Up @@ -142,13 +147,8 @@ pub(crate) fn run_internal_mcp_call(
arguments: serde_json::Value,
allow_mutation: bool,
) -> Result<serde_json::Value> {
let arguments = internal_mcp_arguments(arguments);
let call = providers::ChatToolCall {
id: None,
name: name.to_owned(),
arguments: serde_json::Value::Object(arguments.clone()),
};
validate_chat_tool_call(&call)?;
let call = internal_mcp_tool_call(name, arguments)?;
let arguments = call.arguments.as_object().cloned().unwrap_or_default();
if !chat_tool_call_is_read_only(&call) && !allow_mutation {
bail!(
"MCP tool `{name}` changes local ROCm state; rerun `rocm mcp-call {name}` with --allow-mutation only after explicit user approval"
Expand Down Expand Up @@ -388,14 +388,60 @@ pub(crate) fn run_internal_mcp_call(
}
}

fn internal_mcp_arguments(value: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
if let Some(arguments) = value
/// The validated tool call `run_internal_mcp_call` executes for `arguments`.
///
/// `arguments` is used exactly as given: it is the object the dash approval
/// card was rendered from (`dash_seam::BinToolExecutor`), so validating and
/// running anything else — such as an object nested inside it — would run a
/// command the user never saw. `validate_chat_tool_call` refuses a nested
/// `arguments` key outright, so no such object reaches either side.
pub(crate) fn internal_mcp_tool_call(
name: &str,
arguments: serde_json::Value,
) -> Result<providers::ChatToolCall> {
let call = providers::ChatToolCall {
id: None,
name: name.to_owned(),
arguments,
};
validate_chat_tool_call(&call)?;
Ok(call)
}

/// The tool arguments for `rocm mcp-call <name> --arguments-json <json>`.
///
/// Besides a bare arguments object, the hidden command accepts a pasted MCP
/// `tools/call` params envelope — `{"name": ..., "arguments": {...}}` — and
/// unwraps it here, at the CLI boundary, where the JSON is the operator's own.
/// An envelope holds only `name`, `arguments` and the protocol's optional
/// `_meta`, which carries request metadata rather than tool input and is
/// dropped. Only such a pure envelope is unwrapped: an object that mixes tool
/// fields with an `arguments` key is passed through whole, so validation
/// refuses it rather than silently picking one of the two payloads.
pub(crate) fn mcp_call_cli_arguments(
name: &str,
value: serde_json::Value,
) -> Result<serde_json::Value> {
let Some(object) = value.as_object() else {
return Ok(value);
};
let is_envelope = object
.get("arguments")
.and_then(serde_json::Value::as_object)
.is_some_and(serde_json::Value::is_object)
&& object
.keys()
.all(|key| matches!(key.as_str(), "name" | "arguments" | "_meta"));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: an MCP params object carrying any other protocol key (e.g. task) counts as "mixed" and gets the nested-arguments refusal. Fine for a hidden command, but the refusal could say which keys make a pure envelope (name, arguments, _meta).

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on both counts. Any key outside name, arguments and _meta makes is_envelope false, so the object passes through whole and validate_chat_tool_call refuses it with "must not contain a nested arguments field", which doesn't tell the caller the envelope itself was the problem. It fails closed, so I've kept it out of this PR; a follow-up can have mcp_call_cli_arguments name the keys a pure envelope may hold when it sees an arguments object next to other keys.

if !is_envelope {
return Ok(value);
}
if let Some(envelope_name) = object.get("name")
&& envelope_name.as_str() != Some(name)
{
return arguments.clone();
bail!(
"arguments JSON names tool {envelope_name}, but `rocm mcp-call` was asked to run `{name}`"
);
}
value.as_object().cloned().unwrap_or_default()
Ok(object["arguments"].clone())
}

fn internal_mcp_tool_success(text: String, structured: serde_json::Value) -> serde_json::Value {
Expand Down Expand Up @@ -755,8 +801,11 @@ pub(super) fn run_chat_read_only_tool(
))
}
"install_sdk_dry_run" => {
let arguments = internal_mcp_arguments(call.arguments.clone());
let args = internal_mcp_install_sdk_args(&arguments, true)?;
let arguments = call
.arguments
.as_object()
.context("install_sdk_dry_run arguments must be a JSON object")?;
let args = internal_mcp_install_sdk_args(arguments, true)?;
let output = run_rocm_command_for_paths(paths, &args, Duration::from_mins(2))?;
Ok(internal_mcp_tool_result_from_command(
"Ran `rocm install sdk --dry-run`.",
Expand Down Expand Up @@ -935,6 +984,120 @@ mod tests {
assert_eq!(content["lines_requested"], 50, "{content}");
}

#[test]
fn mcp_call_cli_unwraps_only_a_pure_params_envelope() {
// A pasted `tools/call` params object is unwrapped to its arguments.
assert_eq!(
mcp_call_cli_arguments(
"stop_server",
serde_json::json!({
"name": "stop_server",
"arguments": { "service_id": "svc-1" },
}),
)
.expect("envelope unwraps"),
serde_json::json!({ "service_id": "svc-1" })
);
assert_eq!(
mcp_call_cli_arguments(
"stop_server",
serde_json::json!({ "arguments": { "service_id": "svc-1" } }),
)
.expect("envelope without a name unwraps"),
serde_json::json!({ "service_id": "svc-1" })
);
// The protocol's optional `_meta` does not stop an envelope being one;
// it is request metadata and is dropped with the wrapper.
assert_eq!(
mcp_call_cli_arguments(
"stop_server",
serde_json::json!({
"name": "stop_server",
"arguments": { "service_id": "svc-1" },
"_meta": { "progressToken": 1 },
}),
)
.expect("envelope with _meta unwraps"),
serde_json::json!({ "service_id": "svc-1" })
);
// A bare arguments object passes through untouched.
let bare = serde_json::json!({ "service_id": "svc-1" });
assert_eq!(
mcp_call_cli_arguments("stop_server", bare.clone()).expect("bare passes"),
bare
);
// An envelope naming a different tool is refused rather than run as
// the tool on the command line.
assert!(
mcp_call_cli_arguments(
"stop_server",
serde_json::json!({
"name": "launch_server",
"arguments": { "service_id": "svc-1" },
}),
)
.is_err()
);
// A `name` that is not a string cannot name the tool on the command
// line, so the envelope is refused rather than unwrapped.
assert!(
mcp_call_cli_arguments(
"stop_server",
serde_json::json!({ "name": 5, "arguments": { "service_id": "svc-1" } }),
)
.is_err()
);
// An `arguments` that is not an object is not an envelope: the value
// passes through whole, and validation refuses its nested field.
let scalar = serde_json::json!({ "arguments": 5 });
assert_eq!(
mcp_call_cli_arguments("stop_server", scalar.clone()).expect("passes through"),
scalar
);
}

#[test]
fn mcp_call_refuses_arguments_that_are_not_an_object() {
// The replay runs the value it is given, so a value that is not an
// object is refused rather than read as an empty argument object.
let (root, paths) = test_paths("mcp-call-non-object-arguments");
for value in [
serde_json::Value::Null,
serde_json::json!([]),
serde_json::json!("s"),
] {
let passed = mcp_call_cli_arguments("examine", value.clone()).expect("passes through");
assert_eq!(passed, value);
let err = run_internal_mcp_call(&paths, "examine", passed, false)
.expect_err("non-object arguments must be refused");
assert!(
err.to_string().contains("must be a JSON object"),
"unexpected error for {value}: {err}"
);
}
let _ = fs::remove_dir_all(&root);
}

#[test]
fn mcp_call_refuses_tool_fields_mixed_with_a_nested_arguments_object() {
// Mixed objects are not an envelope: they reach validation whole, and
// validation refuses them instead of choosing one of the two payloads.
let mixed = serde_json::json!({
"service_id": "shown-service",
"arguments": { "service_id": "other-service" },
});
let passed = mcp_call_cli_arguments("stop_server", mixed.clone()).expect("passes through");
assert_eq!(passed, mixed);
let (root, paths) = test_paths("mcp-call-nested-arguments");
let err = run_internal_mcp_call(&paths, "stop_server", passed, true)
.expect_err("a nested arguments object must be refused before running");
assert!(
err.to_string().contains("nested `arguments`"),
"unexpected error: {err}"
);
let _ = fs::remove_dir_all(&root);
}

#[test]
fn mcp_tool_result_text_joins_text_content_items() {
let value = serde_json::json!({
Expand Down
Loading
Loading