diff --git a/PROTOCOL.md b/PROTOCOL.md index 79e0960..8a1032e 100644 --- a/PROTOCOL.md +++ b/PROTOCOL.md @@ -863,6 +863,12 @@ The same page is reachable from the user's own Tailscale network (no relay of Ba - A device may not change a bot's check, in any form (`set_bot` with `check`, `checkModel` or `checkBot`, refused `forbidden`), as it may not change a precheck: only the person at the window decides whether answers are checked. - A device may not set or change a routine's `watch`, `deliverChannel`, or `deliverChat` (a frame whose `routine` has any of those keys, even `null`, is refused `forbidden`; the network page's `keepPrecheck: true` keeps them as stored): a watch makes the service call a connector tool on its own, and channel pairing is local-only, so only the person at the window decides. +### Loopback MCP tool bridge (installed agents) + +When a bot runs an installed agent over ACP (`agentcore acp …`), `appd` starts a per-bot loopback-only HTTP MCP server bound to `127.0.0.1:` with a random 32-byte per-session bearer token (verified in constant time, never logged, never persisted). `appd` injects it automatically into the bot's ACP `Op::Connectors` list as the `bate` HTTP MCP server without mutating any global agent configuration files, and shuts it down immediately when the bot's engine stops or the bot is deleted. + +The bridge exposes `memory_list`, `memory_read`, `memory_write`, `browser`, `apple`, `desktop`, `list_surfaces`, `read_surface`, `list_peers`, and `message_bot`. Every `tools/call` runs through `appd`'s exact permission checks (`decide_alone`), `Needs you` approval cards (supporting `Approve`, `Deny`, `Always`, and `Conversation`, while still always asking for Apple app sends/changes), pause and token-limit enforcement, and `tool_start`/`tool_end` transcript audit trail. + ### Speech (the window, not the service) Both parts run on this Mac with no network and send nothing to the service. diff --git a/appd/src/core.rs b/appd/src/core.rs index 51ee095..9de477c 100644 --- a/appd/src/core.rs +++ b/appd/src/core.rs @@ -32,6 +32,7 @@ use crate::chatgpt; use crate::clients::ClientHandle; use crate::hooks::{self, Hit}; use crate::keychain; +use crate::mcp_bridge::{BridgeCall, BridgeHandle}; use crate::proxy::{self, Upstream}; use crate::store::{ CheckWith, Conversation, Kept, Ledger, MailCheck, NewMail, Owner, Queued, Store, @@ -229,6 +230,17 @@ pub enum Msg { saved: Vec, skipped: Vec, }, + /// A tool call arriving over a bot's per-session loopback MCP bridge. + McpBridgeCall(BridgeCall), + /// An async loopback MCP bridge tool call finished off the core's thread. + McpBridgeDone { + bot: String, + generation: u64, + conversation: String, + call_id: String, + result: Result, + reply: Sender>, + }, /// The service was asked to stop. Shutdown, /// `event: None`: the engine closed its output (it exited or broke the protocol). @@ -695,6 +707,28 @@ struct Running { held: Vec<(String, Op)>, /// The conversation the engine had open before the switch in flight. was: String, + /// Per-session loopback MCP tool bridge for installed ACP agents; dropped when the engine stops. + mcp_bridge: Option, +} + +/// A loopback MCP tool call waiting for the person to answer its `Needs you` approval card. +struct McpPending { + bot: String, + generation: u64, + conversation: String, + tool: String, + arguments: serde_json::Map, + kind: Kind, + target: String, + reply: Sender>, +} + +/// An in-flight async browser call initiated by the loopback MCP bridge. +struct McpInflight { + bot: String, + conversation: String, + call_id: String, + reply: Sender>, } /// Who, other than the windows, a turn's last words go to. @@ -818,6 +852,10 @@ pub struct Core { /// Hand-offs whose acceptance command has not ended, by the worker: it takes no other prompt /// until it has. holds: HashMap, + /// Loopback MCP bridge tool calls awaiting a `Needs you` approval card, by question id. + mcp_pending: HashMap, + /// In-flight browser calls started by the loopback MCP bridge, by request id. + mcp_inflight: HashMap, /// Bots whose folder is on its way to the Trash: they take no command and start no engine. deleting: HashSet, /// The port of the proxy that holds each limited bot's browser to its hosts. Chrome cannot @@ -919,6 +957,8 @@ impl Core { net_keys: HashMap::new(), starting: HashMap::new(), holds: HashMap::new(), + mcp_pending: HashMap::new(), + mcp_inflight: HashMap::new(), deleting: HashSet::new(), browser_proxies: HashMap::new(), lan, @@ -1104,6 +1144,21 @@ impl Core { kept }); } + Msg::McpBridgeCall(call) => self.on_mcp_bridge_call(call), + Msg::McpBridgeDone { + bot, + generation, + conversation, + call_id, + result, + reply, + } => { + if self.engines.get(&bot).map(|r| r.generation) != Some(generation) { + let _ = reply.send(Err("the bot stopped".into())); + return; + } + self.finish_mcp_bridge(&bot, &conversation, call_id, result, reply); + } Msg::Shutdown => { for id in self.servers.keys().cloned().collect::>() { self.stop_server(&id); @@ -1118,6 +1173,16 @@ impl Core { request, result, } => { + if let Some(inflight) = self.mcp_inflight.remove(&request) { + self.finish_mcp_bridge( + &inflight.bot, + &inflight.conversation, + inflight.call_id, + result, + inflight.reply, + ); + return; + } if self.engines.get(&bot).map(|r| r.generation) != Some(generation) { return; } @@ -1667,6 +1732,9 @@ impl Core { if let Some(Value::Number(_)) = asked.get("handoff") { return self.answer_handoff(&bot, &conversation, question, choice); } + if asked.get("mcpBridge").is_some() { + return self.answer_mcp_bridge(&bot, &conversation, question, choice); + } if asked.get("secret").is_some() && choice != DENY { return Err(bad( "a secret is given with `answer_secret`; here it can only be refused with `Deny`", @@ -4146,9 +4214,22 @@ impl Core { Some(_) => Some(self.held(format!("bot:{bot}"), None).map_err(failed)?), None => None, }; + self.counter += 1; + let generation = self.counter; + let mcp_bridge = if agent.is_some() { + Some(BridgeHandle::start(bot.to_owned(), generation, self.tx.clone()).map_err(failed)?) + } else { + None + }; + let mut connectors = connectors; + if let Some(bridge) = &mcp_bridge { + connectors.retain(|c| c.name != "bate"); + connectors.push(bridge.connector()); + } let egress = held.as_ref().map(|(proxy, key)| limit::Egress { proxy: *proxy, service: self.hook_port, + bridge: mcp_bridge.as_ref().map(BridgeHandle::port), key, }); let conversation = match conversation { @@ -4185,8 +4266,6 @@ impl Core { Engine::run(command) }) .map_err(failed)?; - self.counter += 1; - let generation = self.counter; self.connector_reports.remove(bot); let (name, failures) = (bot.to_owned(), self.tx.clone()); // Engine diagnostics go through the service log, so they are rotated with it. @@ -4278,6 +4357,7 @@ impl Core { opening: 0, held: Vec::new(), was: String::new(), + mcp_bridge, }, ); self.send_op(bot, open, Waiter::Open(conversation))?; @@ -4614,6 +4694,7 @@ impl Core { let egress = held.as_ref().map(|(proxy, key)| limit::Egress { proxy: *proxy, service: None, + bridge: None, key, }); project_server::start( @@ -6234,6 +6315,18 @@ impl Core { "Open Bate on your Mac to review that hand-off.", ); } + if asked.get("mcpBridge").is_some() { + return match self.answer_mcp_bridge(bot, &conversation, question, choice) { + Ok(_) => self.ack_chat(bot, kind, callback_id, callback_token, label), + Err((_, e)) => self.ack_chat( + bot, + kind, + callback_id, + callback_token, + &format!("Could not answer: {e}"), + ), + }; + } let op = Op::Answer { question: question.to_owned(), choice: choice.to_owned(), @@ -6489,6 +6582,634 @@ impl Core { Ok(Some(json!({}))) } + /// Classifies a loopback MCP bridge tool call into Bate's permission `(Kind, target, title)`. + fn classify_mcp_bridge( + &self, + bot: &str, + tool: &str, + arguments: &serde_json::Map, + ) -> Result<(Kind, String, String), String> { + let arg_str = |key: &str| { + arguments + .get(key) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + }; + match tool { + "memory_list" => Ok((Kind::Read, "memory/".into(), "List memory notes".into())), + "memory_read" => { + let name = arg_str("name").ok_or("`name` is required")?; + memory::check_name(name)?; + Ok(( + Kind::Read, + format!("memory/{name}"), + format!("Read memory note {name}"), + )) + } + "memory_write" => { + let name = arg_str("name").ok_or("`name` is required")?; + memory::check_name(name)?; + if arguments.get("text").and_then(Value::as_str).is_none() { + return Err("`text` must be a string".into()); + } + Ok(( + Kind::Write, + format!("memory/{name}"), + format!("Write memory note {name}"), + )) + } + "browser" => { + browser::Action::parse(arguments)?; + let action = arg_str("action").unwrap_or("act"); + Ok(( + Kind::Connector, + "browser".into(), + format!("Browser: {action}"), + )) + } + "apple" => { + let apple_tool = arg_str("tool").ok_or("`tool` is required")?; + let app = proto::apple::app(apple_tool) + .ok_or_else(|| format!("unknown Apple app tool `{apple_tool}`"))?; + let inner = arguments + .get("args") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + let call = app.parse(&inner)?; + let target = format!("{apple_tool}:{}", call.action); + let title = if call.shown.is_empty() { + format!("{}: {}", app.tool, call.action) + } else { + format!("{}: {} ({})", app.tool, call.action, call.shown) + }; + Ok((call.kind, target, title)) + } + "desktop" => { + proto::desktop::Call::parse(arguments)?; + let action = arg_str("action").unwrap_or("act"); + Ok(( + Kind::Desktop, + action.to_owned(), + format!("Desktop: {action}"), + )) + } + "list_surfaces" => Ok(( + Kind::Read, + "surfaces".into(), + "List project surfaces".into(), + )), + "read_surface" => { + let uri = arg_str("uri").ok_or("`uri` is required")?; + Ok(( + Kind::Read, + format!("surface:{uri}"), + format!("Read surface {uri}"), + )) + } + "list_peers" => Ok((Kind::Connector, "peers".into(), "List project peers".into())), + "message_bot" => { + let to = arg_str("to").ok_or("`to` is required")?; + if arg_str("text").is_none() { + return Err("`text` is required".into()); + } + let (peers, _) = self.peers_of(bot).map_err(|e| e.to_string())?; + let peer = peers + .iter() + .find(|p| p.id == to || p.name.eq_ignore_ascii_case(to)) + .ok_or_else(|| format!("no peer bot `{to}` in this bot's project"))?; + Ok(( + Kind::Connector, + format!("bot:{}", peer.id), + format!("Message {}", peer.name), + )) + } + other => Err(format!("unknown tool `{other}`")), + } + } + + /// Authorizes and dispatches a tool call arriving over an installed agent's per-bot loopback + /// MCP bridge through Bate's permissions, `Needs you` approval cards, pause/token limits, and + /// transcript audit trail. + fn on_mcp_bridge_call(&mut self, call: BridgeCall) { + let Some(conversation) = self + .engines + .get(&call.bot) + .filter(|r| r.generation == call.generation) + .map(|r| r.conversation.clone()) + else { + let _ = call.reply.send(Err("the bot stopped".into())); + return; + }; + if self.is_paused(&call.bot) { + let _ = call.reply.send(Err("the bot is paused".into())); + return; + } + if let Some(why) = self.token_stop(&call.bot, false) { + let _ = call.reply.send(Err(why)); + return; + } + let (kind, target, title) = + match self.classify_mcp_bridge(&call.bot, &call.tool, &call.arguments) { + Ok(parsed) => parsed, + Err(why) => { + let _ = call.reply.send(Err(why)); + return; + } + }; + let decision = self.decide_alone(&call.bot, kind, &target, Some(&conversation)); + match decision { + Some(DENY) => { + let call_id = format!("mcp-{}", sys::random_hex(6)); + self.record( + &call.bot, + &conversation, + serde_json::to_value(Event::ToolStart { + call: call_id.clone(), + tool: format!("bate__{}", call.tool), + args: call.arguments, + }) + .expect("serializable"), + ); + self.finish_mcp_bridge( + &call.bot, + &conversation, + call_id, + Err("not allowed by this bot's permissions".into()), + call.reply, + ); + } + Some(APPROVE) => { + self.run_mcp_bridge_tool( + &call.bot, + call.generation, + &conversation, + call.tool, + call.arguments, + call.reply, + ); + } + _ => { + let qid = format!("mcp-{}", sys::random_hex(6)); + let mut entry = serde_json::to_value(Event::Question { + question: qid.clone(), + title: title.clone(), + options: vec![APPROVE.to_owned(), DENY.to_owned()], + kind: Some(kind), + target: Some(target.clone()), + secret: None, + }) + .expect("serializable"); + entry["mcpBridge"] = json!(true); + if let Err(e) = self.store.put_question(&conversation, &qid, &entry) { + log!("bot {}: mcp question not stored: {e}", call.bot); + let _ = call.reply.send(Err("could not open approval card".into())); + return; + } + self.record(&call.bot, &conversation, entry); + self.broadcast(&json!({"type": "bots_changed"})); + self.lan.notify_push(crate::push::payload_for_question( + &self.name_of(&call.bot), + &title, + false, + )); + self.mcp_pending.insert( + qid, + McpPending { + bot: call.bot, + generation: call.generation, + conversation, + tool: call.tool, + arguments: call.arguments, + kind, + target, + reply: call.reply, + }, + ); + } + } + } + + /// Resolves a `Needs you` approval card created for a loopback MCP bridge call. + fn answer_mcp_bridge( + &mut self, + bot: &str, + conversation: &str, + question: &str, + choice: &str, + ) -> Reply { + let saves = choice == ALWAYS || choice == CONVERSATION; + if choice != APPROVE && choice != DENY && !saves { + return Err(bad( + "`choice` must be `Approve`, `Deny`, `Always`, or `Conversation`", + )); + } + let Some(pending) = self.mcp_pending.get(question) else { + return Err(( + "no_such_question", + format!("question `{question}` is not open"), + )); + }; + if pending.bot != bot || pending.conversation != conversation { + return Err(( + "no_such_question", + format!("question `{question}` is not open"), + )); + } + if saves && pending.kind.always_asks() { + return Err(bad( + "a send or change in an Apple app is asked about every time", + )); + } + let pending = self.mcp_pending.remove(question).expect("checked above"); + self.store + .take_question(conversation, question) + .map_err(internal)?; + self.broadcast(&json!({ + "type": "question_closed", + "bot": bot, + "conversation": conversation, + "question": question, + })); + self.broadcast(&json!({"type": "bots_changed"})); + if saves { + let grant = Grant { + kind: pending.kind, + target: pending.target.clone(), + at_ms: now_ms(), + }; + let put = if choice == CONVERSATION { + self.store.put_conversation_grant(conversation, &grant) + } else { + self.store.put_grant(bot, &grant) + }; + match put { + Ok(()) => self.broadcast(&json!({"type": "permissions_changed", "bot": bot})), + Err(e) => log!("bot {bot}: grant not stored: {e}"), + } + } + if choice == DENY { + let call_id = format!("mcp-{}", sys::random_hex(6)); + self.record( + bot, + conversation, + serde_json::to_value(Event::ToolStart { + call: call_id.clone(), + tool: format!("bate__{}", pending.tool), + args: pending.arguments, + }) + .expect("serializable"), + ); + self.finish_mcp_bridge( + bot, + conversation, + call_id, + Err("denied by user".into()), + pending.reply, + ); + } else { + self.run_mcp_bridge_tool( + bot, + pending.generation, + conversation, + pending.tool, + pending.arguments, + pending.reply, + ); + } + Ok(Some(json!({}))) + } + + /// Executes an authorized loopback MCP bridge tool call and records its audit events. + fn run_mcp_bridge_tool( + &mut self, + bot: &str, + generation: u64, + conversation: &str, + tool: String, + arguments: serde_json::Map, + reply: Sender>, + ) { + let call_id = format!("mcp-{}", sys::random_hex(6)); + self.record( + bot, + conversation, + serde_json::to_value(Event::ToolStart { + call: call_id.clone(), + tool: format!("bate__{tool}"), + args: arguments.clone(), + }) + .expect("serializable"), + ); + match tool.as_str() { + "memory_list" => { + let res = memory::list(&memory::Place::bot(bot)) + .map(|notes| { + if notes.is_empty() { + "No memory notes yet.".to_owned() + } else { + notes + .into_iter() + .map(|n| n.name) + .collect::>() + .join("\n") + } + }) + .map_err(|e| format!("could not list memory notes: {e}")); + self.finish_mcp_bridge(bot, conversation, call_id, res, reply); + } + "memory_read" => { + let name = arguments + .get("name") + .and_then(Value::as_str) + .unwrap_or("") + .trim(); + let res = memory::check_name(name).and_then(|()| { + match memory::read(&memory::Place::bot(bot), name) { + Ok(Some(text)) => Ok(text), + Ok(None) => Err(format!("no memory note `{name}`")), + Err(e) => Err(format!("could not read `{name}`: {e}")), + } + }); + self.finish_mcp_bridge(bot, conversation, call_id, res, reply); + } + "memory_write" => { + let name = arguments + .get("name") + .and_then(Value::as_str) + .unwrap_or("") + .trim(); + let text = arguments.get("text").and_then(Value::as_str).unwrap_or(""); + let res = memory::check_name(name).and_then(|()| { + let place = memory::Place::bot(bot); + memory::write(&place, name, text.as_bytes()) + .map_err(|e| format!("could not write `{name}`: {e}"))?; + self.sync_memory_place(Owner::Bot(bot), &place); + self.broadcast(&json!({"type": "memory_changed", "bot": bot})); + Ok(format!("Saved memory note `{name}`.")) + }); + self.finish_mcp_bridge(bot, conversation, call_id, res, reply); + } + "browser" => { + let prepared = browser::Action::parse(&arguments).and_then(|action| { + let secrets = self.secrets_of(bot)?; + self.start_browser(bot)?; + Ok((action, secrets)) + }); + match prepared { + Ok((action, secrets)) => { + let req_id = format!("mcp-browser-{call_id}"); + let cancelled = Arc::new(AtomicBool::new(false)); + self.mcp_inflight.insert( + req_id.clone(), + McpInflight { + bot: bot.to_owned(), + conversation: conversation.to_owned(), + call_id, + reply, + }, + ); + self.browsers[bot].act(browser::Job { + request: req_id, + generation, + action, + cancelled, + secrets, + }); + } + Err(e) => self.finish_mcp_bridge(bot, conversation, call_id, Err(e), reply), + } + } + "apple" => { + let apple_tool = arguments + .get("tool") + .and_then(Value::as_str) + .unwrap_or("") + .trim() + .to_owned(); + let inner = arguments + .get("args") + .and_then(Value::as_object) + .cloned() + .unwrap_or_default(); + let full_path = self.full_attachment_paths(bot); + let (bot, conversation, tx, helper) = ( + bot.to_owned(), + conversation.to_owned(), + self.tx.clone(), + self.desktop.clone(), + ); + thread::spawn(move || { + let result = match apple::history(&apple_tool, &inner) { + Some(Ok(call)) => helper.call(&bot, call, full_path), + Some(Err(e)) => Err(e), + None => apple::run(&apple::Tools::system(), &apple_tool, &inner), + }; + let _ = tx.send(Msg::McpBridgeDone { + bot, + generation, + conversation, + call_id, + result, + reply, + }); + }); + } + "desktop" => { + let prepared = proto::desktop::Call::parse(&arguments) + .and_then(|call| Ok((call, self.secrets_of(bot)?))); + match prepared { + Ok((call, secrets)) => { + let full_path = self.full_attachment_paths(bot); + let (bot, conversation, tx, helper) = ( + bot.to_owned(), + conversation.to_owned(), + self.tx.clone(), + self.desktop.clone(), + ); + thread::spawn(move || { + let result = helper + .call(&bot, call, full_path) + .map(|text| browser::redact(&text, &secrets)); + let _ = tx.send(Msg::McpBridgeDone { + bot, + generation, + conversation, + call_id, + result, + reply, + }); + }); + } + Err(e) => self.finish_mcp_bridge(bot, conversation, call_id, Err(e), reply), + } + } + "list_surfaces" | "read_surface" => { + let project = match self.project_of(bot) { + Ok(Some(p)) => p, + Ok(None) => { + return self.finish_mcp_bridge( + bot, + conversation, + call_id, + Err("this bot is not in a project".into()), + reply, + ); + } + Err(e) => { + return self.finish_mcp_bridge( + bot, + conversation, + call_id, + Err(e.to_string()), + reply, + ); + } + }; + let pid = project.id.as_deref().unwrap_or(""); + if !self.servers.contains_key(pid) { + self.ensure_server(&project); + } + let link = self + .servers + .get(pid) + .and_then(|s| s.program.as_ref().map(|p| p.link.clone())); + let Some(link) = link else { + let res = if tool == "list_surfaces" { + Ok("[]".to_owned()) + } else { + Err("the project has no running surface program".into()) + }; + return self.finish_mcp_bridge(bot, conversation, call_id, res, reply); + }; + let uri = arguments + .get("uri") + .and_then(Value::as_str) + .unwrap_or("") + .to_owned(); + let (bot, conversation, tx) = + (bot.to_owned(), conversation.to_owned(), self.tx.clone()); + thread::spawn(move || { + let result = if tool == "list_surfaces" { + link.list().map(|v| v.to_string()) + } else { + link.read(&uri, None, None).map(|v| v.to_string()) + }; + let _ = tx.send(Msg::McpBridgeDone { + bot, + generation, + conversation, + call_id, + result, + reply, + }); + }); + } + "list_peers" => { + let res = self + .peers_of(bot) + .map(|(peers, _)| serde_json::to_string(&peers).unwrap_or_else(|_| "[]".into())) + .map_err(|e| e.to_string()); + self.finish_mcp_bridge(bot, conversation, call_id, res, reply); + } + "message_bot" => { + let to = arguments + .get("to") + .and_then(Value::as_str) + .unwrap_or("") + .trim(); + let text = arguments + .get("text") + .and_then(Value::as_str) + .unwrap_or("") + .trim(); + let res = self + .peers_of(bot) + .map_err(|e| e.to_string()) + .and_then(|(peers, _)| { + let peer = peers + .iter() + .find(|p| p.id == to || p.name.eq_ignore_ascii_case(to)) + .ok_or_else(|| format!("no peer bot `{to}` in this bot's project"))?; + let waits = NewMail { + from: bot, + to: &peer.id, + text, + state: "waiting", + at: now_ms(), + parent: None, + check: None, + }; + let seq = self.store.put_mail(waits).map_err(|e| e.to_string())?; + self.broadcast(&json!({"type": "mail_changed"})); + self.deliver_mail(&peer.id); + Ok(format!("Sent message #{seq} to {}.", peer.name)) + }); + self.finish_mcp_bridge(bot, conversation, call_id, res, reply); + } + other => self.finish_mcp_bridge( + bot, + conversation, + call_id, + Err(format!("unknown tool `{other}`")), + reply, + ), + } + } + + fn finish_mcp_bridge( + &mut self, + bot: &str, + conversation: &str, + call_id: String, + result: Result, + reply: Sender>, + ) { + let (output, is_error) = match &result { + Ok(out) => (out.clone(), false), + Err(err) => (err.clone(), true), + }; + self.record( + bot, + conversation, + serde_json::to_value(Event::ToolEnd { + call: call_id, + output, + is_error, + undo: None, + }) + .expect("serializable"), + ); + let _ = reply.send(result); + } + + /// Cancels all pending/in-flight loopback MCP bridge calls for `bot` when its engine stops. + fn cancel_mcp_bridge(&mut self, bot: &str) { + let pending_ids: Vec = self + .mcp_pending + .iter() + .filter(|(_, p)| p.bot == bot) + .map(|(k, _)| k.clone()) + .collect(); + for qid in pending_ids { + if let Some(p) = self.mcp_pending.remove(&qid) { + let _ = p.reply.send(Err("the bot stopped".into())); + } + } + let inflight_ids: Vec = self + .mcp_inflight + .iter() + .filter(|(_, i)| i.bot == bot) + .map(|(k, _)| k.clone()) + .collect(); + for rid in inflight_ids { + if let Some(i) = self.mcp_inflight.remove(&rid) { + let _ = i.reply.send(Err("the bot stopped".into())); + } + } + } + /// The command ended its run number `run`. A pass, or a second failure, ends the hand-off; /// a first failure gives the worker one more turn. fn on_handoff_checked( @@ -6660,6 +7381,10 @@ impl Core { signed_in: None, }); } + if let Some(bridge) = self.engines.get(bot).and_then(|r| r.mcp_bridge.as_ref()) { + connectors.retain(|c| c.name != "bate"); + connectors.push(bridge.connector()); + } Ok(connectors) } @@ -8274,6 +8999,7 @@ impl Core { if let Some(typing) = r.typing.take() { typing.store(true, Ordering::SeqCst); } + self.cancel_mcp_bridge(bot); let _ = r.child.kill(); let status = r.child.wait(); log!("bot {bot}: engine stopped ({status:?})"); @@ -8594,6 +9320,7 @@ impl Core { let egress = held.as_ref().map(|(proxy, key)| limit::Egress { proxy: *proxy, service: None, + bridge: None, key, }); let mut run = limit::command( diff --git a/appd/src/limit.rs b/appd/src/limit.rs index 9c296fb..e78b703 100644 --- a/appd/src/limit.rs +++ b/appd/src/limit.rs @@ -81,6 +81,7 @@ const NETWORK: &str = r#" (allow network-outbound (remote unix-socket (subpath (param "FOLDER")))) (allow network-outbound (remote ip (string-append "localhost:" (param "PROXY")))) (allow network-outbound (remote ip (string-append "localhost:" (param "SERVICE")))) +(allow network-outbound (remote ip (string-append "localhost:" (param "BRIDGE")))) (deny network-inbound (local ip)) (deny network-bind (local ip)) "#; @@ -91,6 +92,8 @@ pub struct Egress<'a> { pub proxy: u16, /// The service's own port, for an engine's tools; a program has no use for it. pub service: Option, + /// The bot's per-session loopback MCP bridge port, for installed ACP agents. + pub bridge: Option, /// The proxy's user name for this process: the service says which hosts it may reach. pub key: &'a str, } @@ -179,6 +182,7 @@ pub fn command( let ports = [ ("PROXY", e.proxy), ("SERVICE", e.service.unwrap_or(e.proxy)), + ("BRIDGE", e.bridge.unwrap_or(e.proxy)), ]; for (name, port) in ports { command.arg("-D").arg(format!("{name}={port}")); diff --git a/appd/src/main.rs b/appd/src/main.rs index 2859f18..8a3f3cc 100644 --- a/appd/src/main.rs +++ b/appd/src/main.rs @@ -25,6 +25,7 @@ mod limit; mod log; mod login_item; mod login_path; +mod mcp_bridge; mod memory; mod oauth; mod paths; diff --git a/appd/src/mcp_bridge.rs b/appd/src/mcp_bridge.rs new file mode 100644 index 0000000..9206b56 --- /dev/null +++ b/appd/src/mcp_bridge.rs @@ -0,0 +1,575 @@ +//! Per-bot loopback MCP tool bridge (`127.0.0.1:`), authenticated with a +//! random per-session bearer token verified in constant time. Exposes Bate's per-bot tools +//! (memory notes, browser with model-blind Secrets, Apple apps, desktop helper, project +//! Surfaces, and bot-to-bot mail) to installed ACP agents so every call passes through `Core`'s +//! permission checks, `Needs you` approval cards, pause/token-limit state, and audit trail. +//! +//! Runs completely off `Core::run` and shuts down cleanly when dropped. + +use crate::core::Msg; +use crate::sys; +use proto::connectors::{Connector, Transport}; +use serde_json::{Map, Value, json}; +use std::collections::BTreeMap; +use std::io::{self, BufRead, BufReader, Read, Write}; +use std::net::{Shutdown, TcpListener, TcpStream}; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::mpsc::{self, RecvTimeoutError, Sender}; +use std::thread; +use std::time::{Duration, Instant}; + +const MAX_HEAD: u64 = 8 * 1024; +const MAX_BODY: usize = 1024 * 1024; +const READ_TIMEOUT: Duration = Duration::from_secs(10); +/// Approval cards can wait for the person to click Allow once / Deny. +const CALL_TIMEOUT: Duration = Duration::from_secs(180); +const MAX_OPEN: usize = 32; + +/// One MCP tool call arriving over the loopback bridge for `Core` to authorize and run. +pub struct BridgeCall { + pub bot: String, + pub generation: u64, + pub tool: String, + pub arguments: Map, + pub reply: Sender>, +} + +/// Handle to a bot's running loopback MCP bridge. Dropping it stops the listener immediately. +pub struct BridgeHandle { + port: u16, + token: String, + stop: Arc, +} + +impl BridgeHandle { + /// Starts a new loopback-only (`127.0.0.1:0`) MCP HTTP server for `(bot, generation)`. + pub fn start(bot: String, generation: u64, tx: Sender) -> io::Result { + let listener = TcpListener::bind(("127.0.0.1", 0))?; + let port = listener.local_addr()?.port(); + let token = sys::random_hex(32); + let stop = Arc::new(AtomicBool::new(false)); + let server_stop = stop.clone(); + let expected_auth = Arc::new(format!("Bearer {token}")); + let open = Arc::new(AtomicUsize::new(0)); + thread::spawn(move || { + for stream in listener.incoming() { + if server_stop.load(Ordering::SeqCst) { + break; + } + let Ok(stream) = stream else { + continue; + }; + if open.fetch_add(1, Ordering::SeqCst) >= MAX_OPEN { + open.fetch_sub(1, Ordering::SeqCst); + continue; + } + let (bot, tx, expected_auth, stop, open) = ( + bot.clone(), + tx.clone(), + expected_auth.clone(), + server_stop.clone(), + open.clone(), + ); + thread::spawn(move || { + handle_connection(&stream, &bot, generation, &tx, &expected_auth, &stop); + let _ = stream.shutdown(Shutdown::Both); + open.fetch_sub(1, Ordering::SeqCst); + }); + } + }); + Ok(BridgeHandle { port, token, stop }) + } + + pub fn port(&self) -> u16 { + self.port + } + + pub fn url(&self) -> String { + format!("http://127.0.0.1:{}/mcp", self.port) + } + + /// Synthetic HTTP MCP connector injected into the installed agent's ACP `mcpServers`. + /// Never written to SQLite or global agent config files. + pub fn connector(&self) -> Connector { + let mut headers = BTreeMap::new(); + headers.insert("Authorization".to_owned(), format!("Bearer {}", self.token)); + Connector { + name: "bate".to_owned(), + enabled: true, + transport: Transport::Http { + url: self.url(), + headers, + }, + oauth: false, + client_id: None, + signed_in: None, + } + } +} + +impl Drop for BridgeHandle { + fn drop(&mut self) { + self.stop.store(true, Ordering::SeqCst); + // Unblock `listener.incoming()` so the server thread exits and releases the port at once. + let _ = TcpStream::connect_timeout( + &std::net::SocketAddr::from(([127, 0, 0, 1], self.port)), + Duration::from_millis(100), + ); + } +} + +fn token_matches(header: &str, expected: &str) -> bool { + // Compare fixed-length SHA-256 digests byte-by-byte without early exit so neither content nor + // length leaks through response timing. + let a = ring::digest::digest(&ring::digest::SHA256, header.as_bytes()); + let b = ring::digest::digest(&ring::digest::SHA256, expected.as_bytes()); + let mut diff = 0u8; + for (x, y) in a.as_ref().iter().zip(b.as_ref().iter()) { + diff |= x ^ y; + } + std::hint::black_box(diff) == 0 +} + +fn handle_connection( + stream: &TcpStream, + bot: &str, + generation: u64, + tx: &Sender, + expected_auth: &str, + stop: &AtomicBool, +) { + let _ = stream.set_read_timeout(Some(READ_TIMEOUT)); + let _ = stream.set_write_timeout(Some(READ_TIMEOUT)); + let RawRequest { + method, + path, + auth, + body, + } = match read_request(stream) { + Ok(req) => req, + Err((status, msg)) => { + write_json(stream, status, &json!({"error": msg})); + return; + } + }; + if path != "/mcp" { + write_json(stream, 404, &json!({"error": "not found"})); + return; + } + if method != "POST" { + write_json(stream, 405, &json!({"error": "method not allowed"})); + return; + } + if !auth + .as_deref() + .is_some_and(|h| token_matches(h, expected_auth)) + { + write_json(stream, 401, &json!({"error": "unauthorized"})); + return; + } + let Ok(msg) = serde_json::from_slice::(&body) else { + write_json( + stream, + 400, + &json!({"jsonrpc": "2.0", "id": Value::Null, "error": {"code": -32700, "message": "parse error"}}), + ); + return; + }; + let id = msg.get("id").cloned(); + let rpc_method = msg.get("method").and_then(Value::as_str).unwrap_or(""); + let params = msg.get("params").cloned().unwrap_or(Value::Null); + + // Notifications (no id) get 202 Accepted. + if id.is_none() || rpc_method.starts_with("notifications/") { + write_empty(stream, 202); + return; + } + let id = id.unwrap_or(Value::Null); + let reply = match rpc_method { + "initialize" => json!({ + "jsonrpc": "2.0", + "id": id, + "result": { + "protocolVersion": "2025-03-26", + "capabilities": {"tools": {}}, + "serverInfo": {"name": "bate", "version": "0.1"} + } + }), + "ping" => json!({"jsonrpc": "2.0", "id": id, "result": {}}), + "tools/list" => json!({"jsonrpc": "2.0", "id": id, "result": {"tools": tool_schemas()}}), + "tools/call" => { + let tool = params["name"].as_str().unwrap_or("").to_owned(); + let arguments = params["arguments"].as_object().cloned().unwrap_or_default(); + if tool.is_empty() { + json!({ + "jsonrpc": "2.0", + "id": id, + "error": {"code": -32602, "message": "missing tool name"} + }) + } else { + match dispatch_call(bot, generation, tool, arguments, tx, stop) { + Ok(text) => json!({ + "jsonrpc": "2.0", + "id": id, + "result": { + "content": [{"type": "text", "text": text}], + "isError": false + } + }), + Err(err) => json!({ + "jsonrpc": "2.0", + "id": id, + "result": { + "content": [{"type": "text", "text": err}], + "isError": true + } + }), + } + } + } + _ => json!({ + "jsonrpc": "2.0", + "id": id, + "error": {"code": -32601, "message": format!("unknown method `{rpc_method}`")} + }), + }; + write_json(stream, 200, &reply); +} + +fn dispatch_call( + bot: &str, + generation: u64, + tool: String, + arguments: Map, + tx: &Sender, + stop: &AtomicBool, +) -> Result { + let (reply_tx, reply_rx) = mpsc::channel(); + tx.send(Msg::McpBridgeCall(BridgeCall { + bot: bot.to_owned(), + generation, + tool, + arguments, + reply: reply_tx, + })) + .map_err(|_| "the service is stopping".to_owned())?; + let deadline = Instant::now() + CALL_TIMEOUT; + loop { + if stop.load(Ordering::SeqCst) { + return Err("the bot stopped".to_owned()); + } + let left = deadline.saturating_duration_since(Instant::now()); + if left.is_zero() { + return Err("timed out waiting for tool call".to_owned()); + } + match reply_rx.recv_timeout(left.min(Duration::from_millis(200))) { + Ok(result) => return result, + Err(RecvTimeoutError::Timeout) => continue, + Err(RecvTimeoutError::Disconnected) => return Err("the bot stopped".to_owned()), + } + } +} + +struct RawRequest { + method: String, + path: String, + auth: Option, + body: Vec, +} + +fn read_request(stream: &TcpStream) -> Result { + let mut reader = BufReader::new(stream.take(MAX_HEAD)); + let mut first = String::new(); + let n = reader + .read_line(&mut first) + .map_err(|_| (400, "bad request"))?; + if n == 0 || !first.ends_with('\n') { + return Err((400, "bad request")); + } + let mut parts = first.split_whitespace(); + let method = parts.next().unwrap_or("").to_owned(); + let target = parts.next().unwrap_or(""); + let path = target.split_once('?').map_or(target, |(p, _)| p).to_owned(); + let mut length = 0usize; + let mut auth = None; + loop { + let mut line = String::new(); + let n = reader + .read_line(&mut line) + .map_err(|_| (400, "bad request"))?; + if n == 0 || !line.ends_with('\n') { + return Err((400, "bad header")); + } + if line.trim_end().is_empty() { + break; + } + let Some((name, value)) = line.split_once(':') else { + return Err((400, "bad header")); + }; + let (name, value) = (name.trim().to_ascii_lowercase(), value.trim().to_owned()); + match name.as_str() { + "content-length" => length = value.parse().map_err(|_| (400, "bad content-length"))?, + "transfer-encoding" => return Err((411, "content-length required")), + "authorization" => auth = Some(value), + _ => {} + } + } + if length > MAX_BODY { + return Err((413, "body too large")); + } + let mut body = reader.buffer().to_vec(); + if body.len() > length { + body.truncate(length); + } + let remaining = length - body.len(); + if remaining > 0 { + let mut rest = vec![0u8; remaining]; + reader + .into_inner() + .into_inner() + .read_exact(&mut rest) + .map_err(|_| (400, "short body"))?; + body.extend(rest); + } + Ok(RawRequest { + method, + path, + auth, + body, + }) +} + +fn write_json(mut stream: &TcpStream, status: u16, body: &Value) { + let text = body.to_string(); + let _ = write!( + stream, + "HTTP/1.1 {status} -\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{text}", + text.len() + ); +} + +fn write_empty(mut stream: &TcpStream, status: u16) { + let _ = write!( + stream, + "HTTP/1.1 {status} -\r\ncontent-length: 0\r\nconnection: close\r\n\r\n" + ); +} + +fn tool_schemas() -> Value { + json!([ + { + "name": "memory_list", + "description": "List this bot's memory notes.", + "inputSchema": {"type": "object", "properties": {}} + }, + { + "name": "memory_read", + "description": "Read one of this bot's memory notes by name.", + "inputSchema": { + "type": "object", + "properties": {"name": {"type": "string"}}, + "required": ["name"] + } + }, + { + "name": "memory_write", + "description": "Write or update one of this bot's memory notes.", + "inputSchema": { + "type": "object", + "properties": { + "name": {"type": "string"}, + "text": {"type": "string"} + }, + "required": ["name", "text"] + } + }, + { + "name": "browser", + "description": "Drive this bot's isolated Chrome browser (supports model-blind Secrets via `secret`).", + "inputSchema": { + "type": "object", + "properties": { + "action": {"type": "string"}, + "url": {"type": "string"}, + "element": {"type": "integer"}, + "text": {"type": "string"}, + "secret": {"type": "string"}, + "submit": {"type": "boolean"}, + "direction": {"type": "string"}, + "key": {"type": "string"}, + "option": {"type": "string"}, + "seconds": {"type": "integer"} + }, + "required": ["action"] + } + }, + { + "name": "apple", + "description": "Read or act in Apple apps (Mail, Calendar, Reminders, Notes, Contacts, Messages) under this bot's permissions.", + "inputSchema": { + "type": "object", + "properties": { + "tool": {"type": "string"}, + "args": {"type": "object"} + }, + "required": ["tool"] + } + }, + { + "name": "desktop", + "description": "Control other apps on this Mac through Bate Helper under this bot's desktop permissions.", + "inputSchema": { + "type": "object", + "properties": {"action": {"type": "string"}}, + "required": ["action"] + } + }, + { + "name": "list_surfaces", + "description": "List Surfaces exposed by this bot's project connector.", + "inputSchema": {"type": "object", "properties": {}} + }, + { + "name": "read_surface", + "description": "Read a Surface exposed by this bot's project connector.", + "inputSchema": { + "type": "object", + "properties": {"uri": {"type": "string"}}, + "required": ["uri"] + } + }, + { + "name": "list_peers", + "description": "List peer bots in this bot's project that can receive mail.", + "inputSchema": {"type": "object", "properties": {}} + }, + { + "name": "message_bot", + "description": "Send a message to a peer bot in this bot's project.", + "inputSchema": { + "type": "object", + "properties": { + "to": {"type": "string"}, + "text": {"type": "string"} + }, + "required": ["to", "text"] + } + } + ]) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn post_mcp(port: u16, auth: Option<&str>, body: &str) -> (u16, String) { + let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut req = format!( + "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n", + body.len() + ); + if let Some(a) = auth { + req.push_str(&format!("Authorization: {a}\r\n")); + } + req.push_str("\r\n"); + req.push_str(body); + stream.write_all(req.as_bytes()).unwrap(); + let mut resp = String::new(); + stream.read_to_string(&mut resp).unwrap(); + let status: u16 = resp + .lines() + .next() + .unwrap() + .split_whitespace() + .nth(1) + .unwrap() + .parse() + .unwrap(); + let body = resp.split_once("\r\n\r\n").unwrap().1.to_owned(); + (status, body) + } + + #[test] + fn enforces_bearer_token_serves_mcp_and_shuts_down_on_drop() { + let (tx, rx) = mpsc::channel(); + let bridge = BridgeHandle::start("b1".into(), 1, tx).unwrap(); + let port = bridge.port(); + let auth = match &bridge.connector().transport { + Transport::Http { headers, .. } => headers["Authorization"].clone(), + _ => panic!("expected http connector"), + }; + + // Missing or wrong bearer token is rejected with 401. + assert_eq!(post_mcp(port, None, "{}").0, 401); + assert_eq!(post_mcp(port, Some("Bearer wrong-token"), "{}").0, 401); + + // Valid token serves initialize and tools/list. + let (status, body) = post_mcp( + port, + Some(&auth), + &json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {}}).to_string(), + ); + assert_eq!(status, 200); + let parsed: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(parsed["result"]["serverInfo"]["name"], "bate"); + + let (status, body) = post_mcp( + port, + Some(&auth), + &json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}).to_string(), + ); + assert_eq!(status, 200); + let parsed: Value = serde_json::from_str(&body).unwrap(); + let names: Vec<&str> = parsed["result"]["tools"] + .as_array() + .unwrap() + .iter() + .map(|t| t["name"].as_str().unwrap()) + .collect(); + assert!(names.contains(&"memory_read")); + assert!(names.contains(&"browser")); + assert!(names.contains(&"apple")); + assert!(names.contains(&"desktop")); + assert!(names.contains(&"message_bot")); + + // tools/call forwards to Core and returns result. + let call_thread = thread::spawn(move || { + post_mcp( + port, + Some(&auth), + &json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": {"name": "memory_list", "arguments": {}} + }) + .to_string(), + ) + }); + match rx.recv_timeout(Duration::from_secs(5)).unwrap() { + Msg::McpBridgeCall(call) => { + assert_eq!(call.bot, "b1"); + assert_eq!(call.tool, "memory_list"); + call.reply.send(Ok("notes: a.md".into())).unwrap(); + } + _ => panic!("expected McpBridgeCall"), + } + let (status, body) = call_thread.join().unwrap(); + assert_eq!(status, 200); + let parsed: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(parsed["result"]["isError"], false); + assert_eq!(parsed["result"]["content"][0]["text"], "notes: a.md"); + + // Dropping BridgeHandle shuts down the loopback port. + drop(bridge); + let deadline = Instant::now() + Duration::from_secs(2); + while TcpStream::connect(("127.0.0.1", port)).is_ok() { + assert!( + Instant::now() < deadline, + "bridge port still open after drop" + ); + thread::sleep(Duration::from_millis(20)); + } + } +} diff --git a/appd/tests/service.rs b/appd/tests/service.rs index 36f3256..24369b1 100644 --- a/appd/tests/service.rs +++ b/appd/tests/service.rs @@ -20239,3 +20239,276 @@ while True: assert_eq!(ans["code"], "forbidden", "case {idx}: {ans}"); } } + +#[test] +fn loopback_mcp_bridge_authenticates_enforces_approvals_and_shuts_down() { + use std::net::TcpStream; + + fn post_mcp(port: u16, auth: Option<&str>, body: &str) -> (u16, String) { + let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap(); + let mut req = format!( + "POST /mcp HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\nContent-Type: application/json\r\nContent-Length: {}\r\n", + body.len() + ); + if let Some(a) = auth { + req.push_str(&format!("Authorization: {a}\r\n")); + } + req.push_str("\r\n"); + req.push_str(body); + stream.write_all(req.as_bytes()).unwrap(); + let mut resp = String::new(); + stream.read_to_string(&mut resp).unwrap(); + let status: u16 = resp + .lines() + .next() + .unwrap() + .split_whitespace() + .nth(1) + .unwrap() + .parse() + .unwrap(); + let body = resp.split_once("\r\n\r\n").unwrap().1.to_owned(); + (status, body) + } + + let home = home("mcp-bridge"); + let _service = Service::start(&home); + let mut w = Window::connect(&home); + let bot = w.create_bot(); + w.ok("set_disk_access", json!({"bot": bot, "wholeDisk": true})); + w.ok("set_agent", json!({"bot": bot, "command": ["mock-acp"]})); + + // Starting the installed-agent bot injects the loopback `bate` MCP bridge into Op::Connectors. + w.ok("prompt", json!({"bot": bot, "nonce": "n1", "text": "hi"})); + w.wait_for(|f| f["type"] == "transcript" && f["entry"]["type"] == "turn_end"); + + let log_path = home.join("bots").join(&bot).join("connectors.log"); + eventually("connectors logged", || log_path.exists()); + let line = fs::read_to_string(&log_path) + .unwrap() + .lines() + .last() + .unwrap() + .to_owned(); + let op: Value = serde_json::from_str(&line).unwrap(); + let bate = op["connectors"] + .as_array() + .unwrap() + .iter() + .find(|c| c["name"] == "bate") + .expect("bate loopback MCP connector injected"); + assert_eq!(bate["enabled"], true); + let url = bate["transport"]["url"].as_str().unwrap(); + assert!( + url.starts_with("http://127.0.0.1:") && url.ends_with("/mcp"), + "{url}" + ); + let port: u16 = url + .strip_prefix("http://127.0.0.1:") + .unwrap() + .strip_suffix("/mcp") + .unwrap() + .parse() + .unwrap(); + let auth = bate["transport"]["headers"]["Authorization"] + .as_str() + .unwrap() + .to_owned(); + let raw_token = auth.strip_prefix("Bearer ").unwrap().to_owned(); + assert_eq!(raw_token.len(), 64); + + // The bearer token is never written to the service log or saved in list_connectors. + assert!( + !service_log(&home).contains(&raw_token), + "bearer token leaked into appd.log" + ); + assert!( + !w.ok("list_connectors", json!({"bot": bot})) + .to_string() + .contains(&raw_token) + ); + + // Missing or wrong bearer tokens are rejected with 401. + assert_eq!(post_mcp(port, None, "{}").0, 401); + assert_eq!(post_mcp(port, Some("Bearer wrong"), "{}").0, 401); + + // Authenticated initialize and tools/list succeed. + let (status, body) = post_mcp( + port, + Some(&auth), + &json!({"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}).to_string(), + ); + assert_eq!(status, 200); + let list: Value = serde_json::from_str(&body).unwrap(); + assert!(list["result"]["tools"].to_string().contains("memory_write")); + + // Write permission set to `ask`: calling memory_write opens a real Needs you approval card. + w.ok( + "set_permission", + json!({"bot": bot, "kind": "write", "level": "ask"}), + ); + let auth_clone = auth.clone(); + let write_call = std::thread::spawn(move || { + post_mcp( + port, + Some(&auth_clone), + &json!({ + "jsonrpc": "2.0", + "id": 2, + "method": "tools/call", + "params": { + "name": "memory_write", + "arguments": {"name": "plan.md", "text": "ship loopback bridge"} + } + }) + .to_string(), + ) + }); + eventually("mcp approval card opened", || { + !w.ok("open_bot", json!({"bot": bot}))["questions"] + .as_array() + .unwrap() + .is_empty() + }); + let opened = w.ok("open_bot", json!({"bot": bot})); + let q = &opened["questions"][0]; + assert_eq!(q["mcpBridge"], true, "{q}"); + assert_eq!(q["kind"], "write"); + assert_eq!(q["target"], "memory/plan.md"); + let qid = q["question"].as_str().unwrap().to_owned(); + w.ok( + "answer", + json!({"bot": bot, "question": qid, "choice": "Approve"}), + ); + let (status, body) = write_call.join().unwrap(); + assert_eq!(status, 200, "{body}"); + let res: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(res["result"]["isError"], false, "{res}"); + + // Read permission set to `always`: memory_read succeeds immediately and returns the note. + w.ok( + "set_permission", + json!({"bot": bot, "kind": "read", "level": "always"}), + ); + let (status, body) = post_mcp( + port, + Some(&auth), + &json!({ + "jsonrpc": "2.0", + "id": 3, + "method": "tools/call", + "params": {"name": "memory_read", "arguments": {"name": "plan.md"}} + }) + .to_string(), + ); + assert_eq!(status, 200); + let res: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(res["result"]["isError"], false, "{res}"); + assert_eq!(res["result"]["content"][0]["text"], "ship loopback bridge"); + + // Audit trail contains tool_start and tool_end entries for bridged calls. + let history = w.ok("open_bot", json!({"bot": bot}))["history"].to_string(); + assert!(history.contains("bate__memory_write"), "{history}"); + assert!(history.contains("bate__memory_read"), "{history}"); + + // Denying an approval card rejects the MCP tool call cleanly. + let auth_clone = auth.clone(); + let denied_call = std::thread::spawn(move || { + post_mcp( + port, + Some(&auth_clone), + &json!({ + "jsonrpc": "2.0", + "id": 4, + "method": "tools/call", + "params": { + "name": "memory_write", + "arguments": {"name": "blocked.md", "text": "nope"} + } + }) + .to_string(), + ) + }); + eventually("second mcp approval card opened", || { + !w.ok("open_bot", json!({"bot": bot}))["questions"] + .as_array() + .unwrap() + .is_empty() + }); + let qid2 = w.ok("open_bot", json!({"bot": bot}))["questions"][0]["question"] + .as_str() + .unwrap() + .to_owned(); + w.ok( + "answer", + json!({"bot": bot, "question": qid2, "choice": "Deny"}), + ); + let (_, body) = denied_call.join().unwrap(); + let res: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(res["result"]["isError"], true, "{res}"); + assert!( + res["result"]["content"][0]["text"] + .as_str() + .unwrap() + .contains("denied"), + "{res}" + ); + + // Permission level `never` refuses immediately without asking. + w.ok( + "set_permission", + json!({"bot": bot, "kind": "write", "level": "never"}), + ); + let (_, body) = post_mcp( + port, + Some(&auth), + &json!({ + "jsonrpc": "2.0", + "id": 5, + "method": "tools/call", + "params": { + "name": "memory_write", + "arguments": {"name": "never.md", "text": "nope"} + } + }) + .to_string(), + ); + let res: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(res["result"]["isError"], true, "{res}"); + assert!( + res["result"]["content"][0]["text"] + .as_str() + .unwrap() + .contains("not allowed"), + "{res}" + ); + + // Paused bot refuses bridge calls. + w.ok("set_paused", json!({"bot": bot, "paused": true})); + let (_, body) = post_mcp( + port, + Some(&auth), + &json!({ + "jsonrpc": "2.0", + "id": 6, + "method": "tools/call", + "params": {"name": "memory_list", "arguments": {}} + }) + .to_string(), + ); + let res: Value = serde_json::from_str(&body).unwrap(); + assert_eq!(res["result"]["isError"], true, "{res}"); + assert!( + res["result"]["content"][0]["text"] + .as_str() + .unwrap() + .contains("paused"), + "{res}" + ); + + // Deleting the bot shuts down the loopback MCP listener cleanly. + w.ok("delete_bot", json!({"bot": bot})); + eventually("loopback bridge port closed", || { + TcpStream::connect(("127.0.0.1", port)).is_err() + }); +}