1use serde_json::{json, Map, Value};
10
11pub(super) const MSP_SCHEMA_FINGERPRINT: &str =
15 "sha256:c94c3d1f2f51e6424074b9ec43eac3eedcf532d3dcd77351ec1383a87d3049c6";
16
17pub(super) fn initialize_params() -> Value {
21 json!({
22 "clientInfo": { "name": "agentmux", "title": "AgentMux", "version": env!("CARGO_PKG_VERSION") },
23 "capabilities": { "requestedCapabilities": ["sessionMcp"], "userInputDialogs": false },
24 })
25}
26
27pub(super) fn command_id() -> String {
29 let random = uuid::Uuid::new_v4().into_bytes();
30 let mut tail = [0u8; 10];
31 tail.copy_from_slice(&random[6..]);
32 uuid::Builder::from_unix_timestamp_millis(agentmux_common::time::now_ms_u64(), &tail)
33 .into_uuid()
34 .to_string()
35}
36
37pub(super) fn session_request(resume: Option<&str>, cwd: &str, mcp_servers: &Map<String, Value>) -> (&'static str, Value) {
40 let mut params = json!({ "commandId": command_id() });
41 if !mcp_servers.is_empty() {
42 params["config"] = json!({ "mcpServers": mcp_servers });
43 }
44 match resume {
45 Some(sid) => {
46 params["sessionId"] = json!(sid);
47 params["excludeItems"] = json!(true);
48 ("session/resume", params)
49 }
50 None => {
51 params["workspaceRoot"] = json!(cwd);
52 ("session/start", params)
53 }
54 }
55}
56
57pub(super) fn turn_start_params(session_id: &str, text: &str) -> Value {
61 json!({
62 "sessionId": session_id,
63 "commandId": command_id(),
64 "input": [{ "type": "text", "text": text }],
65 "ifBusy": "steer",
66 })
67}
68
69pub(super) fn turn_interrupt_params(session_id: &str) -> Value {
71 json!({ "sessionId": session_id, "commandId": command_id() })
72}
73
74pub(super) fn approval_choice(params: &Value) -> Option<String> {
79 let choices = params.get("availableChoices")?.as_array()?;
80 let with = |decision: &str| {
81 choices
82 .iter()
83 .find(|c| c.get("decision").and_then(Value::as_str) == Some(decision))
84 .and_then(|c| c.get("choiceId").and_then(Value::as_str))
85 };
86 with("approvedForSession")
87 .or_else(|| with("approved"))
88 .or_else(|| with("denied"))
89 .map(str::to_string)
90}
91
92pub(super) fn approval_decide_params(params: &Value) -> Option<Value> {
95 Some(json!({
96 "sessionId": params.get("sessionId")?.as_str()?,
97 "approvalId": params.get("approvalId")?.as_str()?,
98 "choiceId": approval_choice(params)?,
99 "requirementId": params.get("currentRequirementId")?.clone(),
100 "commandId": command_id(),
101 }))
102}
103
104pub(super) fn user_input_cancel_params(params: &Value) -> Option<Value> {
107 Some(json!({
108 "sessionId": params.get("sessionId")?.as_str()?,
109 "userInputId": params.get("userInputId")?.as_str()?,
110 "commandId": command_id(),
111 "reason": "AgentMux can't show this question",
112 }))
113}
114
115pub(super) fn request(id: u64, method: &str, params: Value) -> String {
117 json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }).to_string()
118}
119
120pub(super) fn notification(method: &str) -> String {
122 json!({ "jsonrpc": "2.0", "method": method }).to_string()
123}
124
125pub(super) fn reply_to_host_request(id: &Value, method: &str) -> String {
129 if method == "approval/request" || method == "userInput/request" {
130 return json!({ "jsonrpc": "2.0", "id": id, "result": {} }).to_string();
131 }
132 json!({
133 "jsonrpc": "2.0",
134 "id": id,
135 "error": { "code": -32601, "message": format!("AgentMux does not offer {method}") },
136 })
137 .to_string()
138}
139
140pub(super) const TURN_ENDED_BY_SRV: &str =
144 r#"{"jsonrpc":"2.0","method":"turn/completed","params":{"turnId":"","terminal":"failed"}}"#;
145
146pub(super) fn process_exit_error(exit_code: i32, stderr_tail: &[String]) -> String {
150 let mut message = format!("Muse Code exited (code {exit_code})");
151 let tail = stderr_tail.join("\n");
152 if !tail.trim().is_empty() {
153 message.push_str(": ");
154 message.push_str(tail.trim());
155 }
156 json!({ "jsonrpc": "2.0", "id": null, "error": { "code": -32603, "message": message } }).to_string()
157}
158
159pub(super) fn msp_mcp_servers(
165 mcp_json: &str,
166 resolve: impl Fn(&str) -> Option<String>,
167 lookup: impl Fn(&str) -> Option<String>,
168) -> Map<String, Value> {
169 let pairs = |v: &Value| -> Map<String, Value> {
170 v.as_array()
171 .map(|a| {
172 a.iter()
173 .filter_map(|p| Some((p.get("name")?.as_str()?.to_string(), p.get("value")?.clone())))
174 .collect()
175 })
176 .unwrap_or_default()
177 };
178 let mut out = Map::new();
179 for s in super::acp_mcp::acp_mcp_servers(mcp_json, true, false, resolve, lookup) {
180 let Some(name) = s.get("name").and_then(Value::as_str) else { continue };
181 let server = if s.get("type").and_then(Value::as_str) == Some("http") {
182 json!({ "transport": "streamableHttp", "url": s["url"], "headers": pairs(&s["headers"]), "mode": "optional" })
183 } else {
184 json!({ "transport": "stdio", "command": s["command"], "args": s["args"], "env": pairs(&s["env"]), "mode": "optional" })
185 };
186 out.insert(name.to_string(), server);
187 }
188 out
189}
190
191#[cfg(test)]
192mod tests {
193 use super::*;
194
195 #[test]
196 fn initialize_names_the_client_as_msp_requires_and_asks_for_session_mcp() {
197 let p = initialize_params();
198 let name = p["clientInfo"]["name"].as_str().unwrap();
199 assert!(name.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_'), "{name}");
200 assert_eq!(p["capabilities"]["requestedCapabilities"], json!(["sessionMcp"]));
201 assert_eq!(p["capabilities"]["userInputDialogs"], false);
202 assert!(p["capabilities"].get("experimentalApi").is_none(), "the stable surface only");
203 }
204
205 #[test]
206 fn command_ids_are_distinct_uuid_v7s() {
207 let (a, b) = (command_id(), command_id());
208 assert_ne!(a, b);
209 for id in [a, b] {
210 let u = uuid::Uuid::parse_str(&id).unwrap();
211 assert_eq!(u.get_version_num(), 7, "{id}");
212 }
213 }
214
215 #[test]
216 fn a_session_starts_in_the_cwd_or_resumes_without_history() {
217 let mut mcp = Map::new();
218 mcp.insert("agentmux".into(), json!({"transport": "stdio", "command": "x"}));
219 let (method, p) = session_request(None, "C:/agents/a", &mcp);
220 assert_eq!(method, "session/start");
221 assert_eq!(p["workspaceRoot"], "C:/agents/a");
222 assert_eq!(p["config"]["mcpServers"]["agentmux"]["command"], "x");
223 assert!(p["commandId"].is_string());
224 let (method, p) = session_request(Some("s1"), "C:/agents/a", &Map::new());
225 assert_eq!(method, "session/resume");
226 assert_eq!(p["sessionId"], "s1");
227 assert_eq!(p["excludeItems"], true);
228 assert!(p.get("config").is_none(), "no servers, no config");
229 assert!(p.get("workspaceRoot").is_none());
230 }
231
232 #[test]
233 fn a_turn_is_text_input_that_steers_a_running_turn() {
234 let p = turn_start_params("s1", "hi");
235 assert_eq!(p["sessionId"], "s1");
236 assert_eq!(p["input"], json!([{"type": "text", "text": "hi"}]));
237 assert_eq!(p["ifBusy"], "steer");
238 }
239
240 fn approval(choices: Value) -> Value {
241 json!({
242 "approvalId": "a1", "sessionId": "s1", "currentRequirementId": {"stage": 1},
243 "availableChoices": choices,
244 })
245 }
246
247 #[test]
248 fn approvals_prefer_the_session_then_once_and_never_a_lasting_rule() {
249 let all = approval(json!([
250 {"choiceId": "rule", "decision": "approvedPolicyAmendment"},
251 {"choiceId": "once", "decision": "approved"},
252 {"choiceId": "sess", "decision": "approvedForSession"},
253 {"choiceId": "no", "decision": "denied"},
254 ]));
255 assert_eq!(approval_choice(&all).as_deref(), Some("sess"));
256 let once = approval(json!([{"choiceId": "rule", "decision": "approvedPolicyAmendment"}, {"choiceId": "once", "decision": "approved"}]));
257 assert_eq!(approval_choice(&once).as_deref(), Some("once"));
258 let deny = approval(json!([{"choiceId": "rule", "decision": "approvedPolicyAmendment"}, {"choiceId": "no", "decision": "denied"}]));
259 assert_eq!(approval_choice(&deny).as_deref(), Some("no"));
260 assert_eq!(approval_choice(&approval(json!([]))), None);
261 }
262
263 #[test]
264 fn a_decision_names_the_approval_and_its_current_stage() {
265 let p = approval_decide_params(&approval(json!([{"choiceId": "once", "decision": "approved"}]))).unwrap();
266 assert_eq!(p["approvalId"], "a1");
267 assert_eq!(p["sessionId"], "s1");
268 assert_eq!(p["choiceId"], "once");
269 assert_eq!(p["requirementId"], json!({"stage": 1}));
270 assert!(p["commandId"].is_string());
271 assert!(approval_decide_params(&json!({"approvalId": "a1"})).is_none());
272 }
273
274 #[test]
275 fn host_requests_get_a_receipt_or_method_not_found() {
276 let r: Value = serde_json::from_str(&reply_to_host_request(&json!(7), "approval/request")).unwrap();
277 assert_eq!(r, json!({"jsonrpc": "2.0", "id": 7, "result": {}}));
278 let r: Value = serde_json::from_str(&reply_to_host_request(&json!("x"), "fs/read")).unwrap();
279 assert_eq!(r["id"], "x");
280 assert_eq!(r["error"]["code"], -32601);
281 }
282
283 #[test]
284 fn a_question_is_declined() {
285 let p = user_input_cancel_params(&json!({"sessionId": "s1", "userInputId": "q1"})).unwrap();
286 assert_eq!(p["userInputId"], "q1");
287 assert!(user_input_cancel_params(&json!({"sessionId": "s1"})).is_none());
288 }
289
290 #[test]
291 fn an_exit_error_carries_the_code_and_stderr() {
292 let line: Value = serde_json::from_str(&process_exit_error(3, &["malformed auth file".to_string()])).unwrap();
293 assert_eq!(line["error"]["message"], "Muse Code exited (code 3): malformed auth file");
294 assert!(line["id"].is_null());
295 let line: Value = serde_json::from_str(&process_exit_error(1, &[])).unwrap();
296 assert_eq!(line["error"]["message"], "Muse Code exited (code 1)");
297 }
298
299 #[test]
300 fn mcp_servers_are_keyed_by_name_with_env_and_headers_as_objects() {
301 let raw = r#"{"mcpServers":{
302 "agentmux":{"type":"stdio","command":"agentmux-mcp","args":[],"env":{"AGENTMUX_AGENT_ID":"aria"}},
303 "docs":{"type":"http","url":"https://example.com/mcp","headers":{"Authorization":"Bearer ${T}"}},
304 "feed":{"type":"sse","url":"https://example.com/sse"}
305 }}"#;
306 let resolve = |c: &str| (c == "agentmux-mcp").then(|| "C:/AgentMux/agentmux-mcp.exe".to_string());
307 let lookup = |k: &str| (k == "T").then(|| "t0k".to_string());
308 let s = msp_mcp_servers(raw, resolve, lookup);
309 assert_eq!(
310 s["agentmux"],
311 json!({"transport": "stdio", "command": "C:/AgentMux/agentmux-mcp.exe", "args": [],
312 "env": {"AGENTMUX_AGENT_ID": "aria"}, "mode": "optional"})
313 );
314 assert_eq!(
315 s["docs"],
316 json!({"transport": "streamableHttp", "url": "https://example.com/mcp",
317 "headers": {"Authorization": "Bearer t0k"}, "mode": "optional"})
318 );
319 assert!(s.get("feed").is_none(), "MSP has no SSE transport");
320 assert!(msp_mcp_servers("not json", |_| None, |_| None).is_empty());
321 }
322}