diff --git a/neurosploit-rs/app/src/c2xcli.rs b/neurosploit-rs/app/src/c2xcli.rs index 7ff32d9..2a220e0 100644 --- a/neurosploit-rs/app/src/c2xcli.rs +++ b/neurosploit-rs/app/src/c2xcli.rs @@ -1,14 +1,15 @@ -//! `neurosploit c2x …` — external C2 session reuse (Sliver/Havoc/Mythic/CS). +//! `neurosploit c2x …` — external C2 session reuse (any MCP, not just ours). //! -//! Import an exported session list, list what is known, and pick the best -//! existing session for a target so chain steps reuse footholds. +//! Import an exported session list, or sync directly from any MCP C2 server +//! (stdio or HTTP): Sliver/Havoc/Mythic/Adaptix/Cobalt Strike or a custom +//! `--command`/`--http` server. Then pick and task the best existing session. use clap::Subcommand; use serde_json::{json, Value}; #[derive(Subcommand)] pub enum C2xCmd { - /// Import an exported session list from an external C2 (Sliver/Havoc/Mythic/CS). + /// Import an exported session list from an external C2. Import { /// sliver | havoc | mythic | cobaltstrike #[arg(long)] @@ -31,25 +32,26 @@ pub enum C2xCmd { #[arg(long)] json: bool, }, - /// Discover sessions from any stdio MCP C2 server (Sliver/Havoc/Mythic/ - /// Adaptix or a custom `--command`) and import them. + /// Discover sessions from any MCP C2 server (stdio or HTTP) and import them. Sync { - /// Built-in C2 profile: sliver | havoc | mythic | adaptix. + /// Built-in C2 profile: sliver | havoc | mythic | adaptix | cobaltstrike. #[arg(long)] profile: Option, /// Arbitrary stdio MCP command (overrides --profile). #[arg(long)] command: Option, - /// Arg for --command (repeatable). #[arg(long = "arg")] args: Vec, - /// Env KEY=VAL for --command (repeatable). #[arg(long = "env")] env: Vec, - /// Session kind label (defaults to the profile name). + /// HTTP MCP endpoint (Streamable HTTP), e.g. Cobalt Strike. + #[arg(long)] + http: Option, + /// HTTP header `Key: Value` (repeatable) for --http. + #[arg(long = "header")] + headers: Vec, #[arg(long)] kind: Option, - /// Explicit session-listing tool (default: auto-detect). #[arg(long)] tool: Option, #[arg(long, default_value_t = 60)] @@ -57,6 +59,40 @@ pub enum C2xCmd { #[arg(long)] json: bool, }, + /// Execute a command through the best existing session (auto-task a reused + /// foothold). High-impact commands are gated by the operator checkpoint. + Task { + /// Target IP / host / user to match an existing session. + #[arg(long)] + target: String, + /// Shell command to run on the target. + #[arg(long, allow_hyphen_values = true)] + cmd: String, + /// Built-in C2 profile: sliver | havoc | mythic | adaptix | cobaltstrike. + #[arg(long)] + profile: Option, + /// Arbitrary stdio MCP command (overrides --profile). + #[arg(long)] + mcp: Option, + #[arg(long = "mcp-arg")] + mcp_args: Vec, + #[arg(long = "mcp-env")] + mcp_env: Vec, + /// HTTP MCP endpoint (Streamable HTTP), e.g. Cobalt Strike. + #[arg(long)] + http: Option, + #[arg(long = "header")] + headers: Vec, + #[arg(long)] + kind: Option, + /// Explicit exec tool (default: auto-detect). + #[arg(long)] + tool: Option, + #[arg(long, default_value_t = 120)] + timeout: u64, + #[arg(long)] + json: bool, + }, /// Print the redacted reuse prompt block injected into agent prompts. Context { #[arg(long)] @@ -73,7 +109,15 @@ fn env_pairs(pairs: &[String]) -> Vec<(String, String)> { .collect() } -/// Resolve a profile to its stdio MCP command/args/env from mcp_profiles. +fn header_pairs(pairs: &[String]) -> Vec<(String, String)> { + pairs + .iter() + .filter_map(|h| h.split_once(':')) + .map(|(k, v)| (k.trim().to_string(), v.trim().to_string())) + .filter(|(k, _)| !k.is_empty()) + .collect() +} + fn profile_stdio(name: &str) -> Option<(String, Vec, Vec<(String, String)>)> { use harness::mcp_profiles::{profile, Profile}; let p = match name.to_ascii_lowercase().as_str() { @@ -88,30 +132,94 @@ fn profile_stdio(name: &str) -> Option<(String, Vec, Vec<(String, String let args = cfg .get("args") .and_then(|x| x.as_array()) - .map(|a| { - a.iter() - .filter_map(|v| v.as_str()) - .map(harness::mcp_client::expand_vars) - .collect() - }) + .map(|a| a.iter().filter_map(|v| v.as_str()).map(harness::mcp_client::expand_vars).collect()) .unwrap_or_default(); let env = cfg .get("env") .and_then(|x| x.as_object()) .map(|o| { o.iter() - .map(|(k, v)| { - ( - k.clone(), - harness::mcp_client::expand_vars(v.as_str().unwrap_or("")), - ) - }) + .map(|(k, v)| (k.clone(), harness::mcp_client::expand_vars(v.as_str().unwrap_or("")))) .collect() }) .unwrap_or_default(); Some((command, args, env)) } +fn profile_http(name: &str) -> Option { + use harness::mcp_profiles::{profile, Profile}; + match name.to_ascii_lowercase().as_str() { + "cobaltstrike" | "cobalt" | "cs" => { + let cfg = profile(&Profile::CobaltStrike).config; + cfg.get("url").and_then(|x| x.as_str()).map(|s| s.to_string()) + } + _ => None, + } +} + +enum Tx { + Stdio { + cmd: String, + args: Vec, + env: Vec<(String, String)>, + kind: String, + }, + Http { + url: String, + headers: Vec<(String, String)>, + kind: String, + }, +} + +#[allow(clippy::too_many_arguments)] +fn resolve( + profile: Option<&str>, + stdio_cmd: Option<&str>, + args: &[String], + env: &[String], + http: Option<&str>, + headers: &[String], + kind: Option<&str>, +) -> Result { + if let Some(url) = http.map(str::trim).filter(|u| !u.is_empty()) { + return Ok(Tx::Http { + url: url.to_string(), + headers: header_pairs(headers), + kind: kind.map(|s| s.to_string()).unwrap_or_else(|| "http".into()), + }); + } + if let Some(c) = stdio_cmd.map(str::trim).filter(|c| !c.is_empty()) { + return Ok(Tx::Stdio { + cmd: c.to_string(), + args: args.to_vec(), + env: env_pairs(env), + kind: kind.map(|s| s.to_string()).unwrap_or_else(|| "custom".into()), + }); + } + if let Some(p) = profile { + if let Some((cmd, mut a, e)) = profile_stdio(p) { + a.extend(args.iter().cloned()); + return Ok(Tx::Stdio { + cmd, + args: a, + env: e, + kind: kind.map(|s| s.to_string()).unwrap_or_else(|| p.to_string()), + }); + } + if let Some(url) = profile_http(p) { + return Ok(Tx::Http { + url, + headers: header_pairs(headers), + kind: kind.map(|s| s.to_string()).unwrap_or_else(|| "cobaltstrike".into()), + }); + } + return Err(format!( + "unknown/incompatible profile '{p}' — use --command/--mcp (stdio MCP) or --http " + )); + } + Err("pass --profile, --command/--mcp , or --http ".into()) +} + pub async fn handle_c2x(cmd: C2xCmd) -> anyhow::Result<()> { let out: Value = match cmd { C2xCmd::Import { kind, file, .. } => { @@ -135,48 +243,73 @@ pub async fn handle_c2x(cmd: C2xCmd) -> anyhow::Result<()> { command, args, env, + http, + headers, kind, tool, timeout, .. } => { - let (cmd, arglist, envlist, kind) = if let Some(c) = - command.as_deref().map(str::trim).filter(|c| !c.is_empty()) - { - ( - c.to_string(), - args.clone(), - env_pairs(&env), - kind.clone().unwrap_or_else(|| "custom".to_string()), - ) - } else if let Some(p) = profile.as_deref() { - match profile_stdio(p) { - Some((cmd, mut a, e)) => { - a.extend(args.iter().cloned()); - ( - cmd, - a, - e, - kind.clone().unwrap_or_else(|| p.to_string()), - ) - } - None => { - return Err(anyhow::anyhow!( - "unknown/incompatible profile '{p}' — use --command for a custom stdio MCP server (Cobalt Strike is HTTP: export its sessions and use `c2x import`)" - )) - } + let tx = resolve( + profile.as_deref(), + command.as_deref(), + &args, + &env, + http.as_deref(), + &headers, + kind.as_deref(), + ).map_err(|e| anyhow::anyhow!(e))?; + let report = match tx { + Tx::Stdio { cmd, args, env, kind } => { + harness::c2_reuse::sync_stdio(&cmd, &args, &env, &kind, tool.as_deref(), timeout).await } - } else { - return Err(anyhow::anyhow!( - "pass --profile or --command " - )); - }; - let report = - harness::c2_reuse::sync_stdio(&cmd, &arglist, &envlist, &kind, tool.as_deref(), timeout) - .await - .map_err(|e| anyhow::anyhow!(e))?; + Tx::Http { url, headers, kind } => { + harness::c2_reuse::sync_http(&url, &headers, &kind, tool.as_deref(), timeout).await + } + } + .map_err(|e| anyhow::anyhow!(e))?; json!({ "ok": true, "sync": report, "total": harness::c2_reuse::load().len() }) } + C2xCmd::Task { + target, + cmd, + profile, + mcp, + mcp_args, + mcp_env, + http, + headers, + kind, + tool, + timeout, + .. + } => { + let tx = resolve( + profile.as_deref(), + mcp.as_deref(), + &mcp_args, + &mcp_env, + http.as_deref(), + &headers, + kind.as_deref(), + ).map_err(|e| anyhow::anyhow!(e))?; + let report = match tx { + Tx::Stdio { cmd: mcmd, args, env, kind } => { + harness::c2_reuse::task_stdio( + &mcmd, &args, &env, &kind, &target, &cmd, tool.as_deref(), timeout, + ) + .await + } + Tx::Http { url, headers, kind } => { + harness::c2_reuse::task_http( + &url, &headers, &kind, &target, &cmd, tool.as_deref(), timeout, + ) + .await + } + } + .map_err(|e| anyhow::anyhow!(e))?; + json!({ "ok": true, "task": report }) + } C2xCmd::Context { .. } => json!({ "context": harness::c2_reuse::context() }), }; println!( diff --git a/neurosploit-rs/crates/harness/src/c2_reuse.rs b/neurosploit-rs/crates/harness/src/c2_reuse.rs index fa0baca..4edcbbb 100644 --- a/neurosploit-rs/crates/harness/src/c2_reuse.rs +++ b/neurosploit-rs/crates/harness/src/c2_reuse.rs @@ -299,55 +299,28 @@ pub struct SyncReport { pub total: usize, } -/// Discover C2 sessions from any stdio MCP server: initialize, list tools, -/// pick the session tool (or `tool` override), call it, normalize and persist. -pub async fn sync_stdio( - command: &str, - args: &[String], - env: &[(String, String)], +async fn sync_with( + t: &mut crate::mcp_client::McpTransport, kind: &str, tool: Option<&str>, - timeout_secs: u64, + to: std::time::Duration, ) -> Result { - use std::time::Duration; - let to = Duration::from_secs(timeout_secs.max(1)); - let mut c = crate::mcp_client::McpStdio::spawn(command, args, env).await?; - if let Err(e) = c.initialize(to).await { - c.kill(); - return Err(e); - } - let tools = match c.tools_list(to).await { - Ok(t) => t, - Err(e) => { - c.kill(); - return Err(e); - } - }; + t.initialize(to).await?; + let tools = t.tools_list(to).await?; let names: Vec = tools .iter() - .filter_map(|t| t.get("name").and_then(|x| x.as_str()).map(|s| s.to_string())) + .filter_map(|x| x.get("name").and_then(|v| v.as_str()).map(|s| s.to_string())) .collect(); - let chosen = match tool.map(str::trim).filter(|t| !t.is_empty()) { - Some(t) => t.to_string(), - None => match find_session_tool(kind, &names) { - Some(t) => t, - None => { - let avail = names.join(", "); - c.kill(); - return Err(format!( - "no session-listing tool found on the MCP server (available: {avail}); pass --tool " - )); - } - }, + let chosen = match tool.map(str::trim).filter(|x| !x.is_empty()) { + Some(x) => x.to_string(), + None => find_session_tool(kind, &names).ok_or_else(|| { + format!( + "no session-listing tool found (available: {}); pass --tool ", + names.join(", ") + ) + })?, }; - let res = match c.call_tool(&chosen, serde_json::json!({}), to).await { - Ok(r) => r, - Err(e) => { - c.kill(); - return Err(e); - } - }; - c.kill(); + let res = t.call_tool(&chosen, serde_json::json!({}), to).await?; let text = extract_tool_text(&res); let parsed = parse_export(kind, &text) .map_err(|e| format!("could not parse `{chosen}` output: {e}"))?; @@ -362,6 +335,236 @@ pub async fn sync_stdio( }) } +/// Discover sessions via a stdio MCP C2 server. +pub async fn sync_stdio( + command: &str, + args: &[String], + env: &[(String, String)], + kind: &str, + tool: Option<&str>, + timeout_secs: u64, +) -> Result { + let to = std::time::Duration::from_secs(timeout_secs.max(1)); + let mut t = crate::mcp_client::McpTransport::Stdio( + crate::mcp_client::McpStdio::spawn(command, args, env).await?, + ); + let r = sync_with(&mut t, kind, tool, to).await; + t.kill(); + r +} + +/// Discover sessions via an HTTP (Streamable HTTP) MCP server — e.g. Cobalt Strike. +pub async fn sync_http( + url: &str, + headers: &[(String, String)], + kind: &str, + tool: Option<&str>, + timeout_secs: u64, +) -> Result { + let to = std::time::Duration::from_secs(timeout_secs.max(1)); + let mut t = crate::mcp_client::McpTransport::Http(crate::mcp_client::McpHttp::new( + url, + headers.to_vec(), + )); + sync_with(&mut t, kind, tool, to).await +} + +/// Preferred command-execution tools per C2. +pub fn exec_tools_for(kind: &str) -> &'static [&'static str] { + match normalize_kind(kind).as_str() { + "sliver" => &["sliver_execute", "sliver_shell"], + "havoc" => &["havoc_demon_shell"], + "mythic" => &["mythic_shell"], + "adaptix" => &["powershell", "execute_assembly", "execute_bof"], + "cobaltstrike" => &["cs_execute_command"], + _ => &[], + } +} + +/// Pick an exec tool from an MCP server's tool names (per-C2 preferred, then a +/// name that looks like command/shell execution). +pub fn find_exec_tool(kind: &str, names: &[String]) -> Option { + for pref in exec_tools_for(kind) { + if names.iter().any(|n| n.as_str() == *pref) { + return Some((*pref).to_string()); + } + } + let good = ["exec", "shell", "command", "powershell"]; + let bad = [ + "list", "kill", "stop", "start", "upload", "download", "file", "screenshot", "sleep", + "token", "jobs", "bof", "assembly", "inject", "note", "history", + ]; + names + .iter() + .find(|n| { + let l = n.to_ascii_lowercase(); + good.iter().any(|g| l.contains(g)) && !bad.iter().any(|b| l.contains(b)) + }) + .cloned() +} + +/// Build a tool-call argument object from an exec tool's `inputSchema`, mapping +/// the session id and command into whatever property names the schema declares. +pub fn build_tool_args(schema: &Value, session_id: &str, command: &str) -> Value { + let mut obj = serde_json::Map::new(); + let (mut sid_set, mut cmd_set) = (false, false); + if let Some(props) = schema.get("properties").and_then(|x| x.as_object()) { + for key in props.keys() { + let l = key.to_ascii_lowercase(); + let is_sid = l == "session_id" + || l == "session" + || l == "beacon_id" + || l == "demon_id" + || l == "callback_id" + || l == "agent_id" + || l == "id" + || (l.ends_with("_id") + && ["session", "beacon", "demon", "callback", "agent"] + .iter() + .any(|k| l.contains(k))); + let is_cmd = l == "command" + || l == "cmd" + || l == "script" + || l == "shell" + || l == "args" + || l == "command_line" + || l == "payload"; + if !sid_set && is_sid { + obj.insert(key.clone(), serde_json::json!(session_id)); + sid_set = true; + } else if !cmd_set && is_cmd { + obj.insert(key.clone(), serde_json::json!(command)); + cmd_set = true; + } + } + } + if !sid_set { + obj.insert("session_id".into(), serde_json::json!(session_id)); + } + if !cmd_set { + obj.insert("command".into(), serde_json::json!(command)); + } + Value::Object(obj) +} + +#[derive(Debug, Clone, Serialize)] +pub struct TaskReport { + pub kind: String, + pub session_id: String, + pub tool: String, + pub output: String, +} + +async fn task_with( + t: &mut crate::mcp_client::McpTransport, + kind: &str, + target: &str, + command: &str, + tool: Option<&str>, + to: std::time::Duration, +) -> Result { + let sessions = load(); + let s = select(&sessions, target) + .ok_or_else(|| { + format!("no existing external C2 session matches '{target}' (run `c2x sync`/`c2x import` first)") + })? + .clone(); + // Same high-impact policy as the worker loop: destructive/lateral commands + // are blocked or recorded before they reach the C2. + match crate::checkpoint::gate("remote-exec", command) { + crate::checkpoint::GateDecision::Block(v) => { + return Err(format!("blocked by operator checkpoint: {} (id={})", v.reason, v.id)); + } + crate::checkpoint::GateDecision::Record(v) => { + crate::activity::record_step( + "checkpoint", + &format!("c2x task {command}"), + &format!("record:{}", v.id), + 0, + true, + ); + } + crate::checkpoint::GateDecision::Allow => {} + } + t.initialize(to).await?; + let tools = t.tools_list(to).await?; + let names: Vec = tools + .iter() + .filter_map(|x| x.get("name").and_then(|v| v.as_str()).map(|s| s.to_string())) + .collect(); + let chosen = match tool.map(str::trim).filter(|x| !x.is_empty()) { + Some(x) => x.to_string(), + None => find_exec_tool(kind, &names).ok_or_else(|| { + format!( + "no exec tool found on the C2 MCP (available: {}); pass --tool ", + names.join(", ") + ) + })?, + }; + let schema = tools + .iter() + .find(|x| x.get("name").and_then(|v| v.as_str()) == Some(chosen.as_str())) + .and_then(|x| x.get("inputSchema")) + .cloned() + .unwrap_or(Value::Null); + let args = build_tool_args(&schema, &s.id, command); + let res = t.call_tool(&chosen, args, to).await?; + let output = extract_tool_text(&res); + crate::activity::record_step( + "c2", + &format!("{} {} :: {}", s.kind, s.host, command), + &output, + 0, + true, + ); + Ok(TaskReport { + kind: normalize_kind(kind), + session_id: s.id, + tool: chosen, + output, + }) +} + +/// Execute a command through the best existing session via a stdio C2 MCP. +#[allow(clippy::too_many_arguments)] +pub async fn task_stdio( + command: &str, + args: &[String], + env: &[(String, String)], + kind: &str, + target: &str, + shell_command: &str, + tool: Option<&str>, + timeout_secs: u64, +) -> Result { + let to = std::time::Duration::from_secs(timeout_secs.max(1)); + let mut t = crate::mcp_client::McpTransport::Stdio( + crate::mcp_client::McpStdio::spawn(command, args, env).await?, + ); + let r = task_with(&mut t, kind, target, shell_command, tool, to).await; + t.kill(); + r +} + +/// Execute a command through the best existing session via an HTTP C2 MCP. +#[allow(clippy::too_many_arguments)] +pub async fn task_http( + url: &str, + headers: &[(String, String)], + kind: &str, + target: &str, + shell_command: &str, + tool: Option<&str>, + timeout_secs: u64, +) -> Result { + let to = std::time::Duration::from_secs(timeout_secs.max(1)); + let mut t = crate::mcp_client::McpTransport::Http(crate::mcp_client::McpHttp::new( + url, + headers.to_vec(), + )); + task_with(&mut t, kind, target, shell_command, tool, to).await +} + /// Redacted prompt block: existing footholds a chain step can reuse. pub fn context() -> String { let sessions = load(); @@ -461,6 +664,35 @@ mod tests { assert!(extract_tool_text(&s).contains("\"a\"")); } + #[test] + fn builds_exec_args_from_schema() { + let schema = serde_json::json!({ + "properties": {"beacon_id": {"type": "string"}, "command_line": {"type": "string"}, "other": {}} + }); + let a = build_tool_args(&schema, "s1", "whoami"); + assert_eq!(a["beacon_id"], "s1"); + assert_eq!(a["command_line"], "whoami"); + assert!(a.get("other").is_none()); + // No schema → heuristic keys. + let a2 = build_tool_args(&Value::Null, "s2", "id"); + assert_eq!(a2["session_id"], "s2"); + assert_eq!(a2["command"], "id"); + } + + #[test] + fn picks_exec_tool_per_c2() { + let names: Vec = ["sliver_sessions", "sliver_execute"] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!(find_exec_tool("sliver", &names).as_deref(), Some("sliver_execute")); + let custom: Vec = ["list_targets", "run_shell"] + .iter() + .map(|s| s.to_string()) + .collect(); + assert_eq!(find_exec_tool("custom", &custom).as_deref(), Some("run_shell")); + } + #[test] fn merge_dedupes_by_kind_and_id() { let a = parse_export("sliver", r#"[{"id":"x","host":"h1","ip":"10.0.0.1"}]"#).unwrap(); diff --git a/neurosploit-rs/crates/harness/src/mcp_client.rs b/neurosploit-rs/crates/harness/src/mcp_client.rs index 4b486b8..38ebe9a 100644 --- a/neurosploit-rs/crates/harness/src/mcp_client.rs +++ b/neurosploit-rs/crates/harness/src/mcp_client.rs @@ -177,6 +177,174 @@ pub fn expand_vars(s: &str) -> String { out } +// --------------------------------------------------------------------------- +// HTTP transport (Streamable HTTP MCP): Cobalt Strike and any HTTP MCP server. +// --------------------------------------------------------------------------- + +pub struct McpHttp { + client: reqwest::Client, + url: String, + headers: Vec<(String, String)>, + session_id: Option, + next_id: u64, +} + +impl McpHttp { + pub fn new(url: &str, headers: Vec<(String, String)>) -> Self { + Self { + client: reqwest::Client::new(), + url: url.trim().to_string(), + headers, + session_id: None, + next_id: 1, + } + } + + fn apply_headers(&self, req: reqwest::RequestBuilder) -> reqwest::RequestBuilder { + let mut req = req; + for (k, v) in &self.headers { + req = req.header(k, v); + } + if let Some(sid) = &self.session_id { + req = req.header("mcp-session-id", sid); + } + req + } + + async fn rpc(&mut self, method: &str, params: Value, timeout: Duration) -> Result { + let id = self.next_id; + self.next_id += 1; + let body = json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }); + let req = self + .client + .post(&self.url) + .header("accept", "application/json, text/event-stream") + .header("content-type", "application/json") + .timeout(timeout) + .json(&body); + let resp = self + .apply_headers(req) + .send() + .await + .map_err(|e| format!("MCP HTTP request failed: {e}"))?; + if let Some(sid) = resp.headers().get("mcp-session-id").and_then(|v| v.to_str().ok()) { + self.session_id = Some(sid.to_string()); + } + let status = resp.status(); + let ctype = resp + .headers() + .get("content-type") + .and_then(|v| v.to_str().ok()) + .unwrap_or("") + .to_ascii_lowercase(); + let text = resp.text().await.unwrap_or_default(); + if !status.is_success() { + return Err(format!( + "MCP HTTP {}: {}", + status, + text.chars().take(200).collect::() + )); + } + let v = if ctype.contains("text/event-stream") { + parse_sse_json(&text, id)? + } else { + serde_json::from_str(&text).map_err(|e| format!("MCP HTTP unparseable body: {e}"))? + }; + if let Some(err) = v.get("error") { + return Err(format!("MCP error: {err}")); + } + Ok(v.get("result").cloned().unwrap_or(Value::Null)) + } + + pub async fn initialize(&mut self, timeout: Duration) -> Result<(), String> { + self.rpc( + "initialize", + json!({ + "protocolVersion": DEFAULT_PROTOCOL, + "capabilities": {}, + "clientInfo": { "name": "neurosploit", "version": env!("CARGO_PKG_VERSION") } + }), + timeout, + ) + .await?; + // Fire-and-forget initialized notification. + let body = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" }); + let req = self + .client + .post(&self.url) + .header("content-type", "application/json") + .timeout(timeout) + .json(&body); + let _ = self.apply_headers(req).send().await; + Ok(()) + } + + pub async fn tools_list(&mut self, timeout: Duration) -> Result, String> { + let r = self.rpc("tools/list", json!({}), timeout).await?; + Ok(r.get("tools").and_then(|x| x.as_array()).cloned().unwrap_or_default()) + } + + pub async fn call_tool(&mut self, name: &str, args: Value, timeout: Duration) -> Result { + self.rpc("tools/call", json!({ "name": name, "arguments": args }), timeout) + .await + } +} + +fn parse_sse_json(text: &str, id: u64) -> Result { + let mut fallback: Option = None; + for line in text.lines() { + let line = line.trim_start(); + let Some(payload) = line.strip_prefix("data:") else { continue }; + let payload = payload.trim(); + if payload.is_empty() || payload == "[DONE]" { + continue; + } + if let Ok(v) = serde_json::from_str::(payload) { + let rid = v.get("id").and_then(|x| x.as_u64()); + if rid == Some(id) { + return Ok(v); + } + if fallback.is_none() && (v.get("result").is_some() || v.get("error").is_some()) { + fallback = Some(v); + } + } + } + fallback.ok_or_else(|| "no JSON-RPC response in the SSE body".to_string()) +} + +/// Transport-agnostic MCP client so callers (C2 sync/task) work for both stdio +/// and HTTP servers without duplicating logic. +pub enum McpTransport { + Stdio(McpStdio), + Http(McpHttp), +} + +impl McpTransport { + pub async fn initialize(&mut self, timeout: Duration) -> Result<(), String> { + match self { + McpTransport::Stdio(c) => c.initialize(timeout).await, + McpTransport::Http(c) => c.initialize(timeout).await, + } + } + pub async fn tools_list(&mut self, timeout: Duration) -> Result, String> { + match self { + McpTransport::Stdio(c) => c.tools_list(timeout).await, + McpTransport::Http(c) => c.tools_list(timeout).await, + } + } + pub async fn call_tool(&mut self, name: &str, args: Value, timeout: Duration) -> Result { + match self { + McpTransport::Stdio(c) => c.call_tool(name, args, timeout).await, + McpTransport::Http(c) => c.call_tool(name, args, timeout).await, + } + } + pub fn kill(&mut self) { + if let McpTransport::Stdio(c) = self { + c.kill(); + } + } +} + #[cfg(test)] mod tests { use super::*;