//! Embedded MCP server. Claude Code (running inside the agent container) //! launches this as a stdio child via `--mcp-config`; tool calls land here //! and are translated to `AgentRequest::*` / `ManagerRequest::*` against //! hyperhive's own per-container unix socket at `/run/hive/mcp.sock`. //! //! Two protocols, two surfaces: //! - **hyperhive socket** at `/run/hive/mcp.sock` — JSON-line, our //! broker-routed protocol. Unaffected by this module. //! - **MCP stdio** owned by this module — what claude actually speaks. //! //! Two server flavors: //! - `AgentServer` — sub-agent tools (`send`, `recv`). //! - `ManagerServer` — agent tools + lifecycle (`request_spawn`, `kill`, //! `request_apply_commit`). //! //! Both go through the same `run_tool_envelope` helper so logging + status //! line stay uniform. use std::path::PathBuf; use anyhow::Result; use rmcp::{ ServerHandler, ServiceExt, handler::server::wrapper::Parameters, schemars, tool, tool_handler, tool_router, transport::stdio, }; use crate::client; #[derive(Debug, serde::Deserialize, schemars::JsonSchema)] pub struct SendArgs { /// Logical agent name to deliver the message to (e.g. `"manager"`, /// `"alice"`, or the literal `"operator"` for the dashboard's T4LK box). pub to: String, /// Message body. Plain text; the broker doesn't parse it. pub body: String, } #[derive(Debug, serde::Deserialize, schemars::JsonSchema)] pub struct RecvArgs {} /// Per-agent tool surface. Holds the socket path so each tool call doesn't /// re-derive it; the socket itself is the per-container `/run/hive/mcp.sock`. #[derive(Debug, Clone)] pub struct AgentServer { socket: PathBuf, } impl AgentServer { #[must_use] pub fn new(socket: PathBuf) -> Self { Self { socket } } /// Wrap every tool handler in the same envelope: /// 1. Log the request (tool name + args via `Debug`). /// 2. Run the tool's actual logic. /// 3. Append a status line (inbox state) to the result so claude always /// has a current "how many unread messages" hint without an extra /// tool call. /// 4. Log the result body. /// /// New tools just call `self.run_tool("name", &args, async { ... })` /// and get the same shape for free. async fn run_tool(&self, tool: &'static str, args: String, body: F) -> String where F: std::future::Future, { tracing::info!(tool, %args, "tool: request"); let result = body.await; let status = self.status_line().await; let full = if status.is_empty() { result } else { format!("{result}\n\n[status] {status}") }; tracing::info!(tool, result = %full, "tool: result"); full } /// Non-mutating peek used in the status line. Falls back to a vague /// note rather than failing the whole tool call when the socket /// hiccups. async fn status_line(&self) -> String { match client::request::<_, hive_sh4re::AgentResponse>( &self.socket, &hive_sh4re::AgentRequest::Status, ) .await { Ok(hive_sh4re::AgentResponse::Status { unread }) => { format!("{unread} unread message(s) in inbox") } Ok(other) => format!("status: unexpected response {other:?}"), Err(e) => format!("status: transport error: {e:#}"), } } } #[tool_router] impl AgentServer { #[tool( description = "Send a message to another hyperhive agent (or to the operator). \ Use this to talk to peers or to surface output for the human at the dashboard." )] async fn send(&self, Parameters(args): Parameters) -> String { let log = format!("{args:?}"); let to = args.to.clone(); self.run_tool("send", log, async move { let req = hive_sh4re::AgentRequest::Send { to: args.to, body: args.body, }; match client::request::<_, hive_sh4re::AgentResponse>(&self.socket, &req).await { Ok(hive_sh4re::AgentResponse::Ok) => format!("sent to {to}"), Ok(hive_sh4re::AgentResponse::Err { message }) => format!("send failed: {message}"), Ok(other) => format!("send unexpected response: {other:?}"), Err(e) => format!("send transport error: {e:#}"), } }) .await } #[tool( description = "Pop one message from this agent's inbox. Returns the sender and body, \ or an empty marker if nothing is waiting." )] async fn recv(&self, Parameters(args): Parameters) -> String { let log = format!("{args:?}"); self.run_tool("recv", log, async move { let req = hive_sh4re::AgentRequest::Recv; match client::request::<_, hive_sh4re::AgentResponse>(&self.socket, &req).await { Ok(hive_sh4re::AgentResponse::Message { from, body }) => { format!("from: {from}\n\n{body}") } Ok(hive_sh4re::AgentResponse::Empty) => "(empty)".into(), Ok(hive_sh4re::AgentResponse::Err { message }) => format!("recv failed: {message}"), Ok(other) => format!("recv unexpected response: {other:?}"), Err(e) => format!("recv transport error: {e:#}"), } }) .await } } #[tool_handler( instructions = "You are a hyperhive agent. Use `send` to talk to peers (by their logical \ name) or to the operator (recipient `operator`). Use `recv` to drain your inbox one \ message at a time." )] impl ServerHandler for AgentServer {} /// Run the MCP server over stdio. Returns when the client disconnects. pub async fn serve_stdio(socket: PathBuf) -> Result<()> { let server = AgentServer::new(socket); let service = server.serve(stdio()).await?; service.waiting().await?; Ok(()) } /// Name of the hyperhive MCP server inside claude's view. Claude prefixes /// tools as `mcp____` (e.g. `mcp__hyperhive__send`). pub const SERVER_NAME: &str = "hyperhive"; /// Built-in claude tools the turn loop enables via `--tools`. Anything not /// in this list literally doesn't exist in the session (claude won't even /// try to call it). Web egress (`WebFetch`/`WebSearch`) and nested agents /// (`Task`) are intentionally omitted for now; `Bash` is allowed pending a /// finer-grained allow-list system for shell command patterns. Edit later /// as our trust model evolves. pub const ALLOWED_BUILTIN_TOOLS: &[&str] = &[ "Bash", "Edit", "Glob", "Grep", "NotebookEdit", "Read", "TodoWrite", "Write", ]; /// MCP tools claude is allowed to call without prompting. Mirrors the /// hyperhive surface so a new tool added below propagates to claude's /// allow-list automatically. #[must_use] pub fn allowed_mcp_tools() -> Vec { ["send", "recv"] .iter() .map(|t| format!("mcp__{SERVER_NAME}__{t}")) .collect() } /// Combined allow-list passed to `--allowedTools` (auto-approve) — covers /// both the built-ins and the MCP surface. #[must_use] pub fn allowed_tools_arg() -> String { let mut all: Vec = ALLOWED_BUILTIN_TOOLS.iter().map(|s| (*s).to_owned()).collect(); all.extend(allowed_mcp_tools()); all.join(",") } /// Built-in tools list for `--tools` (which built-ins exist in this /// session). Same as `ALLOWED_BUILTIN_TOOLS` but joined comma-separated. #[must_use] pub fn builtin_tools_arg() -> String { ALLOWED_BUILTIN_TOOLS.join(",") } /// Render the MCP config blob claude reads from `--mcp-config `. /// `agent_binary` is the path (or PATH-resolvable name) of the `hive-ag3nt` /// executable; `socket` is the hyperhive per-agent socket bind-mounted into /// the container (forwarded to the child as `--socket `). #[must_use] pub fn render_claude_config(agent_binary: &str, socket: &std::path::Path) -> String { let config = serde_json::json!({ "mcpServers": { SERVER_NAME: { "command": agent_binary, "args": ["--socket", socket.display().to_string(), "mcp"], "env": {} } } }); serde_json::to_string_pretty(&config).unwrap_or_else(|_| "{}".into()) }