diff --git a/.github/scripts/assert-pure.sh b/.github/scripts/assert-pure.sh index ee1c630b..3d5b9ac9 100755 --- a/.github/scripts/assert-pure.sh +++ b/.github/scripts/assert-pure.sh @@ -17,9 +17,10 @@ set -euo pipefail # whose vocabulary dependency includes `anyhow` and `async-trait`. pure_crates=("tinyhivemind-core" "tinyhivemind-lang") tool_crates=("tinyhivemind-tools") -# Host runs harnesses as processes (ADR 0035), so it may hold a runtime, but it -# must never link one. -host_crates=("tinyhivemind-host") +# Host runs harnesses as processes (ADR 0035), and the MCP server serves them +# hive tools over loopback (ADR 0036), so both may hold a runtime and a +# listener, but neither may link a harness. +host_crates=("tinyhivemind-host" "tinyhivemind-mcp") forbidden_pure='tokio|futures|async-trait|axum|hyper|reqwest|ureq|curl|anyhow|rusqlite|git2|openhuman|tinyagents|tinytools' # Whole families: `openhuman-embed`, `tinyagents-harness` and so on. diff --git a/AGENTS.md b/AGENTS.md index d3678b94..ca42fa76 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -53,11 +53,12 @@ is not advisory — do not add an exception to it to land a change. ## Project Structure -This is a Rust 2024 virtual Cargo workspace with seven packages. Core owns all +This is a Rust 2024 virtual Cargo workspace with eight packages. Core owns all host-neutral behavior; lang is where a hive mind is defined, integrations included; tools renders native tool definitions and records calls; exec runs a package's executable tools and hooks; host is the harness-neutral -half of running seats; OpenHuman is the only crate that links an agent harness, +half of running seats; mcp serves hive tools to seats that run as processes; +OpenHuman is the only crate that links an agent harness, and it deploys hive packages. ```text @@ -75,6 +76,7 @@ crates/ ├── tinyhivemind-tools/ # native TinyTools specs and episode call record ├── tinyhivemind-exec/ # runs a package's executable tools and script hooks ├── tinyhivemind-host/ # hive tool belt, policies, package plans, harness processes +├── tinyhivemind-mcp/ # hive and package tools served to harness processes over loopback MCP ├── tinyhivemind-openhuman/ # package deployment, seat runners, host integration ├── tinyhivemind-hives/ # durable cross-hive coordinator └── tinyhivemind-lang/ # pure hive packages: structure, integrations, edits, lineage @@ -100,7 +102,10 @@ process. `tinyhivemind-exec` runs those executable tools and hooks `tinyhivemind-host` depends on core, hives and lang, and owns what every harness shares: the hive tools and their dispatch, the send and management policy ports, turn scope and prompt, package loading, the deployment plan, and supervised -harness processes. It links no harness, and `assert-pure.sh` checks that. The +harness processes. It links no harness, and `assert-pure.sh` checks that. +`tinyhivemind-mcp` depends on host, hives, lang and exec, and serves those +tools, a package's executable tools and its hooks over Streamable HTTP on +127.0.0.1, one bearer per seat (ADR 0036); it links no harness either. The OpenHuman adapter depends on core, hives, lang, exec and host, re-exports the host's types under its own paths, and deploys packages with `HiveDeployment::from_packages`; its former `HiveConfig` manifest format is diff --git a/Cargo.lock b/Cargo.lock index e5805aad..5d1653f2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3595,6 +3595,25 @@ dependencies = [ "tinyhivemind-core", ] +[[package]] +name = "tinyhivemind-mcp" +version = "0.2.1" +dependencies = [ + "getrandom 0.3.4", + "http-body-util", + "hyper", + "hyper-util", + "serde_json", + "subtle", + "tempfile", + "thiserror", + "tinyhivemind-exec", + "tinyhivemind-hives", + "tinyhivemind-host", + "tinyhivemind-lang", + "tokio", +] + [[package]] name = "tinyhivemind-openhuman" version = "0.2.1" diff --git a/Cargo.toml b/Cargo.toml index 7ff9ffcf..6752b7e6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,7 +4,7 @@ resolver = "3" # package, each directory named for the package it holds. There is no root # package: the crate a host links is `crates/tinyhivemind-core`, the same as any # other member. Keeping the root virtual is what makes that uniform. -members = ["crates/tinyhivemind-core", "crates/tinyhivemind-tools", "crates/tinyhivemind-openhuman", "crates/tinyhivemind-hives", "crates/tinyhivemind-lang", "crates/tinyhivemind-exec", "crates/tinyhivemind-host"] +members = ["crates/tinyhivemind-core", "crates/tinyhivemind-tools", "crates/tinyhivemind-openhuman", "crates/tinyhivemind-hives", "crates/tinyhivemind-lang", "crates/tinyhivemind-exec", "crates/tinyhivemind-host", "crates/tinyhivemind-mcp"] # `worktrees/` holds `git worktree` checkouts of this same repository; each # contains a full copy of this manifest. Keep them excluded from Cargo # workspace discovery. @@ -31,6 +31,23 @@ tinyhivemind-exec = { path = "crates/tinyhivemind-exec" } sha2 = "0.10" # Harness-neutral tool belt, policies, package plans and process supervision. tinyhivemind-host = { path = "crates/tinyhivemind-host" } +# The HTTP/1.1 server under `tinyhivemind-mcp`, which serves hive tools to +# harness processes over Streamable HTTP on loopback (ADR 0036). hyper 1 is a +# protocol implementation and no framework: no router, no TLS, no HTTP/2, no +# middleware stack, so the server's whole request surface (Host, Origin, +# bearer, body bound) is the crate's own code and nothing else is listening. +# It is already in this lockfile through the vendored harness, MIT licensed, +# and builds on 1.96. Server and HTTP/1 only; a test adds `client`. +hyper = { version = "1", default-features = false, features = ["server", "http1"] } +# hyper's tokio I/O adapter, its timer (for the header read timeout) and the +# graceful-shutdown watcher. Nothing else: no client, no auto-HTTP/2. +hyper-util = { version = "0.1", default-features = false, features = ["tokio", "http1", "server-graceful"] } +# Bounded request bodies (`Limited`) and fixed response bodies (`Full`). +http-body-util = "0.1" +# Constant-time comparison of a presented bearer with each seat's. +subtle = { version = "2", default-features = false, features = ["std"] } +# Random per-seat bearers, from the operating system. +getrandom = "0.3" # Durable cross-hive coordinator used at the harness boundary. tinyhivemind-hives = { path = "crates/tinyhivemind-hives" } # Concurrent owned runner futures in the coordinator, outside core. diff --git a/crates/tinyhivemind-exec/src/hook/README.md b/crates/tinyhivemind-exec/src/hook/README.md index 24500011..24d1cef7 100644 --- a/crates/tinyhivemind-exec/src/hook/README.md +++ b/crates/tinyhivemind-exec/src/hook/README.md @@ -4,7 +4,7 @@ A seat's hooks: executable tools bound to an event. | File | Holds | | --- | --- | -| `mod.rs` | `HookRunner` (`pre_tool_use`, `post_tool_use`, `stop`, `is_empty`) and `Verdict` | +| `mod.rs` | `HookRunner` (`pre_tool_use`, `post_tool_use`, `stop`, `is_empty`, `matches_tool`) and `Verdict` | | `matcher.rs` | `*` wildcard matching of a hook's matcher against a tool name | | [`test/`](test/README.md) | Verdicts, matchers, order, failing hooks and event objects | diff --git a/crates/tinyhivemind-exec/src/hook/mod.rs b/crates/tinyhivemind-exec/src/hook/mod.rs index ea522e79..b1efa7c7 100644 --- a/crates/tinyhivemind-exec/src/hook/mod.rs +++ b/crates/tinyhivemind-exec/src/hook/mod.rs @@ -68,6 +68,16 @@ impl HookRunner { self.hooks.is_empty() } + /// Whether a `pre_tool_use` or `post_tool_use` hook names `tool`, so that + /// a call of it would run a hook. + #[must_use] + pub fn matches_tool(&self, tool: &str) -> bool { + self.bound(HookEvent::PreToolUse, Some(tool)) + .chain(self.bound(HookEvent::PostToolUse, Some(tool))) + .next() + .is_some() + } + /// Ask the `pre_tool_use` hooks whether a call of `tool` with /// `arguments` may run. The first refusal wins and later hooks do not run. pub async fn pre_tool_use(&self, tool: &str, arguments: &Value) -> Verdict { diff --git a/crates/tinyhivemind-exec/src/hook/test/matcher.rs b/crates/tinyhivemind-exec/src/hook/test/matcher.rs index 5f50c97b..6756c8be 100644 --- a/crates/tinyhivemind-exec/src/hook/test/matcher.rs +++ b/crates/tinyhivemind-exec/src/hook/test/matcher.rs @@ -26,3 +26,32 @@ fn a_star_matches_any_run_of_characters() { assert!(!matches(Some("a*b*c"), "a__c__b")); assert!(matches(Some("**"), "x")); } + +#[test] +fn a_runner_says_whether_a_tool_hook_names_a_tool() { + use super::support::{hook, runner}; + use serde_json::json; + let dir = std::env::temp_dir(); + let hooks = runner( + vec![ + hook( + "guard", + "pre_tool_use", + "allow", + json!({"matcher": "git_*"}), + ), + hook( + "audit", + "post_tool_use", + "record", + json!({"matcher": "deploy"}), + ), + hook("end", "stop", "record", json!({})), + ], + &dir, + ); + assert!(hooks.matches_tool("git_push")); + assert!(hooks.matches_tool("deploy")); + // A stop hook is bound to no tool. + assert!(!hooks.matches_tool("read_file")); +} diff --git a/crates/tinyhivemind-hives/README.md b/crates/tinyhivemind-hives/README.md index a37d1bb0..9141f9f1 100644 --- a/crates/tinyhivemind-hives/README.md +++ b/crates/tinyhivemind-hives/README.md @@ -25,6 +25,11 @@ The host reads everything with `read_transcript`, including replies to episode without hiding the message, and `release_with` hands a parked agent a note on its next turn. +A host serving tools out of process identifies each state-changing call with +a `TurnCall` and uses the `*_in_turn` entry points: a retry is answered from a +record written with the effect, and a call naming a turn that is not running is +refused. + Direct sends return durable receipts without awaiting peers. `read_direct` exposes only the caller/peer pair, including returned replies, and starts no turn. Hive reads enforce membership and private thread audiences. diff --git a/crates/tinyhivemind-hives/src/coordinator/README.md b/crates/tinyhivemind-hives/src/coordinator/README.md index 34293677..8d49b118 100644 --- a/crates/tinyhivemind-hives/src/coordinator/README.md +++ b/crates/tinyhivemind-hives/src/coordinator/README.md @@ -13,6 +13,7 @@ same input. `release_with` remains the host's manual release operation. | `settings.rs` | Per-hive native policy and retained roles, frozen at acceptance | | `types.rs` | Host runner port and public payloads | | `messaging.rs` | Atomic acceptance, retry IDs, starters, attribution, and private reads | +| `calls.rs` | Identified calls of a running turn: the `*_in_turn` entry points and `running_turn` | | `observe.rs` | Host transcript, committed-revision watch, episode status | | `conduct.rs` | Actual `CompletionDriver`/`Conductor` checkpoint lifecycle | | `scheduler.rs` | FIFO reservations, concurrent futures, shutdown, cancellation | @@ -98,3 +99,19 @@ use the driver's deterministic single-owner fallback. Native routing policy and roles reach the routing request, and widths remain bounded, but confidence, clarification and high-impact thresholds cannot change fallback selection. Configuring these thresholds does not activate a model client. + +## Identified calls + +A host that serves tools out of process cannot tell a transport retry from a +second intended action, so a state-changing call carries a `TurnCall`: the +agent, the turn it says it belongs to, a caller-chosen `call`, and the tool and +arguments. `submit_action_in_turn`, `send_in_turn`, `create_hive_in_turn`, +`join_hive_in_turn` and `leave_hive_in_turn` check in one transaction that the +turn is the agent's running one (`StaleTurn` otherwise), answer a known `call` +with the same tool and arguments from its record without committing, refuse +any other reuse (`CallReused`), or act and record the call with its result on +the `RunningTurn`. A failed commit leaves neither. The record ends with its +turn, and a restart interrupts every running turn, so a retry after one is +refused as stale. `send_in_turn` refuses a sender other than the caller and +still checks `message_id` after `call`. The unidentified entry points are +unchanged. diff --git a/crates/tinyhivemind-hives/src/coordinator/calls.rs b/crates/tinyhivemind-hives/src/coordinator/calls.rs new file mode 100644 index 00000000..632e7ea4 --- /dev/null +++ b/crates/tinyhivemind-hives/src/coordinator/calls.rs @@ -0,0 +1,158 @@ +//! Identified calls: an action taken from a running turn, recorded with it. +//! +//! Each `*_in_turn` entry point checks the call's turn, answers a known call +//! from its record, or acts and records the call, all inside one transaction: +//! a commit holds both the effect and its record, or neither. The record lives +//! on the [`crate::RunningTurn`] and goes when the turn ends. A coordinator +//! restart interrupts every running turn, so a retry after one is refused as +//! stale rather than answered. +use super::{ + Coordinator, EpisodeAction, HiveInfo, Receipt, SendMessage, TurnCall, create_hive_state, + identifier, join_hive_state, leave_hive_state, + messaging::{accept_state, admissible}, + stage_action, +}; +use crate::{CallRecord, Error, Result, StoredState}; +use serde::{Serialize, de::DeserializeOwned}; + +impl Coordinator { + /// The id of `agent_id`'s running turn, if it has one. + /// # Errors + /// Returns a poisoned shared lock error. + pub fn running_turn(&self, agent_id: &str) -> Result> { + Ok(self + .lock()? + .durable + .running + .get(agent_id) + .map(|running| running.request.turn_id.clone())) + } + /// Whether `call` is recorded on its agent's running turn with the same + /// tool and arguments, so that an `*_in_turn` retry of it would be + /// answered from the record rather than act. + /// # Errors + /// Returns a poisoned shared lock error. + pub fn call_recorded(&self, call: &TurnCall) -> Result { + Ok(self + .lock()? + .durable + .running + .get(&call.agent_id) + .filter(|running| running.request.turn_id == call.turn_id) + .and_then(|running| running.calls.get(&call.call)) + .is_some_and(|record| record.tool == call.tool && record.arguments == call.arguments)) + } + /// [`Self::submit_action`] as an identified call of the caller's running turn. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, or the + /// errors of [`Self::submit_action`]. + pub async fn submit_action_in_turn( + &self, + call: &TurnCall, + episode_id: &str, + action: EpisodeAction, + ) -> Result<()> { + self.in_turn(call, |state| { + stage_action(state, &call.agent_id, episode_id, &action) + }) + .await + } + /// [`Self::send`] as an identified call; the sender must be the caller. + /// + /// The send's `message_id` is still checked, after `call`: two calls that + /// send one `message_id` with one payload are one message. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, a + /// sender other than the caller, or the errors of [`Self::send`]. + pub async fn send_in_turn(&self, call: &TurnCall, request: SendMessage) -> Result { + if request.sender != call.agent_id { + return Err(Error::InvalidIdentifier("sender")); + } + admissible(&request)?; + let retention = self.inner.options.retention; + self.in_turn(call, |state| accept_state(state, &request, None, retention)) + .await + } + /// [`Self::create_hive`] as an identified call. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, or the + /// errors of [`Self::create_hive`]. + pub async fn create_hive_in_turn(&self, call: &TurnCall, hive: HiveInfo) -> Result<()> { + identifier(&hive.hive_id, "hive id")?; + identifier(&hive.name, "hive name")?; + self.in_turn(call, |state| create_hive_state(state, &hive)) + .await + } + /// [`Self::join_hive`] as an identified call. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, or the + /// errors of [`Self::join_hive`]. + pub async fn join_hive_in_turn( + &self, + call: &TurnCall, + hive_id: &str, + agent_id: &str, + ) -> Result<()> { + self.in_turn(call, |state| join_hive_state(state, hive_id, agent_id)) + .await + } + /// [`Self::leave_hive`] as an identified call. + /// # Errors + /// [`Error::StaleTurn`], [`Error::CallReused`], an empty identity, or the + /// errors of [`Self::leave_hive`]. + pub async fn leave_hive_in_turn( + &self, + call: &TurnCall, + hive_id: &str, + agent_id: &str, + ) -> Result<()> { + self.in_turn(call, |state| leave_hive_state(state, hive_id, agent_id)) + .await + } + /// Check `call`'s turn, then answer it from its record or run `act` and + /// record it, in one transaction. A recorded answer commits nothing. + async fn in_turn( + &self, + call: &TurnCall, + mut act: impl FnMut(&mut StoredState) -> Result, + ) -> Result { + identifier(&call.agent_id, "agent id")?; + identifier(&call.turn_id, "turn id")?; + identifier(&call.call, "call")?; + let stale = || Error::StaleTurn { + agent_id: call.agent_id.clone(), + turn_id: call.turn_id.clone(), + }; + let gate = self.inner.writer.lock().await; + let value = self + .transact(&gate, |state| { + let running = state + .running + .get(&call.agent_id) + .filter(|running| running.request.turn_id == call.turn_id) + .ok_or_else(stale)?; + if let Some(record) = running.calls.get(&call.call) { + if record.tool != call.tool || record.arguments != call.arguments { + return Err(Error::CallReused(call.call.clone())); + } + return Ok((false, serde_json::from_value(record.result.clone())?)); + } + let value = act(state)?; + let record = CallRecord { + tool: call.tool.clone(), + arguments: call.arguments.clone(), + result: serde_json::to_value(&value)?, + }; + state + .running + .get_mut(&call.agent_id) + .ok_or_else(stale)? + .calls + .insert(call.call.clone(), record); + Ok((true, value)) + }) + .await?; + self.inner.notify.notify_one(); + Ok(value) + } +} diff --git a/crates/tinyhivemind-hives/src/coordinator/messaging.rs b/crates/tinyhivemind-hives/src/coordinator/messaging.rs index 1d88ceab..30db0eb5 100644 --- a/crates/tinyhivemind-hives/src/coordinator/messaging.rs +++ b/crates/tinyhivemind-hives/src/coordinator/messaging.rs @@ -41,100 +41,10 @@ impl Coordinator { request: SendMessage, scheduled_job_id: Option, ) -> Result { - identifier(&request.message_id, "message id")?; - if request.message_id.starts_with("hivemind:") { - return Err(Error::InvalidIdentifier("reserved message id")); - } + admissible(&request)?; let retention = self.inner.options.retention; - self.update(|state| { - let scheduled_job_id = scheduled_job_id.clone().or_else(|| { - state - .running - .get(&request.sender) - .and_then(|running| running.request.scheduled_job_id.clone()) - }); - if let Some(receipt) = retry_receipt(state, &request, scheduled_job_id.as_deref())? { - return Ok(receipt); - } - let recipients = recipients(state, &request)?; - let only_for = narrow_readers( - state, - &request.destination, - request.thread, - request.only_for.clone(), - )?; - let sequence = next_sequence(state)?; - let episode_id = matches!(request.destination, Destination::Hive(_)) - .then(|| format!("episode:{sequence}")); - let message = Message { - scheduled_job_id: scheduled_job_id.clone(), - message_id: request.message_id.clone(), - sequence, - sender: request.sender.clone(), - destination: request.destination.clone(), - body: request.body.clone(), - thread: request.thread, - episode_id: episode_id.clone(), - only_for, - }; - match &request.destination { - Destination::Agent(_) => { - for agent_id in &recipients { - retention.admit_pending(state, agent_id)?; - } - for agent_id in recipients { - state.deliveries.push(Delivery { - sequence, - agent_id, - status: DeliveryStatus::Pending, - }); - } - } - Destination::Hive(id) => { - let mut hive = state - .hives - .get(id) - .cloned() - .ok_or_else(|| Error::UnknownHive(id.clone()))?; - if request.thread.is_some() { - let scope = thread_readers(state, &request.destination, request.thread)?; - if !scope.is_empty() { - hive.members.retain(|member| scope.contains(member)); - } - } - let id = episode_id - .ok_or_else(|| Error::InvalidState("hive message has no episode".into()))?; - state.episodes.push(EpisodeRecord { - settings: state.hive_settings.get(&hive.hive_id).cloned(), - scheduled_job_id: scheduled_job_id.clone(), - episode_id: id, - hive, - opened_at: sequence, - thread: request.thread, - starters: if request.starters.is_empty() { - recipients.clone() - } else { - request.starters.clone() - }, - conductor: None, - pending: Vec::new(), - wave_open: false, - waiting: false, - finished: false, - failure: None, - }); - } - } - state.messages.push(message); - state - .accepted - .insert(request.message_id.clone(), request.clone()); - Ok(Receipt { - message_id: request.message_id.clone(), - sequence, - }) - }) - .await + self.update(|state| accept_state(state, &request, scheduled_job_id.clone(), retention)) + .await } /// Read the caller's direct conversation with a registered peer in durable /// sequence order, including replies returned by the peer's runner. @@ -203,6 +113,108 @@ impl Coordinator { .collect()) } } +/// Refuse a request whose identity no transaction could accept. +pub(super) fn admissible(request: &SendMessage) -> Result<()> { + identifier(&request.message_id, "message id")?; + if request.message_id.starts_with("hivemind:") { + return Err(Error::InvalidIdentifier("reserved message id")); + } + Ok(()) +} +/// Accept `request` into `state`, or answer its retry with the first receipt. +pub(super) fn accept_state( + state: &mut StoredState, + request: &SendMessage, + scheduled_job_id: Option, + retention: crate::RetentionPolicy, +) -> Result { + let scheduled_job_id = scheduled_job_id.or_else(|| { + state + .running + .get(&request.sender) + .and_then(|running| running.request.scheduled_job_id.clone()) + }); + if let Some(receipt) = retry_receipt(state, request, scheduled_job_id.as_deref())? { + return Ok(receipt); + } + let recipients = recipients(state, request)?; + let only_for = narrow_readers( + state, + &request.destination, + request.thread, + request.only_for.clone(), + )?; + let sequence = next_sequence(state)?; + let episode_id = + matches!(request.destination, Destination::Hive(_)).then(|| format!("episode:{sequence}")); + let message = Message { + scheduled_job_id: scheduled_job_id.clone(), + message_id: request.message_id.clone(), + sequence, + sender: request.sender.clone(), + destination: request.destination.clone(), + body: request.body.clone(), + thread: request.thread, + episode_id: episode_id.clone(), + only_for, + }; + match &request.destination { + Destination::Agent(_) => { + for agent_id in &recipients { + retention.admit_pending(state, agent_id)?; + } + for agent_id in recipients { + state.deliveries.push(Delivery { + sequence, + agent_id, + status: DeliveryStatus::Pending, + }); + } + } + Destination::Hive(id) => { + let mut hive = state + .hives + .get(id) + .cloned() + .ok_or_else(|| Error::UnknownHive(id.clone()))?; + if request.thread.is_some() { + let scope = thread_readers(state, &request.destination, request.thread)?; + if !scope.is_empty() { + hive.members.retain(|member| scope.contains(member)); + } + } + let id = episode_id + .ok_or_else(|| Error::InvalidState("hive message has no episode".into()))?; + state.episodes.push(EpisodeRecord { + settings: state.hive_settings.get(&hive.hive_id).cloned(), + scheduled_job_id: scheduled_job_id.clone(), + episode_id: id, + hive, + opened_at: sequence, + thread: request.thread, + starters: if request.starters.is_empty() { + recipients.clone() + } else { + request.starters.clone() + }, + conductor: None, + pending: Vec::new(), + wave_open: false, + waiting: false, + finished: false, + failure: None, + }); + } + } + state.messages.push(message); + state + .accepted + .insert(request.message_id.clone(), request.clone()); + Ok(Receipt { + message_id: request.message_id.clone(), + sequence, + }) +} pub(super) fn membership(state: &StoredState, agent_id: &str, hive_id: &str) -> Result<()> { let hive = state .hives diff --git a/crates/tinyhivemind-hives/src/coordinator/mod.rs b/crates/tinyhivemind-hives/src/coordinator/mod.rs index f84d42c2..86a83d91 100644 --- a/crates/tinyhivemind-hives/src/coordinator/mod.rs +++ b/crates/tinyhivemind-hives/src/coordinator/mod.rs @@ -1,4 +1,5 @@ //! Agent registration, messaging, and conducted scheduling. +mod calls; mod conduct; mod messaging; mod observe; @@ -21,7 +22,7 @@ use tokio::sync::{Mutex as AsyncMutex, Notify, watch}; pub use types::{ AgentRegistration, AgentRunner, CoordinatorOptions, Destination, EpisodeAction, EpisodeContext, EpisodePhase, EpisodeStatus, HOST_ID, HiveInfo, InterruptedTurn, Message, Receipt, RunReport, - SendMessage, TurnDisposition, TurnFuture, TurnOutcome, TurnRequest, + SendMessage, TurnCall, TurnDisposition, TurnFuture, TurnOutcome, TurnRequest, }; /// Cloneable shared coordinator; all clones share runners, inboxes and locks. @@ -202,27 +203,7 @@ impl Coordinator { pub async fn create_hive(&self, hive: HiveInfo) -> Result<()> { identifier(&hive.hive_id, "hive id")?; identifier(&hive.name, "hive name")?; - self.update(|state| { - let mut unique = BTreeSet::new(); - for member in &hive.members { - if !state.agents.contains_key(member) { - return Err(Error::UnknownAgent(member.clone())); - } - if !unique.insert(member) { - return Err(Error::DuplicateMember(member.clone())); - } - } - if let Some(existing) = state.hives.get(&hive.hive_id) { - return if existing == &hive { - Ok(()) - } else { - Err(Error::HiveConflict(hive.hive_id.clone())) - }; - } - state.hives.insert(hive.hive_id.clone(), hive.clone()); - Ok(()) - }) - .await + self.update(|state| create_hive_state(state, &hive)).await } /// List current dynamic hive definitions in ID order. /// # Errors @@ -274,33 +255,15 @@ impl Coordinator { /// # Errors /// Returns unknown hive/agent or storage errors. pub async fn join_hive(&self, hive_id: &str, agent_id: &str) -> Result<()> { - self.update(|state| { - known_agent(state, agent_id)?; - let hive = state - .hives - .get_mut(hive_id) - .ok_or_else(|| Error::UnknownHive(hive_id.into()))?; - if !hive.members.iter().any(|id| id == agent_id) { - hive.members.push(agent_id.into()); - } - Ok(()) - }) - .await + self.update(|state| join_hive_state(state, hive_id, agent_id)) + .await } /// Leave a hive; active turns keep their captured authorization and history. /// # Errors /// Returns unknown hive/agent or storage errors. pub async fn leave_hive(&self, hive_id: &str, agent_id: &str) -> Result<()> { - self.update(|state| { - known_agent(state, agent_id)?; - let hive = state - .hives - .get_mut(hive_id) - .ok_or_else(|| Error::UnknownHive(hive_id.into()))?; - hive.members.retain(|id| id != agent_id); - Ok(()) - }) - .await + self.update(|state| leave_hive_state(state, hive_id, agent_id)) + .await } /// Record an action for the caller's currently running episode. /// # Errors @@ -311,51 +274,8 @@ impl Coordinator { episode_id: &str, action: EpisodeAction, ) -> Result<()> { - self.update(|state| { - let running = state - .running - .get_mut(agent_id) - .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; - let episode = running - .request - .episode - .as_ref() - .filter(|ep| ep.episode_id == episode_id) - .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; - if let EpisodeAction::Ask { agents, .. } = &action { - if agents.is_empty() { - return Err(Error::InvalidIdentifier("ask recipients")); - } - let hive = running - .request - .memberships - .iter() - .find(|hive| hive.hive_id == episode.hive_id) - .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; - let episode_members = state - .episodes - .iter() - .find(|record| record.episode_id == episode_id) - .map(|record| &record.hive.members) - .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; - let mut unique = BTreeSet::new(); - for target in agents { - if target == agent_id - || !hive.members.contains(target) - || !episode_members.contains(target) - || !unique.insert(target) - { - return Err(Error::NotMember { - agent_id: target.clone(), - hive_id: hive.hive_id.clone(), - }); - } - } - } - running.actions.push(action.clone()); - Ok(()) - }) - .await + self.update(|state| stage_action(state, agent_id, episode_id, &action)) + .await } /// Release a parked agent after the host settles its approval. /// Equivalent to [`Self::release_with`] without a note. @@ -439,6 +359,99 @@ fn identifier(value: &str, field: &'static str) -> Result<()> { Ok(()) } } +/// Create `hive` in `state`; an identical definition is already there. +fn create_hive_state(state: &mut StoredState, hive: &HiveInfo) -> Result<()> { + let mut unique = BTreeSet::new(); + for member in &hive.members { + if !state.agents.contains_key(member) { + return Err(Error::UnknownAgent(member.clone())); + } + if !unique.insert(member) { + return Err(Error::DuplicateMember(member.clone())); + } + } + if let Some(existing) = state.hives.get(&hive.hive_id) { + return if existing == hive { + Ok(()) + } else { + Err(Error::HiveConflict(hive.hive_id.clone())) + }; + } + state.hives.insert(hive.hive_id.clone(), hive.clone()); + Ok(()) +} +/// Add `agent_id` to `hive_id` in `state`, unless it is a member already. +fn join_hive_state(state: &mut StoredState, hive_id: &str, agent_id: &str) -> Result<()> { + known_agent(state, agent_id)?; + let hive = state + .hives + .get_mut(hive_id) + .ok_or_else(|| Error::UnknownHive(hive_id.into()))?; + if !hive.members.iter().any(|id| id == agent_id) { + hive.members.push(agent_id.into()); + } + Ok(()) +} +/// Remove `agent_id` from `hive_id` in `state`. +fn leave_hive_state(state: &mut StoredState, hive_id: &str, agent_id: &str) -> Result<()> { + known_agent(state, agent_id)?; + let hive = state + .hives + .get_mut(hive_id) + .ok_or_else(|| Error::UnknownHive(hive_id.into()))?; + hive.members.retain(|id| id != agent_id); + Ok(()) +} +/// Stage `action` on `agent_id`'s running turn in `state`, for `episode_id`. +fn stage_action( + state: &mut StoredState, + agent_id: &str, + episode_id: &str, + action: &EpisodeAction, +) -> Result<()> { + let running = state + .running + .get_mut(agent_id) + .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; + let episode = running + .request + .episode + .as_ref() + .filter(|ep| ep.episode_id == episode_id) + .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; + if let EpisodeAction::Ask { agents, .. } = action { + if agents.is_empty() { + return Err(Error::InvalidIdentifier("ask recipients")); + } + let hive = running + .request + .memberships + .iter() + .find(|hive| hive.hive_id == episode.hive_id) + .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; + let episode_members = state + .episodes + .iter() + .find(|record| record.episode_id == episode_id) + .map(|record| &record.hive.members) + .ok_or_else(|| Error::StaleEpisode(episode_id.into()))?; + let mut unique = BTreeSet::new(); + for target in agents { + if target == agent_id + || !hive.members.contains(target) + || !episode_members.contains(target) + || !unique.insert(target) + { + return Err(Error::NotMember { + agent_id: target.clone(), + hive_id: hive.hive_id.clone(), + }); + } + } + } + running.actions.push(action.clone()); + Ok(()) +} fn known_agent(state: &StoredState, id: &str) -> Result<()> { if state.agents.contains_key(id) { Ok(()) diff --git a/crates/tinyhivemind-hives/src/coordinator/scheduler.rs b/crates/tinyhivemind-hives/src/coordinator/scheduler.rs index 30d6e072..31f0cc1a 100644 --- a/crates/tinyhivemind-hives/src/coordinator/scheduler.rs +++ b/crates/tinyhivemind-hives/src/coordinator/scheduler.rs @@ -236,15 +236,8 @@ impl Coordinator { episode, resumption, }; - next.running.insert( - agent_id.clone(), - RunningTurn { - request: request.clone(), - turn, - actions: Vec::new(), - delivery_sequence, - }, - ); + let running = RunningTurn::claimed(request.clone(), turn, delivery_sequence); + next.running.insert(agent_id.clone(), running); selected.insert(agent_id); claims.push(Claim { runner, request }); } diff --git a/crates/tinyhivemind-hives/src/coordinator/test/README.md b/crates/tinyhivemind-hives/src/coordinator/test/README.md index a2712df0..b961471f 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/README.md +++ b/crates/tinyhivemind-hives/src/coordinator/test/README.md @@ -12,6 +12,7 @@ | `transactions.rs` | Incremental appends, conflict reload/retry, storage failure, cancelled-turn flush, retention | | `observation.rs` | Host transcript reads, the revision watch, episode phases | | `starters.rs` | Host-chosen starters, their validation, and the unchanged wire form | +| `calls.rs` | Identified calls: retries answered once, reuse and stale turns refused, failed commits, reload and restart | | `release.rs` | Release notes delivered once, across restart, and the unchanged wire form | Tests use scripted runner futures, barriers, and notifications. They require no diff --git a/crates/tinyhivemind-hives/src/coordinator/test/calls.rs b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs new file mode 100644 index 00000000..22b8e36e --- /dev/null +++ b/crates/tinyhivemind-hives/src/coordinator/test/calls.rs @@ -0,0 +1,467 @@ +//! Identified calls: one effect per (agent, turn, call), recorded with it. +use super::transactions::Recording; +use super::*; +use crate::{CallRecord, SqliteStorage, Storage}; +use serde_json::{Value, json}; +use tokio::sync::{Notify, mpsc}; + +/// A turn held open by its runner until the test lets it return. +struct Held { + request: TurnRequest, + finish: Arc, + drain: tokio::task::JoinHandle>, +} +impl Held { + fn episode(&self) -> String { + self.request.episode.as_ref().unwrap().episode_id.clone() + } + fn call(&self, call: &str, tool: &str, arguments: Value) -> TurnCall { + TurnCall { + agent_id: self.request.agent_id.clone(), + turn_id: self.request.turn_id.clone(), + call: call.into(), + tool: tool.into(), + arguments, + } + } + fn post(&self, call: &str, body: &str) -> TurnCall { + self.call( + call, + "hivemind_post", + json!({"episode_id": self.episode(), "body": body}), + ) + } + async fn end(self) -> RunReport { + self.finish.notify_one(); + self.drain.await.unwrap().unwrap() + } +} +/// Register `ids` in a hive `work`, each holding a turn open while its +/// request is being received. +async fn holding( + c: &Coordinator, + ids: &[&str], +) -> (mpsc::UnboundedReceiver, Arc) { + let (started, requests) = mpsc::unbounded_channel(); + let finish = Arc::new(Notify::new()); + for id in ids { + let (started, finish) = (started.clone(), finish.clone()); + add(c, id, move |request| { + let (started, finish) = (started.clone(), finish.clone()); + Box::pin(async move { + // Only the turn a test receives is held; later ones, such as + // the conductor's nudges, return at once. + if started.send(request.clone()).is_ok() { + finish.notified().await; + } + Ok(done(&request)) + }) + }) + .await; + } + hive(c, "work", ids).await; + (requests, finish) +} +/// Open an episode for `a` and hold its turn. +async fn hold(c: &Coordinator) -> Held { + let (mut requests, finish) = holding(c, &["a"]).await; + c.send_as_host(message("task", Destination::Hive("work".into()))) + .await + .unwrap(); + let drain = tokio::spawn({ + let c = c.clone(); + async move { c.run_until_idle().await } + }); + let request = requests.recv().await.unwrap(); + Held { + request, + finish, + drain, + } +} +fn actions(c: &Coordinator, agent: &str) -> Vec { + c.lock().unwrap().durable.running[agent].actions.clone() +} +fn posted(body: &str) -> EpisodeAction { + EpisodeAction::Post { body: body.into() } +} + +#[tokio::test] +async fn the_running_turn_is_reported_by_id() { + let c = setup().await; + assert_eq!(c.running_turn("a").unwrap(), None); + let held = hold(&c).await; + assert_eq!( + c.running_turn("a").unwrap().as_deref(), + Some(held.request.turn_id.as_str()) + ); + held.end().await; + assert_eq!(c.running_turn("a").unwrap(), None); +} + +#[tokio::test] +async fn a_retried_post_acts_once_and_returns_the_first_result() { + let c = setup().await; + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + let episode = held.episode(); + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + let revision = c.lock().unwrap().durable.revision; + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + assert_eq!(actions(&c, "a"), [posted("hello")]); + // The answer came from the record, so nothing was committed. + assert_eq!(c.lock().unwrap().durable.revision, revision); + held.end().await; +} + +#[tokio::test] +async fn two_identical_posts_under_different_calls_both_act() { + let c = setup().await; + let held = hold(&c).await; + let episode = held.episode(); + for call in ["post-1", "post-2"] { + c.submit_action_in_turn(&held.post(call, "hello"), &episode, posted("hello")) + .await + .unwrap(); + } + assert_eq!(actions(&c, "a"), [posted("hello"), posted("hello")]); + held.end().await; +} + +#[tokio::test] +async fn reusing_a_call_with_other_arguments_or_another_tool_is_refused() { + let c = setup().await; + let held = hold(&c).await; + let episode = held.episode(); + c.submit_action_in_turn(&held.post("one", "hello"), &episode, posted("hello")) + .await + .unwrap(); + let other_arguments = held.post("one", "goodbye"); + assert!(matches!( + c.submit_action_in_turn(&other_arguments, &episode, posted("goodbye")).await, + Err(Error::CallReused(call)) if call == "one" + )); + let mut other_tool = held.post("one", "hello"); + other_tool.tool = "hivemind_complete".into(); + let complete = EpisodeAction::Complete { + body: "hello".into(), + }; + assert!(matches!( + c.submit_action_in_turn(&other_tool, &episode, complete) + .await, + Err(Error::CallReused(_)) + )); + assert_eq!(actions(&c, "a"), [posted("hello")]); + held.end().await; +} + +#[tokio::test] +async fn a_call_naming_another_turn_is_refused_whatever_its_call() { + let c = setup().await; + let held = hold(&c).await; + let episode = held.episode(); + let mut stale = held.post("post-1", "hello"); + stale.turn_id = "0:0:a".into(); + assert!(matches!( + c.submit_action_in_turn(&stale, &episode, posted("hello")).await, + Err(Error::StaleTurn { agent_id, turn_id }) if agent_id == "a" && turn_id == "0:0:a" + )); + assert_eq!(actions(&c, "a"), Vec::::new()); + assert!(c.lock().unwrap().durable.running["a"].calls.is_empty()); + held.end().await; +} + +#[tokio::test] +async fn a_call_with_no_running_turn_is_refused() { + let c = setup().await; + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + let episode = held.episode(); + held.end().await; + assert!(matches!( + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await, + Err(Error::StaleTurn { .. }) + )); +} + +#[tokio::test] +async fn a_call_without_an_identity_is_refused() { + let c = setup().await; + let held = hold(&c).await; + let episode = held.episode(); + let blank = held.post(" ", "hello"); + assert!(matches!( + c.submit_action_in_turn(&blank, &episode, posted("hello")) + .await, + Err(Error::InvalidIdentifier("call")) + )); + assert_eq!(actions(&c, "a"), Vec::::new()); + held.end().await; +} + +#[tokio::test] +async fn another_seats_episode_is_refused_and_records_nothing() { + let c = setup().await; + let held = hold(&c).await; + let call = held.call( + "post-1", + "hivemind_post", + json!({"episode_id": "episode:99", "body": "hello"}), + ); + assert!(matches!( + c.submit_action_in_turn(&call, "episode:99", posted("hello")) + .await, + Err(Error::StaleEpisode(_)) + )); + assert!(c.lock().unwrap().durable.running["a"].calls.is_empty()); + held.end().await; +} + +#[tokio::test] +async fn a_failed_commit_leaves_neither_the_effect_nor_its_record() { + let storage = Arc::new(Recording::default()); + let c = Coordinator::new( + "runtime".into(), + storage.clone(), + CoordinatorOptions::default(), + ) + .await + .unwrap(); + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + let episode = held.episode(); + storage.fail_next_commits(1); + assert!( + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .is_err() + ); + let stored = storage.load().await.unwrap(); + assert_eq!(stored.running["a"].actions, Vec::::new()); + assert!(stored.running["a"].calls.is_empty()); + assert_eq!(actions(&c, "a"), Vec::::new()); + // The same call then acts, once. + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + assert_eq!(actions(&c, "a"), [posted("hello")]); + held.end().await; +} + +#[tokio::test] +async fn the_record_survives_a_storage_reload_of_a_running_turn() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("hive.sqlite"); + let storage = Arc::new(SqliteStorage::open(&path).unwrap()); + let c = Coordinator::new("runtime".into(), storage, CoordinatorOptions::default()) + .await + .unwrap(); + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + c.submit_action_in_turn(&call, &held.episode(), posted("hello")) + .await + .unwrap(); + let reloaded = SqliteStorage::open(&path).unwrap().load().await.unwrap(); + assert_eq!( + reloaded.running["a"].calls["post-1"], + CallRecord { + tool: "hivemind_post".into(), + arguments: call.arguments.clone(), + result: Value::Null, + } + ); + held.end().await; +} + +#[tokio::test] +async fn after_a_coordinator_restart_the_retry_is_refused() { + let storage = Arc::new(MemoryStorage::new()); + let c = Coordinator::new( + "runtime".into(), + storage.clone(), + CoordinatorOptions::default(), + ) + .await + .unwrap(); + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + let episode = held.episode(); + c.submit_action_in_turn(&call, &episode, posted("hello")) + .await + .unwrap(); + let restarted = Coordinator::new("runtime".into(), storage, CoordinatorOptions::default()) + .await + .unwrap(); + assert!(matches!( + restarted + .submit_action_in_turn(&call, &episode, posted("hello")) + .await, + Err(Error::StaleTurn { .. }) + )); + held.drain.abort(); +} + +#[tokio::test] +async fn the_record_goes_when_its_turn_ends() { + let storage = Arc::new(MemoryStorage::new()); + let c = Coordinator::new( + "runtime".into(), + storage.clone(), + CoordinatorOptions::default(), + ) + .await + .unwrap(); + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + c.submit_action_in_turn(&call, &held.episode(), posted("hello")) + .await + .unwrap(); + held.end().await; + assert!(storage.load().await.unwrap().running.is_empty()); +} + +fn direct(id: &str, sender: &str) -> SendMessage { + SendMessage { + sender: sender.into(), + ..message(id, Destination::Agent("b".into())) + } +} + +#[tokio::test] +async fn a_retried_send_acts_once_and_returns_the_first_receipt() { + let c = setup().await; + let (mut requests, finish) = holding(&c, &["a"]).await; + add(&c, "b", |request| { + Box::pin(async move { Ok(done(&request)) }) + }) + .await; + c.send_as_host(message("task", Destination::Agent("a".into()))) + .await + .unwrap(); + let drain = tokio::spawn({ + let c = c.clone(); + async move { c.run_until_idle().await } + }); + let request = requests.recv().await.unwrap(); + let held = Held { + request, + finish, + drain, + }; + let call = held.call("send-1", "hivemind_send_agent", json!({"body": "hi"})); + let first = c.send_in_turn(&call, direct("note", "a")).await.unwrap(); + let again = c.send_in_turn(&call, direct("note", "a")).await.unwrap(); + assert_eq!(first, again); + // Two calls with one `message_id` and one payload are one message. + let other = held.call("send-2", "hivemind_send_agent", json!({"body": "hi"})); + assert_eq!( + c.send_in_turn(&other, direct("note", "a")).await.unwrap(), + first + ); + let notes = c + .read_transcript(None) + .unwrap() + .into_iter() + .filter(|message| message.message_id == "note") + .count(); + assert_eq!(notes, 1); + // A send can only be the caller's own. + let forged = held.call("send-3", "hivemind_send_agent", json!({"body": "hi"})); + assert!(matches!( + c.send_in_turn(&forged, direct("forged", "b")).await, + Err(Error::InvalidIdentifier("sender")) + )); + held.end().await; +} + +#[tokio::test] +async fn a_retried_join_acts_once_and_returns_the_first_result() { + let c = setup().await; + let held = hold(&c).await; + c.create_hive(HiveInfo { + hive_id: "side".into(), + name: "Side".into(), + description: None, + members: Vec::new(), + }) + .await + .unwrap(); + let call = held.call( + "join-1", + "hivemind_join_hive", + json!({"hive_id": "side", "agent_id": "a"}), + ); + c.join_hive_in_turn(&call, "side", "a").await.unwrap(); + c.leave_hive("side", "a").await.unwrap(); + c.join_hive_in_turn(&call, "side", "a").await.unwrap(); + let side = c + .list_hives() + .unwrap() + .into_iter() + .find(|h| h.hive_id == "side"); + assert_eq!(side.unwrap().members, Vec::::new()); + held.end().await; +} + +#[tokio::test] +async fn hive_management_in_a_turn_acts_and_is_recorded() { + let c = setup().await; + let held = hold(&c).await; + let hive = HiveInfo { + hive_id: "side".into(), + name: "Side".into(), + description: None, + members: vec!["a".into()], + }; + let create = held.call( + "create-1", + "hivemind_create_hive", + json!({"hive_id": "side"}), + ); + c.create_hive_in_turn(&create, hive.clone()).await.unwrap(); + let leave = held.call( + "leave-1", + "hivemind_leave_hive", + json!({"hive_id": "side", "agent_id": "a"}), + ); + c.leave_hive_in_turn(&leave, "side", "a").await.unwrap(); + c.join_hive("side", "a").await.unwrap(); + // Neither retry acts again: the hive is not recreated and `a` stays. + c.create_hive_in_turn(&create, hive).await.unwrap(); + c.leave_hive_in_turn(&leave, "side", "a").await.unwrap(); + let side = c + .list_hives() + .unwrap() + .into_iter() + .find(|h| h.hive_id == "side"); + assert_eq!(side.unwrap().members, ["a"]); + let calls = c.lock().unwrap().durable.running["a"].calls.clone(); + assert_eq!(calls.keys().collect::>(), ["create-1", "leave-1"]); + held.end().await; +} + +#[tokio::test] +async fn a_recorded_call_is_reported_only_for_its_own_tool_arguments_and_turn() { + let c = setup().await; + let held = hold(&c).await; + let call = held.post("post-1", "hello"); + assert!(!c.call_recorded(&call).unwrap()); + c.submit_action_in_turn(&call, &held.episode(), posted("hello")) + .await + .unwrap(); + assert!(c.call_recorded(&call).unwrap()); + assert!(!c.call_recorded(&held.post("post-1", "other")).unwrap()); + let mut stale = call.clone(); + stale.turn_id = "0:0:a".into(); + assert!(!c.call_recorded(&stale).unwrap()); + held.end().await; + assert!(!c.call_recorded(&call).unwrap()); +} diff --git a/crates/tinyhivemind-hives/src/coordinator/test/mod.rs b/crates/tinyhivemind-hives/src/coordinator/test/mod.rs index a43d0c99..aa6c1d97 100644 --- a/crates/tinyhivemind-hives/src/coordinator/test/mod.rs +++ b/crates/tinyhivemind-hives/src/coordinator/test/mod.rs @@ -318,6 +318,7 @@ async fn membership_removed_before_claim_prevents_later_delivery() { c.leave_hive("work", "a").await.unwrap(); assert_eq!(c.run_until_idle().await.unwrap().completed, 0); } +mod calls; mod failures; mod finalization; mod lifecycle; diff --git a/crates/tinyhivemind-hives/src/coordinator/types.rs b/crates/tinyhivemind-hives/src/coordinator/types.rs index 7b44f221..c23d003e 100644 --- a/crates/tinyhivemind-hives/src/coordinator/types.rs +++ b/crates/tinyhivemind-hives/src/coordinator/types.rs @@ -179,6 +179,24 @@ pub struct SendMessage { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub starters: Vec, } +/// One state-changing call made from a running turn, and who made it. +/// +/// `(agent_id, turn_id, call)` identifies it: the first call with an identity +/// acts and is recorded with its effect, a retry with the same `tool` and +/// `arguments` returns the recorded result, and any other reuse is refused. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct TurnCall { + /// Agent the host bound the call to. + pub agent_id: String, + /// Turn the call says it belongs to; it must be the agent's running one. + pub turn_id: String, + /// Caller-chosen identity, unique per intended action within the turn. + pub call: String, + /// Tool the call names. + pub tool: String, + /// Its arguments, without `turn_id` or `call`. + pub arguments: serde_json::Value, +} /// Receipt returned without waiting for the destination agent. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct Receipt { diff --git a/crates/tinyhivemind-hives/src/error.rs b/crates/tinyhivemind-hives/src/error.rs index 9f42d1ba..1cba4363 100644 --- a/crates/tinyhivemind-hives/src/error.rs +++ b/crates/tinyhivemind-hives/src/error.rs @@ -51,6 +51,19 @@ pub enum Error { /// No active bound episode turn admits the action. #[error("stale episode {0}")] StaleEpisode(String), + /// An identified call names a turn that is not its agent's running one, + /// or its agent has no running turn. + #[error("turn {turn_id} is not the running turn of {agent_id}")] + StaleTurn { + /// Agent the call was made as. + agent_id: String, + /// Turn the call named. + turn_id: String, + }, + /// An identified call reuses a `call` its turn already made with another + /// tool or other arguments. + #[error("call {0} was already made with another tool or arguments")] + CallReused(String), /// Store revision changed before commit. #[error("storage revision conflict: expected {expected}, found {actual}")] RevisionConflict { diff --git a/crates/tinyhivemind-hives/src/storage/README.md b/crates/tinyhivemind-hives/src/storage/README.md index 76b26eb5..18a2af0a 100644 --- a/crates/tinyhivemind-hives/src/storage/README.md +++ b/crates/tinyhivemind-hives/src/storage/README.md @@ -34,3 +34,8 @@ from current memberships. Every episode freezes its settings and scheduled job identity. Transcript rows persist scheduled authority on `Message`, while running reservations retain it in `TurnRequest`; legacy rows default to no explicit settings or scheduled origin. + +`RunningTurn::calls` maps each identified call of the turn to its +`CallRecord` (tool, arguments, result). It is omitted when empty, so a +snapshot written before it existed loads unchanged and a turn without +identified calls serializes as before. diff --git a/crates/tinyhivemind-hives/src/storage/mod.rs b/crates/tinyhivemind-hives/src/storage/mod.rs index b6566b95..a0f6b352 100644 --- a/crates/tinyhivemind-hives/src/storage/mod.rs +++ b/crates/tinyhivemind-hives/src/storage/mod.rs @@ -10,8 +10,8 @@ use crate::{Error, Result}; pub use sqlite::SqliteStorage; use std::{future::Future, pin::Pin, sync::Mutex}; pub use types::{ - AgentRecord, Delivery, DeliveryStatus, EpisodeRecord, ParkedTurn, RetentionPolicy, RunningTurn, - StoredState, TranscriptRow, + AgentRecord, CallRecord, Delivery, DeliveryStatus, EpisodeRecord, ParkedTurn, RetentionPolicy, + RunningTurn, StoredState, TranscriptRow, }; /// Future returned by a [`Storage`] operation. Boxed and `Send` so the port diff --git a/crates/tinyhivemind-hives/src/storage/test.rs b/crates/tinyhivemind-hives/src/storage/test.rs index 49308531..3745647e 100644 --- a/crates/tinyhivemind-hives/src/storage/test.rs +++ b/crates/tinyhivemind-hives/src/storage/test.rs @@ -254,6 +254,7 @@ fn retention_keeps_a_settled_episode_a_running_turn_still_reports_to() { turn: None, actions: Vec::new(), delivery_sequence: None, + calls: std::collections::BTreeMap::new(), }, ); RetentionPolicy { @@ -276,3 +277,54 @@ fn retention_policy_wire_form_and_omitted_defaults_are_stable() { serde_json::json!({"settled_episodes":null,"delivered":null,"interrupted":null,"pending_per_agent":null}) ); } + +/// A running turn as a snapshot written before call records existed. +const OLDER_RUNNING_TURN: &str = r#"{ + "request": { + "turn_id": "1:4:a", "agent_id": "a", "session_id": null, + "messages": [], "memberships": [], "episode": null + }, + "turn": null, + "actions": [{"Post": {"body": "hi"}}], + "delivery_sequence": 3 +}"#; + +#[test] +fn a_running_turn_from_before_call_records_loads_with_no_calls() { + let turn: RunningTurn = serde_json::from_str(OLDER_RUNNING_TURN).unwrap(); + assert!(turn.calls.is_empty()); + assert_eq!(turn.delivery_sequence, Some(3)); +} + +#[test] +fn a_running_turn_without_calls_serializes_as_before() { + let turn: RunningTurn = serde_json::from_str(OLDER_RUNNING_TURN).unwrap(); + let value = serde_json::to_value(&turn).unwrap(); + assert!(value.get("calls").is_none()); +} + +#[test] +fn call_records_have_a_pinned_wire_form() { + let mut turn: RunningTurn = serde_json::from_str(OLDER_RUNNING_TURN).unwrap(); + turn.calls.insert( + "post-1".into(), + CallRecord { + tool: "hivemind_post".into(), + arguments: serde_json::json!({"episode_id": "episode:1", "body": "hi"}), + result: serde_json::Value::Null, + }, + ); + let value = serde_json::to_value(&turn).unwrap(); + assert_eq!( + value["calls"], + serde_json::json!({ + "post-1": { + "tool": "hivemind_post", + "arguments": {"episode_id": "episode:1", "body": "hi"}, + "result": null + } + }) + ); + let back: RunningTurn = serde_json::from_value(value).unwrap(); + assert_eq!(back.calls, turn.calls); +} diff --git a/crates/tinyhivemind-hives/src/storage/types.rs b/crates/tinyhivemind-hives/src/storage/types.rs index ab006a12..bc23904d 100644 --- a/crates/tinyhivemind-hives/src/storage/types.rs +++ b/crates/tinyhivemind-hives/src/storage/types.rs @@ -297,4 +297,36 @@ pub struct RunningTurn { pub actions: Vec, /// Accepted direct message sequence when present. pub delivery_sequence: Option, + /// Identified calls this turn made, by the caller's `call`, each recorded + /// in the transaction that made its effect. Absent from snapshots written + /// before calls were identified, and gone with the turn. + #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] + pub calls: BTreeMap, +} +impl RunningTurn { + /// A turn just claimed: nothing staged and no call made yet. + pub(crate) fn claimed( + request: TurnRequest, + turn: Option, + delivery_sequence: Option, + ) -> Self { + Self { + request, + turn, + actions: Vec::new(), + delivery_sequence, + calls: BTreeMap::new(), + } + } +} +/// What one identified call of a running turn did, so that a retry of it is +/// answered rather than repeated. +#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] +pub struct CallRecord { + /// The tool the call named. + pub tool: String, + /// Its arguments, without the call's own identity. + pub arguments: serde_json::Value, + /// What the coordinator returned. + pub result: serde_json::Value, } diff --git a/crates/tinyhivemind-host/src/harness/events.rs b/crates/tinyhivemind-host/src/harness/events.rs index 262c7d55..71fab70c 100644 --- a/crates/tinyhivemind-host/src/harness/events.rs +++ b/crates/tinyhivemind-host/src/harness/events.rs @@ -104,15 +104,18 @@ impl Observer for Ignore { fn event(&self, _: &str, _: Event) {} } -/// A harness asking whether one of its own tools may run. Hive tools never -/// ask: their policy runs where they are served. +/// A request to run one tool call: a harness asking about one of its own +/// tools, or the host's tool server asking about an effectful executable +/// tool of a `supervised` seat. Hive tools never ask: send and management +/// policy decide them. #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] pub struct ToolApproval { /// The seat asking. pub seat: String, /// The running turn. pub turn_id: String, - /// The harness's id for the call. + /// The harness's id for the call, or the model's `call` when the tool + /// server asks. pub call_id: String, /// The tool. pub tool: String, @@ -136,7 +139,7 @@ pub enum ToolDecision { /// Future returned by [`Approver::decide`]. pub type ApprovalFuture = Pin + Send>>; -/// Decides what a harness asks. +/// Decides whether a tool call may run, for a harness or the tool server. pub trait Approver: Send + Sync { /// Decide `request`. The turn waits, within its own timeout. fn decide(&self, request: ToolApproval) -> ApprovalFuture; diff --git a/crates/tinyhivemind-host/src/tools/README.md b/crates/tinyhivemind-host/src/tools/README.md index c2d06bb5..fafa5084 100644 --- a/crates/tinyhivemind-host/src/tools/README.md +++ b/crates/tinyhivemind-host/src/tools/README.md @@ -10,6 +10,12 @@ fit, and its actor and session come from the host, never from an argument. `Belt` executes one. Reads and sends are admitted by coordinator membership and visibility checks; episode actions require the caller's active episode. +`ToolCall::in_turn(turn_id, call)` identifies a call as one action of the +actor's running turn. The belt then sends, stages and manages hives through the +coordinator's `*_in_turn` entry points, which refuse a turn that is not running +and answer a retry from the record written with the effect. `create_agent` is +the creator's, outside that record. Unidentified calls behave as before. + `hivemind_read` requires exactly one of `hive_id` or `agent_id`. Hive reads may include `thread`; direct reads return only the caller's conversation with that peer. `after` is an exclusive sequence cursor in both. Reading schedules nothing. @@ -19,6 +25,10 @@ it a `SendRequest` first; a refusal enqueues and stages nothing. Management consults its authorizer before any mutation, and reaches a harness only through `policy::AgentCreator`. Without it, the management tools are refused. +`Belt::authorize(&call)` runs exactly that send and management policy with no +effect, for a host that must act between authorization and dispatch (the MCP +server runs package hooks there). `Belt::call` still checks again. + | File | Responsibility | | --- | --- | | `mod.rs` | `Belt`: policies, then the coordinator | diff --git a/crates/tinyhivemind-host/src/tools/call.rs b/crates/tinyhivemind-host/src/tools/call.rs index a45071bd..83800772 100644 --- a/crates/tinyhivemind-host/src/tools/call.rs +++ b/crates/tinyhivemind-host/src/tools/call.rs @@ -5,7 +5,7 @@ use crate::{ policy::{ManagementRequest, SendRequest}, }; use serde_json::Value; -use tinyhivemind_hives::HiveInfo; +use tinyhivemind_hives::{HiveInfo, TurnCall}; /// A hive tool call with validated arguments and a host-bound caller. /// @@ -16,6 +16,8 @@ pub struct ToolCall { session: Option, kind: Kind, args: Value, + /// The running turn and caller-chosen call this one says it is. + identity: Option<(String, String)>, } impl ToolCall { /// A call to `kind` by the seat the host bound it to. @@ -34,6 +36,28 @@ impl ToolCall { session, kind, args, + identity: None, + }) + } + /// The same call, identified as `call` of the actor's running turn + /// `turn_id`. + /// + /// A coordinator action of an identified call is refused unless that turn + /// is running, and acts at most once per `call`: a retry with the same + /// arguments returns the recorded result, and other reuse is refused. + #[must_use] + pub fn in_turn(mut self, turn_id: impl Into, call: impl Into) -> Self { + self.identity = Some((turn_id.into(), call.into())); + self + } + /// The coordinator's identity for this call, when it has one. + pub(super) fn turn_call(&self) -> Option { + self.identity.as_ref().map(|(turn_id, call)| TurnCall { + agent_id: self.actor.clone(), + turn_id: turn_id.clone(), + call: call.clone(), + tool: self.kind.name().into(), + arguments: self.args.clone(), }) } pub(super) fn actor(&self) -> &str { diff --git a/crates/tinyhivemind-host/src/tools/mod.rs b/crates/tinyhivemind-host/src/tools/mod.rs index d2647017..7cef40b2 100644 --- a/crates/tinyhivemind-host/src/tools/mod.rs +++ b/crates/tinyhivemind-host/src/tools/mod.rs @@ -11,7 +11,7 @@ use crate::{ }; pub use call::ToolCall; use serde_json::{Value, json}; -use tinyhivemind_hives::{Coordinator, Destination, EpisodeAction, SendMessage}; +use tinyhivemind_hives::{Coordinator, Destination, EpisodeAction, SendMessage, TurnCall}; pub use types::Kind; /// Executes hive tool calls against a coordinator under the host's policies. @@ -51,6 +51,32 @@ impl<'a> Belt<'a> { self.management = Some(management); self } + /// Run exactly the send and management policy [`Self::call`] would run + /// for `call`, with no effect. + /// + /// A host that has to act between authorization and dispatch, such as + /// running a package hook, calls this first. [`Self::call`] still checks + /// again, so a policy that changes between the two is judged by the + /// second check. + /// + /// # Errors + /// The send policy's refusal, disabled management, the management + /// authorizer's refusal, or a memory contract that does not decode. + pub fn authorize(&self, call: &ToolCall) -> Result<()> { + if let (Some(policy), Some(request)) = (self.send_policy, call.outbound()) { + policy.authorize_in_session(call.actor(), &request, call.session())?; + } + if matches!( + call.kind(), + Kind::CreateHive | Kind::CreateAgent | Kind::JoinHive | Kind::LeaveHive + ) { + let management = self.management.ok_or(Error::ManagementDisabled)?; + management + .authorizer + .authorize(call.actor(), &call.management()?)?; + } + Ok(()) + } /// Execute one validated call as its bound actor. /// /// # Errors @@ -59,7 +85,15 @@ impl<'a> Belt<'a> { pub async fn call(&self, call: &ToolCall) -> Result { let coordinator = self.coordinator; let actor = call.actor(); - if let (Some(policy), Some(request)) = (self.send_policy, call.outbound()) { + // A recorded identified call was authorized when it acted; its retry + // is answered from the record and acts on nothing, so policy is not + // asked again. + let recorded = match call.turn_call() { + Some(turn) => coordinator.call_recorded(&turn)?, + None => false, + }; + if let (false, Some(policy), Some(request)) = (recorded, self.send_policy, call.outbound()) + { policy.authorize_in_session(actor, &request, call.session())?; } match call.kind() { @@ -110,7 +144,9 @@ impl<'a> Belt<'a> { self.submit(call, EpisodeAction::Complete { body }).await } Kind::CreateHive | Kind::CreateAgent | Kind::JoinHive | Kind::LeaveHive => { - self.manage(actor, call.management()?).await + let turn = call.turn_call(); + self.manage_as(actor, call.management()?, turn.as_ref(), recorded) + .await } } } @@ -119,11 +155,29 @@ impl<'a> Belt<'a> { /// # Errors /// Disabled management, host denial, agent creation or coordinator errors. pub async fn manage(&self, actor: &str, request: ManagementRequest) -> Result { + self.manage_as(actor, request, None, false).await + } + /// [`Self::manage`], through the coordinator's identified calls when `turn` + /// is given, without asking the authorizer again for a `recorded` one. + /// Creating an agent is the creator's, outside them. + async fn manage_as( + &self, + actor: &str, + request: ManagementRequest, + turn: Option<&TurnCall>, + recorded: bool, + ) -> Result { let management = self.management.ok_or(Error::ManagementDisabled)?; - management.authorizer.authorize(actor, &request)?; + if !recorded { + management.authorizer.authorize(actor, &request)?; + } + let coordinator = self.coordinator; match request { ManagementRequest::CreateHive(hive) => { - self.coordinator.create_hive(hive.clone()).await?; + match turn { + Some(turn) => coordinator.create_hive_in_turn(turn, hive.clone()).await?, + None => coordinator.create_hive(hive.clone()).await?, + } Ok(serde_json::to_value(hive)?) } ManagementRequest::CreateAgent { @@ -142,34 +196,59 @@ impl<'a> Belt<'a> { Ok(json!({"agent_id":agent_id})) } ManagementRequest::JoinHive { hive_id, agent_id } => { - self.coordinator.join_hive(&hive_id, &agent_id).await?; + match turn { + Some(turn) => { + coordinator + .join_hive_in_turn(turn, &hive_id, &agent_id) + .await?; + } + None => coordinator.join_hive(&hive_id, &agent_id).await?, + } Ok(json!({"joined":true})) } ManagementRequest::LeaveHive { hive_id, agent_id } => { - self.coordinator.leave_hive(&hive_id, &agent_id).await?; + match turn { + Some(turn) => { + coordinator + .leave_hive_in_turn(turn, &hive_id, &agent_id) + .await?; + } + None => coordinator.leave_hive(&hive_id, &agent_id).await?, + } Ok(json!({"left":true})) } } } async fn send(&self, call: &ToolCall, destination: Destination) -> Result { - let receipt = self - .coordinator - .send(SendMessage { - message_id: call.text("message_id"), - sender: call.actor().to_owned(), - destination, - body: call.text("body"), - thread: call.integer("thread"), - only_for: call.strings("only_for"), - starters: Vec::new(), - }) - .await?; + let message = SendMessage { + message_id: call.text("message_id"), + sender: call.actor().to_owned(), + destination, + body: call.text("body"), + thread: call.integer("thread"), + only_for: call.strings("only_for"), + starters: Vec::new(), + }; + let receipt = match call.turn_call() { + Some(turn) => self.coordinator.send_in_turn(&turn, message).await?, + None => self.coordinator.send(message).await?, + }; Ok(serde_json::to_value(receipt)?) } async fn submit(&self, call: &ToolCall, action: EpisodeAction) -> Result { - self.coordinator - .submit_action(call.actor(), &call.text("episode_id"), action) - .await?; + let episode = call.text("episode_id"); + match call.turn_call() { + Some(turn) => { + self.coordinator + .submit_action_in_turn(&turn, &episode, action) + .await?; + } + None => { + self.coordinator + .submit_action(call.actor(), &episode, action) + .await?; + } + } Ok(json!({"accepted":true})) } } diff --git a/crates/tinyhivemind-host/src/tools/test/README.md b/crates/tinyhivemind-host/src/tools/test/README.md index 01b208fd..7149c85b 100644 --- a/crates/tinyhivemind-host/src/tools/test/README.md +++ b/crates/tinyhivemind-host/src/tools/test/README.md @@ -7,4 +7,6 @@ | `episodes.rs` | Episode actions inside and outside an assignment | | `sends.rs` | The send policy | | `management.rs` | Authorization, agent creation and disabled management | +| `authorize.rs` | `Belt::authorize`: the same send and management policy, with no effect | +| `identified.rs` | Calls identified by turn act once through the coordinator record | | `support.rs` | A coordinator with registered agents | diff --git a/crates/tinyhivemind-host/src/tools/test/authorize.rs b/crates/tinyhivemind-host/src/tools/test/authorize.rs new file mode 100644 index 00000000..abfa788d --- /dev/null +++ b/crates/tinyhivemind-host/src/tools/test/authorize.rs @@ -0,0 +1,73 @@ +//! `Belt::authorize` runs the policy a call would meet, and nothing else. +use super::support::{coordinator, with_agents}; +use crate::{ + Error, Result, + policy::{ + AgentCreator, CreateFuture, Management, ManagementAuthorizer, ManagementRequest, NewAgent, + SendAuthorizer, SendRequest, + }, + tools::{Belt, Kind, ToolCall}, +}; +use serde_json::json; + +/// Refuses every direct message. +struct NoDirect; +impl SendAuthorizer for NoDirect { + fn authorize(&self, _: &str, request: &SendRequest) -> Result<()> { + match request { + SendRequest::Agent { .. } => Err(Error::SendDenied("no direct messages".into())), + _ => Ok(()), + } + } +} +/// Refuses joins; builds nothing. +struct NoJoins; +impl ManagementAuthorizer for NoJoins { + fn authorize(&self, _: &str, request: &ManagementRequest) -> Result<()> { + match request { + ManagementRequest::JoinHive { .. } => Err(Error::Unauthorized("no joins".into())), + _ => Ok(()), + } + } +} +impl AgentCreator for NoJoins { + fn create(&self, _: NewAgent) -> CreateFuture<'_> { + Box::pin(async { Err(Error::Host("creates nothing".into())) }) + } +} + +#[tokio::test] +async fn authorize_refuses_what_the_send_policy_refuses_and_sends_nothing() -> Result<()> { + let coordinator = with_agents(&["a", "b"]).await?; + let belt = Belt::new(&coordinator).with_send_policy(&NoDirect); + let direct = json!({"agent_id": "b", "message_id": "m1", "body": "hi"}); + let call = ToolCall::new("a", None, Kind::SendAgent, direct)?; + assert!(matches!(belt.authorize(&call), Err(Error::SendDenied(_)))); + assert_eq!(coordinator.read_direct("a", "b", None)?.len(), 0); + let post = json!({"episode_id": "e", "body": "b"}); + belt.authorize(&ToolCall::new("a", None, Kind::Post, post)?)?; + belt.authorize(&ToolCall::new("a", None, Kind::ListHives, json!({}))?)?; + Ok(()) +} + +#[tokio::test] +async fn authorize_refuses_what_management_refuses_or_lacks() -> Result<()> { + let coordinator = coordinator().await?; + let join = json!({"hive_id": "h", "agent_id": "a"}); + let call = ToolCall::new("a", None, Kind::JoinHive, join)?; + assert!(matches!( + Belt::new(&coordinator).authorize(&call), + Err(Error::ManagementDisabled) + )); + let managed = Belt::new(&coordinator).with_management(Management { + authorizer: &NoJoins, + creator: &NoJoins, + }); + assert!(matches!( + managed.authorize(&call), + Err(Error::Unauthorized(_)) + )); + let leave = json!({"hive_id": "h", "agent_id": "a"}); + managed.authorize(&ToolCall::new("a", None, Kind::LeaveHive, leave)?)?; + Ok(()) +} diff --git a/crates/tinyhivemind-host/src/tools/test/identified.rs b/crates/tinyhivemind-host/src/tools/test/identified.rs new file mode 100644 index 00000000..9bbfa3ff --- /dev/null +++ b/crates/tinyhivemind-host/src/tools/test/identified.rs @@ -0,0 +1,227 @@ +//! A call identified by its turn acts once, through the coordinator's record. +use super::support::{coordinator, hive}; +use crate::{ + Error, Result, + policy::{ + AgentCreator, CreateFuture, Management, ManagementAuthorizer, ManagementRequest, NewAgent, + }, + tools::{Belt, Kind, ToolCall}, +}; +use serde_json::{Value, json}; +use std::sync::Arc; +use tinyhivemind_hives::{ + AgentRegistration, AgentRunner, Coordinator, Destination, HiveInfo, SendMessage, + TurnDisposition, TurnFuture, TurnOutcome, TurnRequest, +}; +use tokio::sync::{Notify, mpsc}; + +/// Hands its first turn's request to the test and holds that turn open. +struct Holds { + started: mpsc::UnboundedSender, + finish: Arc, +} +impl AgentRunner for Holds { + fn run(&self, request: TurnRequest) -> TurnFuture { + let (started, finish) = (self.started.clone(), self.finish.clone()); + Box::pin(async move { + if started.send(request.clone()).is_ok() { + finish.notified().await; + } + Ok(TurnOutcome { + session_id: "stable".into(), + reply: None, + disposition: TurnDisposition::Completed, + }) + }) + } +} +/// Admits everything; creates nothing. +struct Open; +impl ManagementAuthorizer for Open { + fn authorize(&self, _: &str, _: &ManagementRequest) -> Result<()> { + Ok(()) + } +} +impl AgentCreator for Open { + fn create(&self, _: NewAgent) -> CreateFuture<'_> { + Box::pin(async { Err(Error::Host("creates nothing".into())) }) + } +} + +/// `a`'s running turn in hive `h`, with `b` registered beside it. +async fn running() -> Result<(Coordinator, TurnRequest, Arc)> { + let coordinator = coordinator().await?; + let (started, mut requests) = mpsc::unbounded_channel(); + let finish = Arc::new(Notify::new()); + for id in ["a", "b"] { + coordinator + .register_agent(AgentRegistration { + agent_id: id.into(), + runtime_id: "r".into(), + runner: Arc::new(Holds { + started: started.clone(), + finish: finish.clone(), + }), + }) + .await?; + } + coordinator.create_hive(hive(&["a"])).await?; + coordinator + .send_as_host(SendMessage { + message_id: "start".into(), + sender: String::new(), + destination: Destination::Hive("h".into()), + body: "work".into(), + thread: None, + only_for: vec![], + starters: Vec::new(), + }) + .await?; + tokio::spawn({ + let coordinator = coordinator.clone(); + async move { coordinator.run_until_idle().await } + }); + let request = requests.recv().await.ok_or(Error::ManagementDisabled)?; + Ok((coordinator, request, finish)) +} +fn identified(request: &TurnRequest, call: &str, kind: Kind, args: Value) -> Result { + Ok(ToolCall::new(&request.agent_id, None, kind, args)?.in_turn(&request.turn_id, call)) +} +fn episode(request: &TurnRequest) -> String { + request + .episode + .as_ref() + .map(|episode| episode.episode_id.clone()) + .unwrap_or_default() +} + +#[tokio::test] +async fn an_identified_post_retried_acts_once_and_another_call_acts_again() -> Result<()> { + let (coordinator, request, finish) = running().await?; + let belt = Belt::new(&coordinator); + let args = json!({"episode_id": episode(&request), "body": "once"}); + let first = identified(&request, "p1", Kind::Post, args.clone())?; + assert_eq!(belt.call(&first).await?, json!({"accepted": true})); + assert_eq!(belt.call(&first).await?, json!({"accepted": true})); + let second = identified(&request, "p2", Kind::Post, args)?; + belt.call(&second).await?; + let reused = identified( + &request, + "p1", + Kind::Post, + json!({"episode_id": episode(&request), "body": "changed"}), + )?; + assert!(matches!( + belt.call(&reused).await, + Err(Error::Coordinator(tinyhivemind_hives::Error::CallReused(_))) + )); + finish.notify_one(); + Ok(()) +} + +#[tokio::test] +async fn an_identified_call_naming_another_turn_is_refused() -> Result<()> { + let (coordinator, request, finish) = running().await?; + let belt = Belt::new(&coordinator); + let args = json!({"episode_id": episode(&request), "body": "late"}); + let stale = ToolCall::new("a", None, Kind::Post, args)?.in_turn("0:0:a", "p1"); + assert!(matches!( + belt.call(&stale).await, + Err(Error::Coordinator( + tinyhivemind_hives::Error::StaleTurn { .. } + )) + )); + finish.notify_one(); + Ok(()) +} + +#[tokio::test] +async fn an_identified_send_retried_returns_the_first_receipt() -> Result<()> { + let (coordinator, request, finish) = running().await?; + let belt = Belt::new(&coordinator); + let args = json!({"agent_id": "b", "message_id": "m1", "body": "hi"}); + let send = identified(&request, "s1", Kind::SendAgent, args)?; + let receipt = belt.call(&send).await?; + assert_eq!(belt.call(&send).await?, receipt); + let delivered = coordinator.read_direct("a", "b", None)?; + assert_eq!(delivered.len(), 1); + finish.notify_one(); + Ok(()) +} + +#[tokio::test] +async fn identified_hive_management_acts_once() -> Result<()> { + let (coordinator, request, finish) = running().await?; + let belt = Belt::new(&coordinator).with_management(Management { + authorizer: &Open, + creator: &Open, + }); + let create = identified( + &request, + "c1", + Kind::CreateHive, + json!({"hive_id": "side", "name": "Side"}), + )?; + belt.call(&create).await?; + let join = identified( + &request, + "j1", + Kind::JoinHive, + json!({"hive_id": "side", "agent_id": "b"}), + )?; + assert_eq!(belt.call(&join).await?, json!({"joined": true})); + let leave = identified( + &request, + "l1", + Kind::LeaveHive, + json!({"hive_id": "side", "agent_id": "b"}), + )?; + assert_eq!(belt.call(&leave).await?, json!({"left": true})); + // A retried join is answered from its record and joins nobody. + assert_eq!(belt.call(&join).await?, json!({"joined": true})); + let side: Vec = coordinator + .list_hives()? + .into_iter() + .filter(|hive| hive.hive_id == "side") + .collect(); + assert_eq!(side[0].members, Vec::::new()); + finish.notify_one(); + Ok(()) +} + +/// Admits sends until closed, counting what it is asked. +#[derive(Default)] +struct Closing { + closed: std::sync::atomic::AtomicBool, + asked: std::sync::atomic::AtomicUsize, +} +impl crate::policy::SendAuthorizer for Closing { + fn authorize(&self, _: &str, _: &crate::policy::SendRequest) -> Result<()> { + use std::sync::atomic::Ordering; + self.asked.fetch_add(1, Ordering::SeqCst); + if self.closed.load(Ordering::SeqCst) { + Err(Error::SendDenied("closed".into())) + } else { + Ok(()) + } + } +} + +#[tokio::test] +async fn a_recorded_send_is_answered_without_asking_the_policy_again() -> Result<()> { + use std::sync::atomic::Ordering; + let (coordinator, request, finish) = running().await?; + let policy = Closing::default(); + let belt = Belt::new(&coordinator).with_send_policy(&policy); + let args = json!({"agent_id": "b", "message_id": "m1", "body": "hi"}); + let send = identified(&request, "s1", Kind::SendAgent, args)?; + let receipt = belt.call(&send).await?; + policy.closed.store(true, Ordering::SeqCst); + assert_eq!(belt.call(&send).await?, receipt); + assert_eq!(policy.asked.load(Ordering::SeqCst), 1); + let args = json!({"agent_id": "b", "message_id": "m2", "body": "hi"}); + let other = identified(&request, "s2", Kind::SendAgent, args)?; + assert!(matches!(belt.call(&other).await, Err(Error::SendDenied(_)))); + finish.notify_one(); + Ok(()) +} diff --git a/crates/tinyhivemind-host/src/tools/test/mod.rs b/crates/tinyhivemind-host/src/tools/test/mod.rs index ff1d1c15..f46d7541 100644 --- a/crates/tinyhivemind-host/src/tools/test/mod.rs +++ b/crates/tinyhivemind-host/src/tools/test/mod.rs @@ -1,6 +1,8 @@ //! The belt acts for its bound caller, under the host's policies. +mod authorize; mod declarations; mod episodes; +mod identified; mod management; mod messaging; mod sends; diff --git a/crates/tinyhivemind-mcp/Cargo.toml b/crates/tinyhivemind-mcp/Cargo.toml new file mode 100644 index 00000000..c14e8ed8 --- /dev/null +++ b/crates/tinyhivemind-mcp/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "tinyhivemind-mcp" +description = "Serves hive tools and a package's executable tools to harness processes over loopback MCP." +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +readme = "README.md" +publish = false +# This crate opens a listening socket, on 127.0.0.1 only (ADR 0036), so it is +# outside the pure crates. It names no harness and links none; +# `.github/scripts/assert-pure.sh` asserts that no harness is in its graph. + +[dependencies] +# The tool belt, its policy ports, `ToolEndpoint` and the `Approver` port. +tinyhivemind-host.workspace = true +# The coordinator: running turns and identified calls. +tinyhivemind-hives.workspace = true +# Seat declarations: executable tools, hooks, permissions, autonomy. +tinyhivemind-lang.workspace = true +# Runs executable tools and hooks under the package calling convention. +tinyhivemind-exec.workspace = true +# The HTTP/1.1 server; see the workspace entry for why. +hyper.workspace = true +hyper-util.workspace = true +http-body-util.workspace = true +# Bearer comparison and generation. +subtle.workspace = true +getrandom.workspace = true +# JSON-RPC messages and tool arguments. +serde_json.workspace = true +# Typed errors. +thiserror.workspace = true +# The listener, connection tasks, the shutdown signal and body deadlines. +tokio = { workspace = true, features = ["net", "rt", "sync", "time", "macros"] } + +[dev-dependencies] +# The loopback client the tests drive the server with. +hyper = { workspace = true, features = ["client"] } +# Async tests on a multi-threaded runtime. +tokio = { workspace = true, features = ["macros", "rt-multi-thread"] } +# Seat workspaces the fixture tools write in. +tempfile.workspace = true + +[lints] +workspace = true diff --git a/crates/tinyhivemind-mcp/README.md b/crates/tinyhivemind-mcp/README.md new file mode 100644 index 00000000..07887806 --- /dev/null +++ b/crates/tinyhivemind-mcp/README.md @@ -0,0 +1,26 @@ +# tinyhivemind-mcp + +Serves a seat's hive tools and its package's executable tools to a harness +that runs as a child process, over the Streamable HTTP transport of the Model +Context Protocol, on a random port of 127.0.0.1 +([ADR 0036](../../docs/adr/0036-hive-tools-are-served-over-loopback-mcp.md)). + +Every seat gets its own random bearer, and the bearer alone decides who is +calling. A state-changing call also names its `turn` and a `call` of its own +choosing: a call from a turn that is not running is refused, and a retry of a +call returns the first result instead of acting again. Package hooks, tool +permissions and the `autonomy` gate run here, before dispatch, so they hold +whichever harness the seat runs on. + +It holds no episode state (the coordinator in +[`tinyhivemind-hives`](../tinyhivemind-hives/README.md) does), starts no +harness, and links none; `.github/scripts/assert-pure.sh` checks the last. It +opens a listening socket, so it is not one of the pure crates. + +The behaviour is specified in [the harnesses spec](../../docs/specs/harnesses.md#hive-tools); +the repository [README](../../README.md) says how this fits the rest. + +| Path | Purpose | +| --- | --- | +| [`src/`](src/README.md) | The crate's modules | +| [`tests/`](tests/README.md) | Loopback HTTP tests of the whole contract | diff --git a/crates/tinyhivemind-mcp/src/README.md b/crates/tinyhivemind-mcp/src/README.md new file mode 100644 index 00000000..c4a5875b --- /dev/null +++ b/crates/tinyhivemind-mcp/src/README.md @@ -0,0 +1,14 @@ +# Source + +| Path | Purpose | +| --- | --- | +| `lib.rs` | Crate overview, example and public surface | +| `error/` | `Error`: why a server could not start or a seat could not be served; `test.rs` pins the messages | +| [`server/`](server/README.md) | The listener, request admission and JSON-RPC | +| [`seat/`](seat/README.md) | `SeatTools` and the seat's bearer | +| [`tools/`](tools/README.md) | The served catalog and how one call is carried out | + +The public surface is `HiveToolServer`, `Services`, `ServerOptions`, +`SeatTools`, `PROTOCOL_VERSIONS` and `Error`. A seat's endpoint is the host's +`tinyhivemind_host::harness::ToolEndpoint`, and the approver is the host's +`tinyhivemind_host::harness::Approver`. diff --git a/crates/tinyhivemind-mcp/src/error/README.md b/crates/tinyhivemind-mcp/src/error/README.md new file mode 100644 index 00000000..7e6745be --- /dev/null +++ b/crates/tinyhivemind-mcp/src/error/README.md @@ -0,0 +1,6 @@ +# Errors + +| File | Holds | +| --- | --- | +| `mod.rs` | `Error` and `Result`: why the server could not start or a seat could not be served | +| `test.rs` | The message of each variant, including those no test can provoke | diff --git a/crates/tinyhivemind-mcp/src/error/mod.rs b/crates/tinyhivemind-mcp/src/error/mod.rs new file mode 100644 index 00000000..5320a79c --- /dev/null +++ b/crates/tinyhivemind-mcp/src/error/mod.rs @@ -0,0 +1,51 @@ +//! Why a server could not start, or a seat could not be served. + +/// Server result. +pub type Result = std::result::Result; + +/// Failures starting the server and serving a seat. A refused tool call is +/// not one of these: the model reads it as the tool's error result. +#[derive(Debug, thiserror::Error)] +pub enum Error { + /// The loopback listener could not be opened. + #[error("cannot listen on loopback: {0}")] + Listen(#[source] std::io::Error), + /// The operating system gave no randomness for a bearer. + #[error("no randomness for a bearer: {0}")] + Random(String), + /// The seat declares a sandbox, which nothing confines here yet. + #[error("seat {0} declares a sandbox, which this server cannot enforce")] + UnsupportedSandbox(String), + /// The seat declares package MCP servers, which are not proxied yet. + #[error("seat {0} declares package mcp servers, which this server does not proxy")] + UnsupportedMcpServers(String), + /// An executable tool declares an argument the server adds itself. + #[error("tool {tool} declares the reserved argument {name}")] + ReservedArgument { + /// The tool. + tool: String, + /// `turn` or `call`. + name: String, + }, + /// An executable tool's argument schema uses a keyword the server cannot + /// check, so it could not refuse arguments that break it. + #[error("tool {tool} declares the schema keyword {keyword}, which this server cannot check")] + UnsupportedSchema { + /// The tool. + tool: String, + /// The keyword. + keyword: String, + }, + /// Two of a seat's tools have one name. + #[error("tool {0} is declared twice")] + DuplicateTool(String), + /// The seat is already served. + #[error("seat {0} is already served")] + DuplicateSeat(String), + /// The server's task ended other than by returning. + #[error("the server task failed: {0}")] + Stopped(String), +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-mcp/src/error/test.rs b/crates/tinyhivemind-mcp/src/error/test.rs new file mode 100644 index 00000000..9fb65620 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/error/test.rs @@ -0,0 +1,30 @@ +//! Every error reads as a lowercase sentence naming what failed. +use super::Error; + +#[test] +fn errors_name_what_failed() { + let cases = [ + ( + Error::Listen(std::io::Error::other("no socket")), + "cannot listen on loopback: no socket", + ), + ( + Error::Random("no entropy".into()), + "no randomness for a bearer: no entropy", + ), + ( + Error::Stopped("panicked".into()), + "the server task failed: panicked", + ), + ( + Error::UnsupportedSchema { + tool: "t".into(), + keyword: "pattern".into(), + }, + "tool t declares the schema keyword pattern, which this server cannot check", + ), + ]; + for (error, text) in cases { + assert_eq!(error.to_string(), text); + } +} diff --git a/crates/tinyhivemind-mcp/src/lib.rs b/crates/tinyhivemind-mcp/src/lib.rs new file mode 100644 index 00000000..de5338c6 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/lib.rs @@ -0,0 +1,64 @@ +//! Hive tools for harness processes, over MCP on loopback. +//! +//! A harness that runs as a child process cannot be handed a native tool, so +//! [`HiveToolServer`] serves a seat's hive tools and its package's +//! executable tools over the Streamable HTTP transport of the Model Context +//! Protocol, on a random port of 127.0.0.1 (ADR 0036): +//! +//! - **Identity.** [`HiveToolServer::serve_seat`] draws a random bearer per +//! seat and returns its [`ToolEndpoint`]. The bearer alone decides the +//! actor; it is compared in constant time and never printed. +//! - **Turn and call.** Every state-changing tool's schema gets two required +//! arguments, `turn` and `call`, removed again before hooks and dispatch. +//! A call whose `turn` is not the seat's running turn is refused. The +//! identity (seat, turn, call) makes a retry return the first result: a +//! coordinator action is recorded by the coordinator in the transaction of +//! its effect, and an executable tool, `create_agent` or any call a hook +//! matches is recorded here, started and finished, in memory. +//! - **Policy.** Package hooks, permission tool names and the `autonomy` and +//! `access` gate run here, before dispatch; a supervised effectful tool is +//! asked of the host's [`Approver`], and refused when there is none. Hive +//! tools go through the host's send and management policy in the belt. +//! - **Surface.** Tools only; resource and prompt lists are empty. A bad +//! `Host`, any `Origin`, an oversized body or a wrong bearer is refused, +//! and no response is a redirect. +//! +//! ``` +//! use std::sync::Arc; +//! use tinyhivemind_hives::{Coordinator, CoordinatorOptions, MemoryStorage}; +//! use tinyhivemind_mcp::{HiveToolServer, SeatTools, ServerOptions, Services}; +//! +//! # #[tokio::main(flavor = "current_thread")] +//! # async fn main() -> Result<(), Box> { +//! let coordinator = Coordinator::new( +//! "runtime".into(), +//! Arc::new(MemoryStorage::new()), +//! CoordinatorOptions::default(), +//! ) +//! .await?; +//! let server = HiveToolServer::start(Services::new(coordinator), ServerOptions::default()).await?; +//! let endpoint = server.serve_seat(SeatTools::new("scout"))?; +//! assert!(endpoint.url.starts_with("http://127.0.0.1:")); +//! assert!(endpoint.tools.contains("hivemind_post")); +//! // The bearer goes into the harness's private config, never a log. +//! assert!(!format!("{endpoint:?}").contains(endpoint.bearer())); +//! server.shutdown().await?; +//! # Ok(()) } +//! ``` +//! +//! What this crate does not hold: episode state, which is the coordinator's; +//! a harness, which a client crate starts and points at the endpoint; and a +//! proxy for a package's own MCP servers, so a seat declaring one is refused +//! by [`SeatTools::from_lowered`]. Nothing pure depends on it. +//! +//! [`ToolEndpoint`]: tinyhivemind_host::harness::ToolEndpoint +//! [`Approver`]: tinyhivemind_host::harness::Approver + +mod error; +mod seat; +mod server; +mod tools; + +pub use error::{Error, Result}; +pub use seat::SeatTools; +pub use server::{HiveToolServer, PROTOCOL_VERSIONS, ServerOptions, Services}; diff --git a/crates/tinyhivemind-mcp/src/seat/README.md b/crates/tinyhivemind-mcp/src/seat/README.md new file mode 100644 index 00000000..e4580afb --- /dev/null +++ b/crates/tinyhivemind-mcp/src/seat/README.md @@ -0,0 +1,18 @@ +# Seat + +`SeatTools` is what one seat is served beyond the hive tools: its executable +tools, its hooks and the context they run in, its access, and its permission +layers' tool names. `SeatTools::from_lowered` builds it from a package's +lowered seat; a non-empty `tools.allow` serves only the tools it names plus +the seat's executable tools, as on the linked path; access is the strictest of the runtime's `autonomy` and every +permission layer's `access`. It refuses a seat with package MCP servers (not +proxied yet), with any sandbox other than `none` (nothing confines a tool +here), a tool whose own `args` declare `turn` or `call`, and an argument +schema keyword the server cannot check. The bearer is overwritten when +dropped; copies in a `ToolEndpoint` are the host's. + +| File | Responsibility | +| --- | --- | +| `mod.rs` | `SeatTools`, its builders and checks | +| `bearer.rs` | A random 256-bit bearer, compared in constant time; `Debug` prints `redacted` | +| `test.rs` | Bearer generation, comparison and redaction | diff --git a/crates/tinyhivemind-mcp/src/seat/bearer.rs b/crates/tinyhivemind-mcp/src/seat/bearer.rs new file mode 100644 index 00000000..2c198735 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/seat/bearer.rs @@ -0,0 +1,47 @@ +//! A seat's random bearer, compared in constant time and never printed. +use crate::{Error, Result}; +use std::fmt::{self, Write as _}; +use subtle::ConstantTimeEq; + +/// 32 random bytes as 64 lowercase hex characters. +pub(crate) struct Bearer(String); + +impl Bearer { + /// A fresh bearer from the operating system's randomness. + pub(crate) fn generate() -> Result { + let mut bytes = [0_u8; 32]; + getrandom::fill(&mut bytes).map_err(|error| Error::Random(error.to_string()))?; + let mut text = String::with_capacity(64); + for byte in bytes { + let _ = write!(text, "{byte:02x}"); + } + Ok(Self(text)) + } + + /// Whether `presented` is this bearer, in time that does not depend on + /// where they differ. + pub(crate) fn matches(&self, presented: &[u8]) -> bool { + self.0.as_bytes().ct_eq(presented).into() + } + + /// The secret itself, for the seat's endpoint and nothing else. + pub(crate) fn expose(&self) -> &str { + &self.0 + } +} + +impl Drop for Bearer { + /// Overwrite the secret before its memory is freed. Copies handed out as + /// a `ToolEndpoint` are the host's to wipe. + fn drop(&mut self) { + let mut bytes = std::mem::take(&mut self.0).into_bytes(); + bytes.fill(0); + std::hint::black_box(&bytes); + } +} + +impl fmt::Debug for Bearer { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Bearer(redacted)") + } +} diff --git a/crates/tinyhivemind-mcp/src/seat/mod.rs b/crates/tinyhivemind-mcp/src/seat/mod.rs new file mode 100644 index 00000000..0c927d11 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/seat/mod.rs @@ -0,0 +1,218 @@ +//! What one seat is served: its executable tools, hooks and permissions. +//! +//! [`SeatTools`] is built by hand or from a package's lowered seat with +//! [`SeatTools::from_lowered`], which refuses what this server cannot +//! enforce rather than accepting it unenforced. +mod bearer; + +use crate::{Error, Result}; +pub(crate) use bearer::Bearer; +use tinyhivemind_exec::ExecContext; +use tinyhivemind_lang::{ + Access, ExecTool, LoweredHook, LoweredSeat, PermissionSet, RuntimeSettings, Sandbox, +}; + +/// The arguments the server adds to a state-changing tool's schema. +pub(crate) const RESERVED: [&str; 2] = ["turn", "call"]; + +/// One seat's tools beyond the hive vocabulary, and the policy over all of +/// them. +#[derive(Clone, Debug)] +pub struct SeatTools { + seat: String, + programs: Vec, + hooks: Vec, + context: ExecContext, + access: Access, + permissions: Vec, + denied: Vec, + allowed: Vec, +} + +impl SeatTools { + /// Seat `seat` with the hive tools only, under `supervised` access, the + /// language's default. + #[must_use] + pub fn new(seat: impl Into) -> Self { + let seat = seat.into(); + Self { + context: ExecContext { + seat: seat.clone(), + ..ExecContext::default() + }, + seat, + programs: Vec::new(), + hooks: Vec::new(), + access: Access::Supervised, + permissions: Vec::new(), + denied: Vec::new(), + allowed: Vec::new(), + } + } + + /// The seat a package lowered, on `runtime`, its tools running in + /// `context`. + /// + /// A non-empty `tools.allow` serves only the tools it names and the + /// seat's executable tools, as on the linked path. Access is the + /// strictest of the runtime's `autonomy` and every + /// permission layer's `access`. + /// + /// # Errors + /// [`Error::UnsupportedMcpServers`] for a seat with package MCP servers, + /// [`Error::UnsupportedSandbox`] for any sandbox but `none`, and + /// [`Error::ReservedArgument`] for a tool declaring `turn` or `call`, and + /// [`Error::UnsupportedSchema`] for an argument schema keyword the server + /// cannot check. + pub fn from_lowered( + seat: &LoweredSeat, + runtime: &RuntimeSettings, + context: ExecContext, + ) -> Result { + let integration = &seat.integration; + if !integration.mcp.is_empty() { + return Err(Error::UnsupportedMcpServers(seat.id.clone())); + } + let sandboxed = runtime.sandbox != Sandbox::None + || integration + .permissions + .iter() + .any(|set| set.sandbox != Sandbox::None); + if sandboxed { + return Err(Error::UnsupportedSandbox(seat.id.clone())); + } + let access = integration + .permissions + .iter() + .map(|set| set.access) + .min() + .unwrap_or(runtime.autonomy) + .min(runtime.autonomy); + let tools = Self { + seat: seat.id.clone(), + programs: integration.programs.clone(), + hooks: integration.hooks.clone(), + context, + access, + permissions: integration.permissions.clone(), + denied: integration.tools.deny.clone(), + allowed: integration.tools.allow.clone(), + }; + tools.check()?; + Ok(tools) + } + + /// Also serve `programs`. + #[must_use] + pub fn with_programs(mut self, programs: Vec) -> Self { + self.programs = programs; + self + } + + /// Run `hooks` around the seat's tool calls. + #[must_use] + pub fn with_hooks(mut self, hooks: Vec) -> Self { + self.hooks = hooks; + self + } + + /// Run programs and hooks in `context`. + #[must_use] + pub fn with_context(mut self, context: ExecContext) -> Self { + self.context = context; + self + } + + /// Serve only the tools `allowed` names, and the seat's executable tools; + /// empty serves every tool. + #[must_use] + pub fn with_allowed(mut self, allowed: Vec) -> Self { + self.allowed = allowed; + self + } + + /// Judge effectful programs under `access`. + #[must_use] + pub fn with_access(mut self, access: Access) -> Self { + self.access = access; + self + } + + /// Serve only what every one of `permissions` allows by name. + #[must_use] + pub fn with_permissions(mut self, permissions: Vec) -> Self { + self.permissions = permissions; + self + } + + /// The seat's coordinator id. + #[must_use] + pub fn seat(&self) -> &str { + &self.seat + } + + /// The access effectful programs are judged under. + #[must_use] + pub fn access(&self) -> Access { + self.access + } + + /// The executable tools' names, in declaration order. + #[must_use] + pub fn program_names(&self) -> Vec<&str> { + self.programs.iter().map(|tool| tool.id.as_str()).collect() + } + + pub(crate) fn programs(&self) -> &[ExecTool] { + &self.programs + } + + pub(crate) fn hooks(&self) -> &[LoweredHook] { + &self.hooks + } + + pub(crate) fn context(&self) -> &ExecContext { + &self.context + } + + /// Whether the seat's tool rules let `name` be served. + pub(crate) fn permits(&self, name: &str) -> bool { + let allowed = self.allowed.is_empty() + || self.allowed.iter().any(|tool| tool == name) + || self.programs.iter().any(|tool| tool.id == name); + allowed + && !self.denied.iter().any(|denied| denied == name) + && self.permissions.iter().all(|set| { + !set.deny_tools.iter().any(|denied| denied == name) + && set + .allow_tools + .as_ref() + .is_none_or(|allowed| allowed.iter().any(|tool| tool == name)) + }) + } + + /// Refuse a tool declaring an argument the server adds, or a schema + /// keyword it cannot check. + pub(crate) fn check(&self) -> Result<()> { + for tool in &self.programs { + if let Some(keyword) = crate::tools::unsupported(&tool.args) { + return Err(Error::UnsupportedSchema { + tool: tool.id.clone(), + keyword, + }); + } + for name in RESERVED { + if tool.args["properties"].get(name).is_some() { + return Err(Error::ReservedArgument { + tool: tool.id.clone(), + name: name.into(), + }); + } + } + } + Ok(()) + } +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-mcp/src/seat/test.rs b/crates/tinyhivemind-mcp/src/seat/test.rs new file mode 100644 index 00000000..58d82be5 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/seat/test.rs @@ -0,0 +1,21 @@ +//! Bearers: random, compared exactly, and never printed. +#![allow(clippy::expect_used)] +use super::Bearer; + +#[test] +fn a_bearer_is_64_hex_characters_and_matches_only_itself() { + let bearer = Bearer::generate().expect("randomness"); + let other = Bearer::generate().expect("randomness"); + assert_eq!(bearer.expose().len(), 64); + assert!(bearer.expose().bytes().all(|b| b.is_ascii_hexdigit())); + assert!(bearer.matches(bearer.expose().as_bytes())); + assert!(!bearer.matches(other.expose().as_bytes())); + assert!(!bearer.matches(&bearer.expose().as_bytes()[..63])); +} + +#[test] +fn a_bearer_debugs_as_redacted() { + let bearer = Bearer::generate().expect("randomness"); + let printed = format!("{bearer:?}"); + assert_eq!(printed, "Bearer(redacted)"); +} diff --git a/crates/tinyhivemind-mcp/src/server/README.md b/crates/tinyhivemind-mcp/src/server/README.md new file mode 100644 index 00000000..b16cad2d --- /dev/null +++ b/crates/tinyhivemind-mcp/src/server/README.md @@ -0,0 +1,30 @@ +# Server + +`HiveToolServer::start` binds 127.0.0.1 on a random port and serves HTTP/1.1 +(hyper 1, no framework) at `/mcp`. `serve_seat` draws a bearer and returns the +seat's `ToolEndpoint`; `withdraw_seat` refuses that bearer from then on; +`shutdown` stops accepting, lets open requests finish within +`ServerOptions::shutdown_grace`, and closes the listener. + +Bounds: `max_calls` calls in flight across seats and `max_calls_per_seat` per +seat, each held by the call's own task until it finishes, so a client that +hangs up does not free its slot early; a header read timeout (which also +closes idle and unauthenticated connections, so accepting needs no bound and +idle sockets cannot keep a seat waiting); a body timeout; `max_body_bytes`; +and `max_records` and `max_record_bytes` per seat's call records. A +background task drops the records of every turn that ends. + +Protocol: revisions `2025-11-25`, `2025-06-18` and `2025-03-26`. The spike's +harnesses asked for the first two (OpenHuman 0.64.15 and OpenClaw +`2025-11-25`, Codex 0.171 `2025-06-18`). One JSON-RPC message per POST, always +answered as `application/json`; batches are refused. Notifications and client +responses get 202 with no body. No `Mcp-Session-Id` is issued: the transport +makes sessions optional, the bearer already names the seat, and none of the +three harnesses needed one. A GET for the optional event stream, a DELETE or any +other method gets 405 with `Allow: POST`. + +| File | Responsibility | +| --- | --- | +| `mod.rs` | `HiveToolServer`, `Services`, `ServerOptions`, the accept loop | +| `http.rs` | Host, Origin, path, bearer, method, version header, body bound | +| `rpc.rs` | JSON-RPC framing and the MCP methods: initialize, ping, tools, empty resource and prompt lists | diff --git a/crates/tinyhivemind-mcp/src/server/http.rs b/crates/tinyhivemind-mcp/src/server/http.rs new file mode 100644 index 00000000..d45c80a2 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/server/http.rs @@ -0,0 +1,105 @@ +//! Admission of one HTTP request, before any JSON-RPC is read. +//! +//! In order: exactly one `Host` must name this listener (`127.0.0.1:` or +//! `localhost:`), any `Origin` is refused, the path must be `/mcp`, the +//! bearer must be a served seat's, the method must be POST (a GET for the +//! optional event stream gets 405, as the Streamable HTTP transport allows), +//! an `MCP-Protocol-Version` header must name a served revision, and the +//! body must fit [`super::ServerOptions::max_body_bytes`] and arrive within +//! its timeout. Nothing here ever answers with a redirect. +use super::rpc::{self, Answer}; +use super::{PROTOCOL_VERSIONS, Shared}; +use http_body_util::{BodyExt, Full, LengthLimitError, Limited}; +use hyper::body::{Bytes, Incoming}; +use hyper::header::{self, HeaderValue}; +use hyper::{Method, Request, Response, StatusCode}; +use std::convert::Infallible; +use std::sync::Arc; + +/// Answer `request`. +/// +/// # Errors +/// Never; every failure is an HTTP status. +pub(super) async fn handle( + shared: Arc, + request: Request, +) -> Result>, Infallible> { + Ok(admit(&shared, request).await) +} + +async fn admit(shared: &Arc, request: Request) -> Response> { + let headers = request.headers(); + let mut hosts = headers.get_all(header::HOST).iter(); + let host = hosts.next().and_then(|value| value.to_str().ok()); + let port = shared.port; + let own = [format!("127.0.0.1:{port}"), format!("localhost:{port}")]; + let named = host.is_some_and(|host| own.iter().any(|own| own == host)); + if !named || hosts.next().is_some() { + return status(StatusCode::FORBIDDEN); + } + if headers.contains_key(header::ORIGIN) { + return status(StatusCode::FORBIDDEN); + } + if request.uri().path() != "/mcp" { + return status(StatusCode::NOT_FOUND); + } + let presented = headers + .get(header::AUTHORIZATION) + .and_then(|value| value.as_bytes().strip_prefix(b"Bearer ")); + let Some(seat) = presented.and_then(|bearer| shared.seat(bearer)) else { + let mut refused = status(StatusCode::UNAUTHORIZED); + refused + .headers_mut() + .insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer")); + return refused; + }; + if request.method() != Method::POST { + let mut refused = status(StatusCode::METHOD_NOT_ALLOWED); + refused + .headers_mut() + .insert(header::ALLOW, HeaderValue::from_static("POST")); + return refused; + } + let version = headers + .get("mcp-protocol-version") + .map(HeaderValue::as_bytes); + if version.is_some_and(|version| !PROTOCOL_VERSIONS.iter().any(|v| v.as_bytes() == version)) { + return status(StatusCode::BAD_REQUEST); + } + let limit = shared.options.max_body_bytes; + let declared = headers + .get(header::CONTENT_LENGTH) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.parse::().ok()); + if declared.is_some_and(|length| length > limit) { + return status(StatusCode::PAYLOAD_TOO_LARGE); + } + let body = Limited::new(request.into_body(), limit).collect(); + let bytes = match tokio::time::timeout(shared.options.body_timeout, body).await { + Err(_) => return status(StatusCode::REQUEST_TIMEOUT), + Ok(Err(error)) if error.downcast_ref::().is_some() => { + return status(StatusCode::PAYLOAD_TOO_LARGE); + } + Ok(Err(_)) => return status(StatusCode::BAD_REQUEST), + Ok(Ok(collected)) => collected.to_bytes(), + }; + match rpc::answer(shared, seat, &bytes).await { + Answer::Accepted => status(StatusCode::ACCEPTED), + Answer::Reply(code, message) => { + let mut response = Response::new(Full::new(Bytes::from(message.to_string()))); + *response.status_mut() = code; + response.headers_mut().insert( + header::CONTENT_TYPE, + HeaderValue::from_static("application/json"), + ); + response + } + } +} + +/// An empty response with `code`. +fn status(code: StatusCode) -> Response> { + let mut response = Response::new(Full::new(Bytes::new())); + *response.status_mut() = code; + response +} diff --git a/crates/tinyhivemind-mcp/src/server/mod.rs b/crates/tinyhivemind-mcp/src/server/mod.rs new file mode 100644 index 00000000..36710482 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/server/mod.rs @@ -0,0 +1,376 @@ +//! The listener: one server per host, every seat behind its own bearer. +//! +//! [`HiveToolServer::start`] binds a random port of 127.0.0.1 and serves +//! HTTP/1.1 at `/mcp`. Each [`HiveToolServer::serve_seat`] draws a fresh +//! bearer and returns the seat's [`ToolEndpoint`]. Calls in flight are +//! bounded across seats and per seat, and a call keeps its place until it +//! finishes, even when its client hung up; connections are not bounded, but +//! an idle one is closed after the header timeout. [`HiveToolServer::shutdown`] stops accepting, lets the +//! open requests finish within a grace period, and returns. +mod http; +mod rpc; + +use crate::seat::{Bearer, SeatTools}; +use crate::tools::{Ledger, SeatState}; +use crate::{Error, Result}; +use hyper::server::conn::http1; +use hyper::service::service_fn; +use hyper_util::rt::{TokioIo, TokioTimer}; +use hyper_util::server::graceful::GracefulShutdown; +use std::fmt; +use std::net::{Ipv4Addr, SocketAddr}; +use std::sync::{Arc, PoisonError, RwLock}; +use std::time::Duration; +use tinyhivemind_exec::{EnvSecrets, Secrets}; +use tinyhivemind_hives::Coordinator; +use tinyhivemind_host::harness::{Approver, ToolEndpoint}; +use tinyhivemind_host::policy::{AgentCreator, Management, ManagementAuthorizer, SendAuthorizer}; +use tinyhivemind_host::tools::Belt; +use tokio::net::TcpListener; +use tokio::sync::{Semaphore, watch}; +use tokio::task::JoinHandle; + +/// The MCP protocol revisions served, newest first. In the harness spike +/// `Codex` 0.171 asked for `2025-06-18`, and `OpenHuman` 0.64.15 and +/// `OpenClaw` for `2025-11-25`; an initialize asking for anything else is +/// answered with the newest. +pub const PROTOCOL_VERSIONS: [&str; 3] = ["2025-11-25", "2025-06-18", "2025-03-26"]; + +/// What the server dispatches through: the coordinator and the host's ports. +#[derive(Clone)] +pub struct Services { + pub(crate) coordinator: Coordinator, + send_policy: Option>, + management: Option<(Arc, Arc)>, + pub(crate) approver: Option>, + pub(crate) secrets: Arc, +} + +impl Services { + /// Dispatch to `coordinator`, admitting every send, managing nothing, + /// approving nothing, and resolving secrets from this process's + /// environment. + #[must_use] + pub fn new(coordinator: Coordinator) -> Self { + Self { + coordinator, + send_policy: None, + management: None, + approver: None, + secrets: Arc::new(EnvSecrets), + } + } + + /// Gate the outbound hive tools behind `policy`. + #[must_use] + pub fn with_send_policy(mut self, policy: Arc) -> Self { + self.send_policy = Some(policy); + self + } + + /// Serve the management tools, authorized by `authorizer`, agents built + /// by `creator`. + #[must_use] + pub fn with_management( + mut self, + authorizer: Arc, + creator: Arc, + ) -> Self { + self.management = Some((authorizer, creator)); + self + } + + /// Ask `approver` about effectful executable tools of supervised seats. + /// Without one, every such call is refused. + #[must_use] + pub fn with_approver(mut self, approver: Arc) -> Self { + self.approver = Some(approver); + self + } + + /// Resolve the `env` references of tools and hooks through `secrets`. + #[must_use] + pub fn with_secrets(mut self, secrets: Arc) -> Self { + self.secrets = secrets; + self + } + + /// The belt every hive tool call goes through. + pub(crate) fn belt(&self) -> Belt<'_> { + let mut belt = Belt::new(&self.coordinator); + if let Some(policy) = &self.send_policy { + belt = belt.with_send_policy(policy.as_ref()); + } + if let Some((authorizer, creator)) = &self.management { + belt = belt.with_management(Management { + authorizer: authorizer.as_ref(), + creator: creator.as_ref(), + }); + } + belt + } +} + +impl fmt::Debug for Services { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Services") + .field("coordinator", &self.coordinator) + .field("send_policy", &self.send_policy.is_some()) + .field("management", &self.management.is_some()) + .field("approver", &self.approver.is_some()) + .finish_non_exhaustive() + } +} + +/// Bounds and names of a server. +#[derive(Clone, Debug)] +pub struct ServerOptions { + /// The server's name, which harnesses put in its tools' names. + pub name: String, + /// Largest request body accepted; a larger one gets 413. + pub max_body_bytes: usize, + /// Most tool calls running at once, across seats; nonzero. A call holds + /// its place until it finishes, even when its client has hung up. + pub max_calls: usize, + /// Most tool calls one seat may have running at once; nonzero. + pub max_calls_per_seat: usize, + /// Most call records one seat's running turn may hold. + pub max_records: usize, + /// Most bytes of arguments and results those records may hold. + pub max_record_bytes: usize, + /// Longest a connection may take to send a request's headers, which is + /// also how long an idle or unauthenticated connection is kept. + pub header_timeout: Duration, + /// Longest a request may take to send its body. + pub body_timeout: Duration, + /// Longest shutdown waits for open requests. + pub shutdown_grace: Duration, +} + +impl Default for ServerOptions { + fn default() -> Self { + Self { + name: "hivemind".into(), + max_body_bytes: 1 << 20, + max_calls: 32, + max_calls_per_seat: 4, + max_records: 256, + max_record_bytes: 1 << 20, + header_timeout: Duration::from_secs(5), + body_timeout: Duration::from_secs(30), + shutdown_grace: Duration::from_secs(5), + } + } +} + +/// What every connection shares. +#[derive(Debug)] +pub(crate) struct Shared { + pub(crate) services: Services, + pub(crate) options: ServerOptions, + pub(crate) port: u16, + seats: RwLock>>, + pub(crate) ledger: Ledger, + /// Calls in flight, across seats. + pub(crate) calls: Arc, +} + +impl Shared { + /// The seat whose bearer is `presented`. Every seat is compared, so the + /// time taken says nothing about which one matched. + pub(crate) fn seat(&self, presented: &[u8]) -> Option> { + let seats = self.seats.read().unwrap_or_else(PoisonError::into_inner); + let mut found = None; + for seat in seats.iter() { + if seat.bearer.matches(presented) { + found = Some(seat.clone()); + } + } + found + } +} + +/// The loopback MCP server. +pub struct HiveToolServer { + shared: Arc, + addr: SocketAddr, + stop: watch::Sender, + task: JoinHandle<()>, + purge: JoinHandle<()>, +} + +impl HiveToolServer { + /// Bind a random port of 127.0.0.1 and start serving. + /// + /// # Errors + /// [`Error::Listen`] when the listener cannot be opened. + pub async fn start(services: Services, options: ServerOptions) -> Result { + let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)) + .await + .map_err(Error::Listen)?; + let addr = listener.local_addr().map_err(Error::Listen)?; + let shared = Arc::new(Shared { + services, + port: addr.port(), + seats: RwLock::default(), + ledger: Ledger::new(options.max_records, options.max_record_bytes), + calls: Arc::new(Semaphore::new(options.max_calls.max(1))), + options, + }); + let (stop, stopped) = watch::channel(false); + let task = tokio::spawn(serve(listener, shared.clone(), stopped.clone())); + let purge = tokio::spawn(purge_ended(shared.clone(), stopped)); + Ok(Self { + shared, + addr, + stop, + task, + purge, + }) + } + + /// Where the server listens. + #[must_use] + pub fn local_addr(&self) -> SocketAddr { + self.addr + } + + /// The URL every seat is served at. + #[must_use] + pub fn url(&self) -> String { + format!("http://{}/mcp", self.addr) + } + + /// Serve `seat` behind a fresh bearer, and return its endpoint. + /// + /// # Errors + /// [`Error::DuplicateSeat`], [`Error::DuplicateTool`], + /// [`Error::ReservedArgument`] or [`Error::Random`]. + pub fn serve_seat(&self, seat: SeatTools) -> Result { + let managed = self.shared.services.management.is_some(); + let per_seat = self.shared.options.max_calls_per_seat; + let bearer = Bearer::generate()?; + let state = SeatState::new(seat, bearer, managed, &self.shared.services, per_seat)?; + let mut seats = self + .shared + .seats + .write() + .unwrap_or_else(PoisonError::into_inner); + let id = state.tools.seat().to_owned(); + if seats.iter().any(|served| served.tools.seat() == id) { + return Err(Error::DuplicateSeat(id)); + } + let endpoint = ToolEndpoint::new( + self.shared.options.name.clone(), + self.url(), + state.bearer.expose(), + state.catalog.names(), + ); + seats.push(Arc::new(state)); + Ok(endpoint) + } + + /// Stop serving the seat with this id; its bearer is refused from now + /// on. Whether it was served. + pub fn withdraw_seat(&self, seat_id: &str) -> bool { + let mut seats = self + .shared + .seats + .write() + .unwrap_or_else(PoisonError::into_inner); + let before = seats.len(); + seats.retain(|served| served.tools.seat() != seat_id); + drop(seats); + self.shared.ledger.forget(seat_id); + before + != self + .shared + .seats + .read() + .unwrap_or_else(PoisonError::into_inner) + .len() + } + + /// Stop accepting, let open requests finish within the grace period, and + /// close the listener. + /// + /// # Errors + /// [`Error::Stopped`] when the server task panicked. + pub async fn shutdown(mut self) -> Result<()> { + let _ = self.stop.send(true); + let purged = (&mut self.purge).await; + let served = (&mut self.task).await; + served + .and(purged) + .map_err(|error| Error::Stopped(error.to_string())) + } +} + +impl Drop for HiveToolServer { + fn drop(&mut self) { + let _ = self.stop.send(true); + } +} + +impl fmt::Debug for HiveToolServer { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let seats = self + .shared + .seats + .read() + .unwrap_or_else(PoisonError::into_inner); + let ids: Vec<&str> = seats.iter().map(|seat| seat.tools.seat()).collect(); + f.debug_struct("HiveToolServer") + .field("addr", &self.addr) + .field("seats", &ids) + .finish_non_exhaustive() + } +} + +/// Accept connections until told to stop, then wind them down. +/// +/// Accepting is not bounded: an idle or unauthenticated connection is closed +/// after [`ServerOptions::header_timeout`] and holds no call slot, so it +/// cannot keep a seat waiting. What is bounded is calls in flight. +async fn serve(listener: TcpListener, shared: Arc, mut stopped: watch::Receiver) { + let graceful = GracefulShutdown::new(); + loop { + let stream = tokio::select! { + _ = stopped.wait_for(|stop| *stop) => break, + accepted = listener.accept() => match accepted { + Ok((stream, _)) => stream, + Err(_) => continue, + }, + }; + let handler = shared.clone(); + let service = service_fn(move |request| http::handle(handler.clone(), request)); + let connection = http1::Builder::new() + .timer(TokioTimer::new()) + .header_read_timeout(shared.options.header_timeout) + .serve_connection(TokioIo::new(stream), service); + let connection = graceful.watch(connection); + tokio::spawn(connection); + } + drop(listener); + let _ = tokio::time::timeout(shared.options.shutdown_grace, graceful.shutdown()).await; +} + +/// Drop the call records of every turn that has ended, as the coordinator +/// commits. +async fn purge_ended(shared: Arc, mut stopped: watch::Receiver) { + let coordinator = shared.services.coordinator.clone(); + let mut revisions = coordinator.subscribe(); + loop { + tokio::select! { + _ = stopped.wait_for(|stop| *stop) => break, + changed = revisions.changed() => { + if changed.is_err() { + break; + } + shared + .ledger + .purge(|seat| coordinator.running_turn(seat).ok().flatten()); + } + } + } +} diff --git a/crates/tinyhivemind-mcp/src/server/rpc.rs b/crates/tinyhivemind-mcp/src/server/rpc.rs new file mode 100644 index 00000000..848d14fa --- /dev/null +++ b/crates/tinyhivemind-mcp/src/server/rpc.rs @@ -0,0 +1,140 @@ +//! JSON-RPC 2.0 and the MCP methods a tools-only server answers. +//! +//! One message per POST; a batch is refused. A notification or a response +//! from the client is accepted with no body. No session id is issued: the +//! bearer already names the seat, and none of the three harnesses needed one. +use super::{PROTOCOL_VERSIONS, Shared}; +use crate::tools::{self, SeatState}; +use hyper::StatusCode; +use serde_json::{Value, json}; +use std::sync::Arc; + +/// What a POST is answered with. +#[derive(Debug)] +pub(super) enum Answer { + /// 202, no body. + Accepted, + /// A JSON-RPC message with this status. + Reply(StatusCode, Value), +} + +const PARSE_ERROR: i64 = -32700; +const INVALID_REQUEST: i64 = -32600; +const METHOD_NOT_FOUND: i64 = -32601; +const INVALID_PARAMS: i64 = -32602; +const INTERNAL_ERROR: i64 = -32603; + +/// Answer the JSON-RPC message in `body` as `seat`. +pub(super) async fn answer(shared: &Arc, seat: Arc, body: &[u8]) -> Answer { + let Ok(message) = serde_json::from_slice::(body) else { + return Answer::Reply( + StatusCode::BAD_REQUEST, + error(&Value::Null, PARSE_ERROR, "parse error"), + ); + }; + if message.is_array() { + let refused = error(&Value::Null, INVALID_REQUEST, "batches are not supported"); + return Answer::Reply(StatusCode::BAD_REQUEST, refused); + } + let id = message.get("id").cloned(); + let replied = message.get("result").is_some() || message.get("error").is_some(); + let invalid = |id: Option<&Value>| { + let id = id.unwrap_or(&Value::Null); + Answer::Reply( + StatusCode::BAD_REQUEST, + error(id, INVALID_REQUEST, "invalid request"), + ) + }; + if message.get("jsonrpc").and_then(Value::as_str) != Some("2.0") { + return invalid(id.as_ref()); + } + match (message.get("method").and_then(Value::as_str), id) { + (Some(method), Some(id)) => { + let params = message.get("params").cloned().unwrap_or(Value::Null); + let reply = match request(shared, seat, method, params).await { + Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}), + Err((code, text)) => error(&id, code, &text), + }; + Answer::Reply(StatusCode::OK, reply) + } + // A notification, or the client's answer to a request: nothing to say. + (Some(_), None) => Answer::Accepted, + (None, Some(_)) if replied => Answer::Accepted, + (None, id) => invalid(id.as_ref()), + } +} + +async fn request( + shared: &Arc, + seat: Arc, + method: &str, + params: Value, +) -> Result { + Ok(match method { + "initialize" => { + let asked = params["protocolVersion"].as_str(); + let version = PROTOCOL_VERSIONS + .iter() + .find(|version| Some(**version) == asked) + .unwrap_or(&PROTOCOL_VERSIONS[0]); + json!({ + "protocolVersion": version, + "capabilities": {"tools": {"listChanged": false}}, + "serverInfo": {"name": shared.options.name, "version": env!("CARGO_PKG_VERSION")}, + }) + } + "ping" => json!({}), + "tools/list" => json!({"tools": seat.catalog.listing()}), + "tools/call" => return call(shared, seat, params).await, + "resources/list" => json!({"resources": []}), + "resources/templates/list" => json!({"resourceTemplates": []}), + "prompts/list" => json!({"prompts": []}), + other => return Err((METHOD_NOT_FOUND, format!("method {other} is not served"))), + }) +} + +/// Run a `tools/call` on its own task, so that a client hanging up does not +/// cancel a call halfway and leave its outcome unknown. +async fn call( + shared: &Arc, + seat: Arc, + params: Value, +) -> Result { + let Some(name) = params["name"].as_str().map(str::to_owned) else { + return Err((INVALID_PARAMS, "tools/call needs a tool name".into())); + }; + let arguments = params.get("arguments").cloned().unwrap_or(Value::Null); + // The seat's own slot first, so a seat at its bound holds no shared one. + // Both are held by the call's task, so they are released when the call + // ends, not when its client hangs up. + let stopping = || (INTERNAL_ERROR, "the server is stopping".to_owned()); + let own = seat + .calls + .clone() + .acquire_owned() + .await + .map_err(|_| stopping())?; + let shared_slot = shared + .calls + .clone() + .acquire_owned() + .await + .map_err(|_| stopping())?; + let shared = shared.clone(); + let task = tokio::spawn(async move { + let _slots = (own, shared_slot); + tools::call(&shared.services, &shared.ledger, &seat, &name, arguments).await + }); + match task.await { + Ok(Ok(outcome)) => Ok(json!({ + "content": [{"type": "text", "text": outcome.text}], + "isError": outcome.is_error, + })), + Ok(Err(unknown)) => Err((INVALID_PARAMS, format!("unknown tool {}", unknown.0))), + Err(_) => Err((INTERNAL_ERROR, "the call failed".into())), + } +} + +fn error(id: &Value, code: i64, message: &str) -> Value { + json!({"jsonrpc": "2.0", "id": id, "error": {"code": code, "message": message}}) +} diff --git a/crates/tinyhivemind-mcp/src/tools/README.md b/crates/tinyhivemind-mcp/src/tools/README.md new file mode 100644 index 00000000..3e7b8f3c --- /dev/null +++ b/crates/tinyhivemind-mcp/src/tools/README.md @@ -0,0 +1,38 @@ +# Tools + +The catalog of one seat, and the path of one `tools/call`. + +A tool changes state unless it is a list or read hive tool or a program +declared `side_effects = "read"`, and any tool a `pre_tool_use` or +`post_tool_use` hook matches changes state too, reads included. Such a tool's +schema gets the required `turn` and `call`, which dispatch removes before +anything else sees the arguments. + +A call then goes: turn check (refused unless it is the seat's running turn), +argument validation (a hive tool's declaration, or a program's `args` schema), +and one of two records. + +- A coordinator action with no matching hook goes to the host's belt as an + identified call; the coordinator records it in the transaction of its effect. +- Everything else (executable tools, `create_agent`, any hooked call) uses the + in-memory `Ledger`: a known call is answered from it, or refused while its + outcome is unknown or when its `call` was used for something else; then the + host's send and management policy (`Belt::authorize`) for a hive tool; then + "started" is recorded, only if the coordinator still says the turn is + running; then the access gate for a program (a denial drops the record); + then the turn is checked again, the hooks and tool run, and + "finished" is recorded. A hooked coordinator action has both records. + +A refusal before any hook runs records nothing. The belt checks send and +management policy again at dispatch, so a policy that changes in between is +judged by that second check. Each call runs on its own task, +so a client that hangs up does not cancel it halfway. + +| File | Responsibility | +| --- | --- | +| `mod.rs` | `Catalog`: what is served, under which schema | +| `dispatch.rs` | One call, from arguments to result | +| `ledger.rs` | Started and finished records of out-of-transaction calls | +| `gate.rs` | `read_only`, `supervised` with the host's approver, `autonomous` | +| `schema.rs` | Executable tool arguments checked against their declared `args` | +| `test.rs` | Ledger turn rules and bounds; the schema checker | diff --git a/crates/tinyhivemind-mcp/src/tools/dispatch.rs b/crates/tinyhivemind-mcp/src/tools/dispatch.rs new file mode 100644 index 00000000..831c3469 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/tools/dispatch.rs @@ -0,0 +1,307 @@ +//! One `tools/call`, from the model's arguments to the result it reads. +//! +//! In order: find the tool; for a state-changing one take `turn` and `call` +//! out of the arguments and refuse unless `turn` is the seat's running turn; +//! validate; then either hand a coordinator action with no hook to the belt +//! as an identified call, whose record the coordinator writes with the +//! effect, or go through the [`Ledger`]: answer a known call, judge the +//! host's send and management policy (hive tools) or the access gate +//! (programs), record the start, run the `pre_tool_use` hooks, run the +//! tool, run the `post_tool_use` hooks, record the finish. A call refused by +//! validation or policy before any hook runs records nothing. +use super::ledger::{Identity, Known, Ledger, Outcome}; +use super::{Catalog, Served, Target}; +use super::{gate, schema}; +use crate::seat::{Bearer, SeatTools}; +use crate::server::Services; +use serde_json::{Map, Value}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, PoisonError}; +use tinyhivemind_exec::{HookRunner, Verdict}; +use tinyhivemind_host::harness::ToolApproval; +use tinyhivemind_host::tools::{Kind, ToolCall}; +use tinyhivemind_lang::SideEffects; +use tokio::sync::Semaphore; + +/// The note appended to a result whose stdout passed 1 MiB. +const TRUNCATED: &str = "\n[output truncated at 1 MiB]"; + +/// The model named a tool its seat is not served. +#[derive(Clone, Debug)] +pub(crate) struct UnknownTool(pub(crate) String); + +/// A served seat: its bearer, its tools, and what runs them. +#[derive(Debug)] +pub(crate) struct SeatState { + pub(crate) tools: SeatTools, + pub(crate) bearer: Bearer, + pub(crate) catalog: Catalog, + hooks: HookRunner, + /// Runs of each executable tool, for `THM_CALL_ID`. + runs: Mutex>, + /// Calls of this seat in flight. + pub(crate) calls: Arc, +} + +impl SeatState { + pub(crate) fn new( + tools: SeatTools, + bearer: Bearer, + managed: bool, + services: &Services, + max_calls: usize, + ) -> crate::Result { + tools.check()?; + let hooks = HookRunner::new( + tools.hooks().to_vec(), + Arc::new(tools.context().clone()), + services.secrets.clone(), + ); + let catalog = Catalog::build(&tools, &hooks, managed)?; + Ok(Self { + tools, + bearer, + catalog, + hooks, + runs: Mutex::default(), + calls: Arc::new(Semaphore::new(max_calls.max(1))), + }) + } + + fn id(&self) -> &str { + self.tools.seat() + } + + fn next_run(&self, tool: &str) -> String { + let mut runs = self.runs.lock().unwrap_or_else(PoisonError::into_inner); + let run = runs.entry(tool.to_owned()).or_default(); + *run += 1; + format!("{tool}-{run}") + } +} + +/// Carry out one call of `name` with `arguments` as `seat`. +/// +/// # Errors +/// [`UnknownTool`] when the seat is not served `name`; every other refusal is +/// an error [`Outcome`]. +pub(crate) async fn call( + services: &Services, + ledger: &Ledger, + seat: &SeatState, + name: &str, + arguments: Value, +) -> Result { + let tool = seat + .catalog + .find(name) + .ok_or_else(|| UnknownTool(name.to_owned()))?; + let mut arguments = match arguments { + Value::Null => Value::Object(Map::new()), + other => other, + }; + let Some(object) = arguments.as_object_mut() else { + return Ok(Outcome::refused("arguments must be an object")); + }; + if !tool.changes_state { + if let Err(refusal) = validated(tool, &arguments) { + return Ok(refusal); + } + return Ok(run(services, seat, tool, &arguments, None).await); + } + let Some(turn) = take_text(object, "turn") else { + return Ok(Outcome::refused( + "missing argument turn: name your running turn", + )); + }; + let Some(call) = take_text(object, "call").filter(|call| !call.trim().is_empty()) else { + return Ok(Outcome::refused( + "missing argument call: name this action, uniquely within the turn", + )); + }; + let identity = Identity { + seat: seat.id().to_owned(), + turn, + call, + }; + if let Err(refusal) = running(services, &identity).and_then(|()| validated(tool, &arguments)) { + return Ok(refusal); + } + let in_transaction = matches!(tool.target, Target::Hive(kind) if kind != Kind::CreateAgent); + if in_transaction && !tool.hooked { + return Ok(run(services, seat, tool, &arguments, Some(&identity)).await); + } + if let Some(answer) = answered(ledger.lookup(&identity, name, &arguments), &identity) { + return Ok(answer); + } + if let Target::Hive(kind) = tool.target + && let Err(refusal) = authorized(services, seat, kind, &arguments) + { + return Ok(refusal); + } + let running_turn = || services.coordinator.running_turn(seat.id()).ok().flatten(); + let started = ledger.start(&identity, name, &arguments, running_turn); + if let Some(answer) = answered(started, &identity) { + return Ok(answer); + } + // Recorded as pending before the approver is asked, so a retry while it + // decides is refused rather than asking twice. A refusal here ran + // nothing, so it records nothing. + if let Target::Program(program) = &tool.target + && program.side_effects != SideEffects::Read + { + let request = ToolApproval { + seat: identity.seat.clone(), + turn_id: identity.turn.clone(), + call_id: identity.call.clone(), + tool: name.to_owned(), + arguments: arguments.clone(), + }; + let approver = services.approver.as_ref(); + if let Err(refusal) = gate::admit(seat.tools.access(), approver, request).await { + ledger.abandon(&identity); + return Ok(Outcome::refused(refusal)); + } + } + // The approver may have taken long enough for the turn to end. + if let Err(refusal) = running(services, &identity) { + ledger.abandon(&identity); + return Ok(refusal); + } + let outcome = if tool.hooked { + match seat.hooks.pre_tool_use(name, &arguments).await { + Verdict::Deny(message) => Outcome::refused(message), + Verdict::Allow => { + let outcome = run_in_turn(services, seat, tool, &arguments, &identity).await; + seat.hooks + .post_tool_use(name, &arguments, &outcome.text) + .await; + outcome + } + } + } else { + run_in_turn(services, seat, tool, &arguments, &identity).await + }; + ledger.finish(&identity, outcome.clone()); + Ok(outcome) +} + +/// Run `tool` as `identity` if its turn is still running, which hooks may +/// have outlasted. +async fn run_in_turn( + services: &Services, + seat: &SeatState, + tool: &Served, + arguments: &Value, + identity: &Identity, +) -> Outcome { + match running(services, identity) { + Ok(()) => run(services, seat, tool, arguments, Some(identity)).await, + Err(refusal) => refusal, + } +} + +/// Refuse a call whose turn is not the seat's running turn. +fn running(services: &Services, identity: &Identity) -> Result<(), Outcome> { + match services.coordinator.running_turn(&identity.seat) { + Ok(Some(running)) if running == identity.turn => Ok(()), + Ok(_) => Err(stale(identity)), + Err(error) => Err(Outcome::refused(error.to_string())), + } +} + +fn stale(identity: &Identity) -> Outcome { + let stale = tinyhivemind_hives::Error::StaleTurn { + agent_id: identity.seat.clone(), + turn_id: identity.turn.clone(), + }; + Outcome::refused(stale.to_string()) +} + +/// Refuse arguments that do not fit the tool's declaration. +fn validated(tool: &Served, arguments: &Value) -> Result<(), Outcome> { + match &tool.target { + Target::Hive(kind) => kind.validate(arguments).map_err(|error| error.to_string()), + Target::Program(program) => schema::check(&program.args, arguments, ""), + } + .map_err(Outcome::refused) +} + +/// Refuse a hive call the host's send or management policy refuses, before +/// any hook runs. The belt checks again as it dispatches. +fn authorized( + services: &Services, + seat: &SeatState, + kind: Kind, + arguments: &Value, +) -> Result<(), Outcome> { + let call = ToolCall::new(seat.id(), None, kind, arguments.clone()) + .map_err(|error| Outcome::refused(error.to_string()))?; + services + .belt() + .authorize(&call) + .map_err(|error| Outcome::refused(error.to_string())) +} + +/// The answer the ledger already has for a call, if any. +fn answered(known: Known, identity: &Identity) -> Option { + match known { + Known::New => None, + Known::Answered(outcome) => Some(outcome), + Known::Running => Some(Outcome::refused(format!( + "call {} has started and its outcome is not known; use a new call only to act again", + identity.call + ))), + Known::Reused => Some(Outcome::refused( + tinyhivemind_hives::Error::CallReused(identity.call.clone()).to_string(), + )), + Known::Stale => Some(stale(identity)), + Known::Full => Some(Outcome::refused(format!( + "call {} is refused: this turn already holds as many call records as the server keeps", + identity.call + ))), + } +} + +/// Run `tool` itself, identified as `identity` when given. +async fn run( + services: &Services, + seat: &SeatState, + tool: &Served, + arguments: &Value, + identity: Option<&Identity>, +) -> Outcome { + match &tool.target { + Target::Hive(kind) => { + let call = match ToolCall::new(seat.id(), None, *kind, arguments.clone()) { + Ok(call) => call, + Err(error) => return Outcome::refused(error.to_string()), + }; + let call = match identity { + Some(identity) => call.in_turn(&identity.turn, &identity.call), + None => call, + }; + match services.belt().call(&call).await { + Ok(value) => Outcome::success(value.to_string()), + Err(error) => Outcome::refused(error.to_string()), + } + } + Target::Program(program) => { + let run_id = seat.next_run(&program.id); + let context = seat.tools.context(); + let secrets = services.secrets.as_ref(); + match tinyhivemind_exec::run(program, context, secrets, arguments, &run_id).await { + Ok(output) if output.truncated => Outcome::success(output.text + TRUNCATED), + Ok(output) => Outcome::success(output.text), + Err(error) => Outcome::refused(error.to_string()), + } + } + } +} + +fn take_text(object: &mut Map, name: &str) -> Option { + match object.remove(name) { + Some(Value::String(text)) => Some(text), + _ => None, + } +} diff --git a/crates/tinyhivemind-mcp/src/tools/gate.rs b/crates/tinyhivemind-mcp/src/tools/gate.rs new file mode 100644 index 00000000..92346ed4 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/tools/gate.rs @@ -0,0 +1,39 @@ +//! The `autonomy` and `access` gate, judged before hooks and dispatch. +//! +//! It covers executable tools not declared `side_effects = "read"`. Hive +//! tools stay under send and management policy instead, as on the linked +//! path, and a harness's own approval prompts are never relied on. +use std::sync::Arc; +use tinyhivemind_host::harness::{Approver, ToolApproval, ToolDecision}; +use tinyhivemind_lang::Access; + +/// Admit `request` under `access`, asking `approver` when supervised. +/// +/// # Errors +/// The refusal the model reads: `read_only` refuses outright, `supervised` +/// refuses without an approver or on its denial. +pub(crate) async fn admit( + access: Access, + approver: Option<&Arc>, + request: ToolApproval, +) -> Result<(), String> { + match access { + Access::Autonomous => Ok(()), + Access::ReadOnly => Err(format!( + "access read_only refuses {}, which may change state", + request.tool + )), + Access::Supervised => { + let Some(approver) = approver else { + return Err(format!( + "supervised seat {} has no approver for {}", + request.seat, request.tool + )); + }; + match approver.decide(request).await { + ToolDecision::Allow => Ok(()), + ToolDecision::Deny { reason } => Err(reason), + } + } + } +} diff --git a/crates/tinyhivemind-mcp/src/tools/ledger.rs b/crates/tinyhivemind-mcp/src/tools/ledger.rs new file mode 100644 index 00000000..14bb052f --- /dev/null +++ b/crates/tinyhivemind-mcp/src/tools/ledger.rs @@ -0,0 +1,213 @@ +//! The in-memory started and finished records of calls that act outside the +//! coordinator's transaction: executable tools, `create_agent`, and every +//! call a hook matches. +//! +//! Each seat keeps the records of one turn: its running one. A call is +//! recorded only after the coordinator confirms, inside the ledger's lock, +//! that the call's turn is the seat's running turn, so a call that was held +//! (by an approver, a hook) while its turn ended can neither run nor replace +//! the newer turn's records. Records of a turn that is no longer running are +//! dropped by [`Ledger::purge`], and a withdrawn seat's by [`Ledger::forget`]. +//! A seat's records are bounded in count and bytes, and a call past either +//! bound is refused, never recorded by evicting another. The records are +//! this process's alone: at most once holds within one server process. +use serde_json::Value; +use std::collections::HashMap; +use std::sync::{Mutex, PoisonError}; + +/// What a call returned to the model. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) struct Outcome { + /// The tool result's text. + pub(crate) text: String, + /// Whether it is an error result. + pub(crate) is_error: bool, +} + +impl Outcome { + /// A result. + pub(crate) fn success(text: impl Into) -> Self { + Self { + text: text.into(), + is_error: false, + } + } + + /// A refusal or failure the model reads. + pub(crate) fn refused(text: impl Into) -> Self { + Self { + text: text.into(), + is_error: true, + } + } +} + +/// (seat, turn, call). +#[derive(Clone, Debug)] +pub(crate) struct Identity { + pub(crate) seat: String, + pub(crate) turn: String, + pub(crate) call: String, +} + +/// What the ledger knows of a call. +#[derive(Clone, Debug, Eq, PartialEq)] +pub(crate) enum Known { + /// Nothing: it may act. + New, + /// It finished with this outcome. + Answered(Outcome), + /// It started and has not finished, or never will. + Running, + /// Its `call` was used for another tool or other arguments. + Reused, + /// Its turn is not the seat's running turn. + Stale, + /// The seat's records are at their bound. + Full, +} + +#[derive(Debug)] +struct Entry { + tool: String, + arguments: Value, + outcome: Option, + bytes: usize, +} + +#[derive(Debug, Default)] +struct Records { + turn: String, + calls: HashMap, + bytes: usize, +} + +/// Every seat's records for its running turn. +#[derive(Debug)] +pub(crate) struct Ledger { + seats: Mutex>, + max_records: usize, + max_bytes: usize, +} + +impl Ledger { + /// A ledger holding at most `max_records` records and `max_bytes` bytes + /// of arguments and results per seat. + pub(crate) fn new(max_records: usize, max_bytes: usize) -> Self { + Self { + seats: Mutex::default(), + max_records, + max_bytes, + } + } + + /// What is known of `identity` as a call of `tool` with `arguments`. + /// Looking changes nothing. + pub(crate) fn lookup(&self, identity: &Identity, tool: &str, arguments: &Value) -> Known { + let seats = self.seats.lock().unwrap_or_else(PoisonError::into_inner); + seats + .get(&identity.seat) + .filter(|turn| turn.turn == identity.turn) + .map_or(Known::New, |turn| { + known(&turn.calls, &identity.call, tool, arguments) + }) + } + + /// Record `identity` as started, if `running` (asked under the lock) says + /// its turn is the seat's running turn and it is not known already. + pub(crate) fn start( + &self, + identity: &Identity, + tool: &str, + arguments: &Value, + running: impl FnOnce() -> Option, + ) -> Known { + let mut seats = self.seats.lock().unwrap_or_else(PoisonError::into_inner); + if running().as_deref() != Some(identity.turn.as_str()) { + return Known::Stale; + } + let turn = seats.entry(identity.seat.clone()).or_default(); + if turn.turn != identity.turn { + // The stored turn is not running, so it has ended. + *turn = Records { + turn: identity.turn.clone(), + ..Records::default() + }; + } + let known = known(&turn.calls, &identity.call, tool, arguments); + if known != Known::New { + return known; + } + let bytes = identity.call.len() + tool.len() + arguments.to_string().len(); + if turn.calls.len() >= self.max_records || turn.bytes + bytes > self.max_bytes { + return Known::Full; + } + turn.bytes += bytes; + turn.calls.insert( + identity.call.clone(), + Entry { + tool: tool.into(), + arguments: arguments.clone(), + outcome: None, + bytes, + }, + ); + Known::New + } + + /// Record what a started call returned. A call whose turn has since been + /// replaced has no record left to finish. + pub(crate) fn finish(&self, identity: &Identity, outcome: Outcome) { + self.with_entry(identity, |turn, call| { + if let Some(entry) = turn.calls.get_mut(call) { + entry.bytes += outcome.text.len(); + turn.bytes += outcome.text.len(); + entry.outcome = Some(outcome); + } + }); + } + + /// Drop the record of a started call that was refused before any hook or + /// tool ran, so that it records nothing. + pub(crate) fn abandon(&self, identity: &Identity) { + self.with_entry(identity, |turn, call| { + if let Some(entry) = turn.calls.remove(call) { + turn.bytes -= entry.bytes; + } + }); + } + + /// Drop every record of `seat`. + pub(crate) fn forget(&self, seat: &str) { + let mut seats = self.seats.lock().unwrap_or_else(PoisonError::into_inner); + seats.remove(seat); + } + + /// Drop the records of every seat whose turn `running` says has ended. + pub(crate) fn purge(&self, running: impl Fn(&str) -> Option) { + let mut seats = self.seats.lock().unwrap_or_else(PoisonError::into_inner); + seats.retain(|seat, turn| running(seat).as_deref() == Some(turn.turn.as_str())); + } + + fn with_entry(&self, identity: &Identity, act: impl FnOnce(&mut Records, &str)) { + let mut seats = self.seats.lock().unwrap_or_else(PoisonError::into_inner); + if let Some(turn) = seats + .get_mut(&identity.seat) + .filter(|turn| turn.turn == identity.turn) + { + act(turn, &identity.call); + } + } +} + +fn known(calls: &HashMap, call: &str, tool: &str, arguments: &Value) -> Known { + match calls.get(call) { + None => Known::New, + Some(entry) if entry.tool != tool || entry.arguments != *arguments => Known::Reused, + Some(Entry { + outcome: Some(outcome), + .. + }) => Known::Answered(outcome.clone()), + Some(_) => Known::Running, + } +} diff --git a/crates/tinyhivemind-mcp/src/tools/mod.rs b/crates/tinyhivemind-mcp/src/tools/mod.rs new file mode 100644 index 00000000..08dd8082 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/tools/mod.rs @@ -0,0 +1,163 @@ +//! The tools one seat is served, and how a call of one is carried out. +//! +//! A [`Catalog`] holds the hive tools and the seat's executable tools that +//! its permissions allow, each with the schema the model sees. A tool that +//! changes state (every hive tool but the list and read tools, every program +//! not declared `side_effects = "read"`, and any tool a hook matches) gets +//! two required arguments in its schema, `turn` and `call`, which +//! [`dispatch`] checks and removes before hooks and dispatch. +mod dispatch; +mod gate; +mod ledger; +mod schema; + +use crate::seat::{RESERVED, SeatTools}; +use crate::{Error, Result}; +pub(crate) use dispatch::{SeatState, call}; +pub(crate) use ledger::Ledger; +pub(crate) use schema::unsupported; +use serde_json::{Value, json}; +use std::collections::BTreeSet; +use tinyhivemind_exec::HookRunner; +use tinyhivemind_host::tools::Kind; +use tinyhivemind_lang::{ExecTool, SideEffects}; + +/// What a served tool runs. +#[derive(Clone, Debug)] +pub(crate) enum Target { + /// A hive tool, through the host's belt. + Hive(Kind), + /// An executable tool of the package. + Program(ExecTool), +} + +/// One tool as a seat is served it. +#[derive(Clone, Debug)] +pub(crate) struct Served { + pub(crate) name: String, + description: String, + schema: Value, + pub(crate) target: Target, + /// The call must name its turn and carry a `call`. + pub(crate) changes_state: bool, + /// A `pre_tool_use` or `post_tool_use` hook matches it. + pub(crate) hooked: bool, +} + +/// Every tool one seat is served, in a fixed order. +#[derive(Clone, Debug)] +pub(crate) struct Catalog(Vec); + +impl Catalog { + /// The hive tools (management ones when `managed`), then the seat's + /// programs, less what its permissions deny. + pub(crate) fn build(seat: &SeatTools, hooks: &HookRunner, managed: bool) -> Result { + let mut served = Vec::new(); + let mut names = BTreeSet::new(); + let hive = Kind::all(managed).into_iter().map(|kind| { + let reads = matches!(kind, Kind::ListHives | Kind::ListAgents | Kind::Read); + let (name, schema) = (kind.name().to_owned(), kind.schema()); + ( + name, + kind.description().to_owned(), + schema, + Target::Hive(kind), + !reads, + ) + }); + let programs = seat.programs().iter().map(|tool| { + let writes = tool.side_effects != SideEffects::Read; + let target = Target::Program(tool.clone()); + ( + tool.id.clone(), + tool.description.clone(), + tool.args.clone(), + target, + writes, + ) + }); + for (name, description, schema, target, effectful) in hive.chain(programs) { + if !names.insert(name.clone()) { + return Err(Error::DuplicateTool(name)); + } + if !seat.permits(&name) { + continue; + } + let hooked = hooks.matches_tool(&name); + let changes_state = effectful || hooked; + let schema = if changes_state { + identified(schema) + } else { + schema + }; + served.push(Served { + name, + description, + schema, + target, + changes_state, + hooked, + }); + } + Ok(Self(served)) + } + + /// The tool the model calls `name`. + pub(crate) fn find(&self, name: &str) -> Option<&Served> { + self.0.iter().find(|tool| tool.name == name) + } + + /// Every served name. + pub(crate) fn names(&self) -> Vec { + self.0.iter().map(|tool| tool.name.clone()).collect() + } + + /// The `tools/list` result's `tools`. + pub(crate) fn listing(&self) -> Value { + Value::Array( + self.0 + .iter() + .map(|tool| { + json!({ + "name": tool.name, + "description": tool.description, + "inputSchema": tool.schema, + }) + }) + .collect(), + ) + } +} + +/// `schema` with the required `turn` and `call` arguments added. +fn identified(mut schema: Value) -> Value { + if !schema.is_object() { + schema = json!({"type": "object"}); + } + let fields = [ + ( + RESERVED[0], + "Your running turn id, exactly as your turn gave it. A call from any other turn is refused.", + ), + ( + RESERVED[1], + "A name you choose for this one action, unique within the turn. Repeat it only to retry the same call with the same arguments.", + ), + ]; + if !schema["properties"].is_object() { + schema["properties"] = json!({}); + } + if !schema["required"].is_array() { + schema["required"] = json!([]); + } + for (name, description) in fields { + schema["properties"][name] = json!({"type": "string", "description": description}); + if let Some(required) = schema["required"].as_array_mut() { + required.push(json!(name)); + } + } + schema +} + +#[cfg(test)] +mod test; diff --git a/crates/tinyhivemind-mcp/src/tools/schema.rs b/crates/tinyhivemind-mcp/src/tools/schema.rs new file mode 100644 index 00000000..f81f70df --- /dev/null +++ b/crates/tinyhivemind-mcp/src/tools/schema.rs @@ -0,0 +1,180 @@ +//! Arguments checked against an executable tool's declared schema. +//! +//! The language only requires `args` to be an object schema, and no JSON +//! Schema validator is linked outside the harness, so this checks the subset a +//! tool argument schema uses: `type` (a name or a list of names), `enum`, +//! `const`, `properties`, `required`, `additionalProperties` (a boolean or a +//! schema), `items`, `minimum`, `maximum`, `exclusiveMinimum`, +//! `exclusiveMaximum`, `minLength`, `maxLength`, `minItems` and `maxItems`. +//! Annotations (`description`, `title`, `default`, `examples`, `format`, +//! `$comment`) check nothing. A schema using any other keyword is refused +//! when its seat is served, so no keyword is ever accepted and left +//! unchecked. +use serde_json::{Map, Value}; + +const CHECKED: [&str; 15] = [ + "type", + "enum", + "const", + "properties", + "required", + "additionalProperties", + "items", + "minimum", + "maximum", + "exclusiveMinimum", + "exclusiveMaximum", + "minLength", + "maxLength", + "minItems", + "maxItems", +]; +const ANNOTATIONS: [&str; 6] = [ + "description", + "title", + "default", + "examples", + "format", + "$comment", +]; + +/// The first keyword in `schema`, at any depth, that is not checked here. +pub(crate) fn unsupported(schema: &Value) -> Option { + let object = schema.as_object()?; + for (keyword, value) in object { + let known = CHECKED.contains(&keyword.as_str()) || ANNOTATIONS.contains(&keyword.as_str()); + if !known { + return Some(keyword.clone()); + } + let nested = match keyword.as_str() { + "properties" => value + .as_object() + .and_then(|properties| properties.values().find_map(unsupported)), + "items" | "additionalProperties" => unsupported(value), + _ => None, + }; + if nested.is_some() { + return nested; + } + } + None +} + +/// Check `value` against `schema`, naming the first place it does not fit. +pub(crate) fn check(schema: &Value, value: &Value, at: &str) -> Result<(), String> { + let Some(schema) = schema.as_object() else { + return Ok(()); + }; + if let Some(kinds) = schema.get("type") { + let names: Vec<&str> = match kinds { + Value::String(name) => vec![name.as_str()], + Value::Array(names) => names.iter().filter_map(Value::as_str).collect(), + _ => Vec::new(), + }; + if !names.iter().any(|name| is(name, value)) { + return Err(format!("{at} must be {}", names.join(" or "))); + } + } + if let Some(allowed) = schema.get("enum").and_then(Value::as_array) + && !allowed.contains(value) + { + return Err(format!("{at} is not one of the allowed values")); + } + if schema + .get("const") + .is_some_and(|constant| constant != value) + { + return Err(format!("{at} is not the allowed value")); + } + bounds(schema, value, at)?; + if let (Some(items), Some(values)) = (schema.get("items"), value.as_array()) { + for (index, item) in values.iter().enumerate() { + check(items, item, &format!("{at}[{index}]"))?; + } + } + if let Some(object) = value.as_object() { + fields(schema, object, at)?; + } + Ok(()) +} + +fn is(name: &str, value: &Value) -> bool { + match name { + "string" => value.is_string(), + "integer" => { + value.is_i64() || value.is_u64() || value.as_f64().is_some_and(|n| n.fract() == 0.0) + } + "number" => value.is_number(), + "boolean" => value.is_boolean(), + "object" => value.is_object(), + "array" => value.is_array(), + "null" => value.is_null(), + _ => false, + } +} + +fn bounds(schema: &Map, value: &Value, at: &str) -> Result<(), String> { + let limit = |keyword: &str| schema.get(keyword).and_then(Value::as_f64); + let count = |keyword: &str| schema.get(keyword).and_then(Value::as_u64); + if let Some(number) = value.as_f64() { + let fails = limit("minimum").is_some_and(|min| number < min) + || limit("maximum").is_some_and(|max| number > max) + || limit("exclusiveMinimum").is_some_and(|min| number <= min) + || limit("exclusiveMaximum").is_some_and(|max| number >= max); + if fails { + return Err(format!("{at} is out of range")); + } + } + let length = match value { + Value::String(text) => Some((text.chars().count() as u64, "Length")), + Value::Array(items) => Some((items.len() as u64, "Items")), + _ => None, + }; + if let Some((length, unit)) = length { + let fails = count(&format!("min{unit}")).is_some_and(|min| length < min) + || count(&format!("max{unit}")).is_some_and(|max| length > max); + if fails { + return Err(format!("{at} has the wrong length")); + } + } + Ok(()) +} + +fn fields( + schema: &Map, + object: &Map, + at: &str, +) -> Result<(), String> { + let path = |name: &str| { + if at.is_empty() { + name.to_owned() + } else { + format!("{at}.{name}") + } + }; + let properties = schema.get("properties").and_then(Value::as_object); + for required in schema + .get("required") + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + { + if !object.contains_key(required) { + return Err(format!("missing argument {}", path(required))); + } + } + for (name, field) in object { + match properties.and_then(|properties| properties.get(name)) { + Some(declared) => check(declared, field, &path(name))?, + None => match schema.get("additionalProperties") { + Some(Value::Bool(false)) => { + return Err(format!("unknown argument {}", path(name))); + } + Some(extra @ Value::Object(_)) => check(extra, field, &path(name))?, + _ => {} + }, + } + } + Ok(()) +} diff --git a/crates/tinyhivemind-mcp/src/tools/test.rs b/crates/tinyhivemind-mcp/src/tools/test.rs new file mode 100644 index 00000000..f002f9f2 --- /dev/null +++ b/crates/tinyhivemind-mcp/src/tools/test.rs @@ -0,0 +1,148 @@ +//! The ledger's turn rules and bounds, and the argument schema checker. +use super::ledger::{Identity, Known, Ledger, Outcome}; +use super::schema::{check, unsupported}; +use serde_json::json; + +fn id(turn: &str, call: &str) -> Identity { + Identity { + seat: "a".into(), + turn: turn.into(), + call: call.into(), + } +} +fn running(turn: &'static str) -> impl Fn() -> Option { + move || Some(turn.to_owned()) +} + +#[test] +fn a_stale_start_neither_records_nor_replaces_the_running_turns_records() { + let ledger = Ledger::new(8, 4096); + let args = json!({}); + assert_eq!( + ledger.start(&id("t2", "c"), "x", &args, running("t2")), + Known::New + ); + ledger.finish(&id("t2", "c"), Outcome::success("done")); + assert_eq!( + ledger.start(&id("t1", "c"), "x", &args, running("t2")), + Known::Stale + ); + assert_eq!(ledger.lookup(&id("t1", "c"), "x", &args), Known::New); + assert_eq!( + ledger.lookup(&id("t2", "c"), "x", &args), + Known::Answered(Outcome::success("done")) + ); +} + +#[test] +fn abandon_forget_and_purge_drop_records() { + let ledger = Ledger::new(8, 4096); + let args = json!({}); + ledger.start(&id("t1", "c"), "x", &args, running("t1")); + assert_eq!(ledger.lookup(&id("t1", "c"), "x", &args), Known::Running); + ledger.abandon(&id("t1", "c")); + assert_eq!(ledger.lookup(&id("t1", "c"), "x", &args), Known::New); + ledger.start(&id("t1", "c"), "x", &args, running("t1")); + ledger.purge(|_| Some("t1".into())); + assert_eq!(ledger.lookup(&id("t1", "c"), "x", &args), Known::Running); + ledger.purge(|_| None); + assert_eq!(ledger.lookup(&id("t1", "c"), "x", &args), Known::New); + ledger.start(&id("t1", "c"), "x", &args, running("t1")); + ledger.forget("a"); + assert_eq!(ledger.lookup(&id("t1", "c"), "x", &args), Known::New); +} + +#[test] +fn a_full_seat_refuses_and_a_newer_turn_starts_empty() { + let ledger = Ledger::new(1, 4096); + let args = json!({}); + assert_eq!( + ledger.start(&id("t1", "a"), "x", &args, running("t1")), + Known::New + ); + assert_eq!( + ledger.start(&id("t1", "b"), "x", &args, running("t1")), + Known::Full + ); + assert_eq!( + ledger.start(&id("t1", "a"), "y", &args, running("t1")), + Known::Reused + ); + assert_eq!( + ledger.start(&id("t2", "b"), "x", &args, running("t2")), + Known::New + ); + let tight = Ledger::new(8, 8); + let big = json!({"note": "far too long for the bound"}); + assert_eq!( + tight.start(&id("t1", "a"), "x", &big, running("t1")), + Known::Full + ); +} + +#[test] +fn the_schema_checker_enforces_every_keyword_it_accepts() { + let schema = json!({ + "type": "object", + "description": "fixture", + "properties": { + "name": {"type": "string", "minLength": 2, "maxLength": 4}, + "count": {"type": "integer", "minimum": 1, "maximum": 3}, + "ratio": {"type": "number", "exclusiveMinimum": 0, "exclusiveMaximum": 1}, + "mode": {"enum": ["a", "b"]}, + "fixed": {"const": 7}, + "tags": {"type": "array", "items": {"type": "string"}, "minItems": 1, "maxItems": 2}, + "maybe": {"type": ["string", "null"]}, + "flag": {"type": "boolean"}, + "nested": {"type": "object", "required": ["x"], "additionalProperties": {"type": "integer"}} + }, + "additionalProperties": false + }); + assert_eq!(unsupported(&schema), None); + let fits = json!({ + "name": "abc", "count": 2, "ratio": 0.5, "mode": "a", "fixed": 7, + "tags": ["t"], "maybe": null, "flag": true, "nested": {"x": 1, "y": 2} + }); + assert_eq!(check(&schema, &fits, ""), Ok(())); + for (field, value, said) in [ + ("name", json!("a"), "name has the wrong length"), + ("count", json!(9), "count is out of range"), + ("count", json!(1.5), "count must be integer"), + ("ratio", json!(1), "ratio is out of range"), + ("mode", json!("c"), "mode is not one of the allowed values"), + ("fixed", json!(8), "fixed is not the allowed value"), + ("tags", json!([]), "tags has the wrong length"), + ("tags", json!([1]), "tags[0] must be string"), + ("maybe", json!(1), "maybe must be string or null"), + ("flag", json!("yes"), "flag must be boolean"), + ("nested", json!({"y": 1}), "missing argument nested.x"), + ( + "nested", + json!({"x": 1, "y": "z"}), + "nested.y must be integer", + ), + ("other", json!(1), "unknown argument other"), + ] { + let mut value_set = fits.clone(); + value_set[field] = value; + assert_eq!( + check(&schema, &value_set, ""), + Err(said.to_owned()), + "{field}" + ); + } + assert_eq!(check(&json!(true), &json!(1), ""), Ok(())); +} + +#[test] +fn an_unchecked_keyword_is_found_at_any_depth() { + assert_eq!( + unsupported(&json!({"type": "object", "oneOf": []})), + Some("oneOf".into()) + ); + let nested = json!({"properties": {"a": {"items": {"pattern": "x"}}}}); + assert_eq!(unsupported(&nested), Some("pattern".into())); + let extra = json!({"additionalProperties": {"format": "uri", "$ref": "#"}}); + assert_eq!(unsupported(&extra), Some("$ref".into())); + assert_eq!(unsupported(&json!(true)), None); +} diff --git a/crates/tinyhivemind-mcp/tests/README.md b/crates/tinyhivemind-mcp/tests/README.md new file mode 100644 index 00000000..62c8a392 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/README.md @@ -0,0 +1,15 @@ +# Tests + +Every test drives a real server over a loopback HTTP/1.1 client. + +| File | Covers | +| --- | --- | +| `http.rs` | Bearer, Host, Origin, body bound, methods and paths, version negotiation, notifications, malformed messages, tools-only surface, redacted `Debug`, the connection bound, shutdown | +| `calls.rs` | Hive tools: the served schemas, turn and call checks, retries, reuse, another seat, a forged actor, sends, joins, `create_agent`, a hook-denied call, policy refusals before hooks | +| `programs.rs` | Executable tools: retries, an unknown outcome, hooked reads, hook denial, the `read_only` and `supervised` gates, the approver | +| `policy.rs` | The host send policy refusing a send; secrets and `Services` debug | +| `review.rs` | Turn changes during approval, hang-ups, call and record bounds, argument schemas | +| `seats.rs` | `SeatTools::from_lowered` refusals and access, permission tool names, duplicates | +| `e2e.rs` | A harness's whole session: initialize, notification, GET, list, and a post as seat `a`, refused as seat `b` | +| [`support/`](support/README.md) | The client and the held-turn hive fixture | +| [`fixtures/`](fixtures/README.md) | Scripts the executable tools and hooks run | diff --git a/crates/tinyhivemind-mcp/tests/calls.rs b/crates/tinyhivemind-mcp/tests/calls.rs new file mode 100644 index 00000000..e58e7da3 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/calls.rs @@ -0,0 +1,457 @@ +//! Hive tools: the turn check, call identity, and policy before dispatch. +#![allow(clippy::unwrap_used, clippy::expect_used)] +mod support; + +use serde_json::{Value, json}; +use std::sync::Arc; +use support::{Hive, hook}; +use tinyhivemind_hives::HiveInfo; +use tinyhivemind_host::Result as HostResult; +use tinyhivemind_host::policy::{ + AgentCreator, CreateFuture, ManagementAuthorizer, ManagementRequest, NewAgent, SendAuthorizer, + SendRequest, +}; + +fn post(hive: &Hive, call: &str, body: &str) -> Value { + json!({"episode_id": hive.episode(), "body": body, "turn": hive.turn_id(), "call": call}) +} + +async fn plain() -> Hive { + Hive::start(|services| services, |seat, _| seat).await +} + +#[tokio::test] +async fn tools_list_adds_turn_and_call_to_state_changing_tools_only() { + let hive = plain().await; + let tools = hive.a.tools().await; + let names: Vec<&str> = tools.iter().map(|(name, _)| name.as_str()).collect(); + assert_eq!( + names, + [ + "hivemind_list_hives", + "hivemind_list_agents", + "hivemind_read", + "hivemind_send_hive", + "hivemind_send_agent", + "hivemind_post", + "hivemind_ask", + "hivemind_broadcast", + "hivemind_complete", + ] + ); + for (name, schema) in &tools { + let changes = !matches!( + name.as_str(), + "hivemind_list_hives" | "hivemind_list_agents" | "hivemind_read" + ); + for field in ["turn", "call"] { + assert_eq!( + schema["properties"].get(field).is_some(), + changes, + "{name} {field}" + ); + let required = schema["required"].as_array().unwrap(); + assert_eq!(required.contains(&json!(field)), changes, "{name} {field}"); + } + } + let names: Vec = hive.endpoint.tools.iter().cloned().collect(); + assert_eq!(names.len(), 9); +} + +#[tokio::test] +async fn a_retried_post_acts_once_and_returns_the_first_result() { + let mut hive = plain().await; + let first = hive + .a + .call("hivemind_post", post(&hive, "p1", "once")) + .await; + assert_eq!(first, (r#"{"accepted":true}"#.into(), false)); + assert_eq!( + hive.a + .call("hivemind_post", post(&hive, "p1", "once")) + .await, + first + ); + hive.settle().await; + assert_eq!(hive.written("a", "once"), 1); +} + +#[tokio::test] +async fn two_identical_posts_under_different_calls_both_act() { + let mut hive = plain().await; + for call in ["p1", "p2"] { + let (_, failed) = hive + .a + .call("hivemind_post", post(&hive, call, "twice")) + .await; + assert!(!failed); + } + hive.settle().await; + assert_eq!(hive.written("a", "twice"), 2); +} + +#[tokio::test] +async fn reusing_a_call_with_other_arguments_or_another_tool_is_refused() { + let mut hive = plain().await; + hive.a + .call("hivemind_post", post(&hive, "p1", "first")) + .await; + let (text, failed) = hive + .a + .call("hivemind_post", post(&hive, "p1", "second")) + .await; + assert!(failed && text.contains("already made"), "{text}"); + let (text, failed) = hive + .a + .call("hivemind_complete", post(&hive, "p1", "first")) + .await; + assert!(failed && text.contains("already made"), "{text}"); + hive.settle().await; + assert_eq!(hive.written("a", "second"), 0); +} + +#[tokio::test] +async fn a_missing_call_or_turn_is_refused() { + let mut hive = plain().await; + let mut missing_call = post(&hive, "p1", "none"); + missing_call.as_object_mut().unwrap().remove("call"); + let (text, failed) = hive.a.call("hivemind_post", missing_call).await; + assert!(failed && text.contains("call"), "{text}"); + let mut missing_turn = post(&hive, "p1", "none"); + missing_turn.as_object_mut().unwrap().remove("turn"); + let (text, failed) = hive.a.call("hivemind_post", missing_turn).await; + assert!(failed && text.contains("turn"), "{text}"); + let (_, failed) = hive.a.call("hivemind_post", post(&hive, "", "none")).await; + assert!(failed); + hive.settle().await; + assert_eq!(hive.written("a", "none"), 0); +} + +#[tokio::test] +async fn a_stale_turn_is_refused() { + let mut hive = plain().await; + let mut stale = post(&hive, "p1", "late"); + stale["turn"] = json!("0:1:a"); + let (text, failed) = hive.a.call("hivemind_post", stale).await; + assert!(failed && text.contains("not the running turn"), "{text}"); + hive.settle().await; + // After the turn ends, its own id is stale too. + let (_, failed) = hive + .a + .call("hivemind_post", post(&hive, "p2", "late")) + .await; + assert!(failed); + assert_eq!(hive.written("a", "late"), 0); +} + +#[tokio::test] +async fn another_seats_bearer_cannot_act_in_a_turn_and_has_none_of_its_own() { + let mut hive = plain().await; + // `b` presents `a`'s turn and episode: the bearer says `b`, which is not running. + let (text, failed) = hive + .b + .call("hivemind_post", post(&hive, "p1", "as b")) + .await; + assert!( + failed && text.contains("not the running turn of b"), + "{text}" + ); + hive.settle().await; + assert_eq!(hive.written("a", "as b") + hive.written("b", "as b"), 0); +} + +#[tokio::test] +async fn another_seats_episode_is_refused() { + let mut hive = plain().await; + let mut other = post(&hive, "p1", "elsewhere"); + other["episode_id"] = json!("episode:999"); + let (text, failed) = hive.a.call("hivemind_post", other).await; + assert!(failed && text.contains("stale episode"), "{text}"); + hive.settle().await; + assert_eq!(hive.written("a", "elsewhere"), 0); +} + +#[tokio::test] +async fn a_forged_actor_is_refused() { + let mut hive = plain().await; + let mut forged = post(&hive, "p1", "forged"); + forged["sender"] = json!("b"); + let (text, failed) = hive.a.call("hivemind_post", forged).await; + assert!(failed && text.contains("unknown argument sender"), "{text}"); + hive.settle().await; + assert_eq!(hive.written("a", "forged") + hive.written("b", "forged"), 0); +} + +#[tokio::test] +async fn an_unknown_tool_is_a_protocol_error() { + let hive = plain().await; + let response = hive + .a + .rpc( + "tools/call", + json!({"name": "hivemind_create_hive", "arguments": {}}), + ) + .await; + assert_eq!(response["error"]["code"], -32602); +} + +#[tokio::test] +async fn a_read_needs_no_identity() { + let hive = plain().await; + let (text, failed) = hive.a.call("hivemind_list_hives", json!({})).await; + assert!(!failed, "{text}"); + assert!(text.contains("work")); +} + +#[tokio::test] +async fn a_retried_send_acts_once_and_one_message_id_is_one_message() { + let hive = plain().await; + let send = |call: &str| json!({"agent_id": "b", "message_id": "m1", "body": "hello b", "turn": hive.turn_id(), "call": call}); + let first = hive.a.call("hivemind_send_agent", send("s1")).await; + assert!(!first.1, "{first:?}"); + assert_eq!(hive.a.call("hivemind_send_agent", send("s1")).await, first); + assert_eq!(hive.a.call("hivemind_send_agent", send("s2")).await, first); + assert_eq!( + hive.coordinator.read_direct("a", "b", None).unwrap().len(), + 1 + ); +} + +/// Admits every management request; builds no agents. +struct Open; +impl ManagementAuthorizer for Open { + fn authorize(&self, _: &str, _: &ManagementRequest) -> HostResult<()> { + Ok(()) + } +} +impl AgentCreator for Open { + fn create(&self, _: NewAgent) -> CreateFuture<'_> { + Box::pin(async { Err(tinyhivemind_host::Error::Host("no templates".into())) }) + } +} + +#[tokio::test] +async fn a_retried_join_acts_once_and_returns_the_first_result() { + let hive = Hive::start( + |services| services.with_management(Arc::new(Open), Arc::new(Open)), + |seat, _| seat, + ) + .await; + assert_eq!(hive.a.tools().await.len(), 13); + hive.coordinator + .create_hive(HiveInfo { + hive_id: "side".into(), + name: "Side".into(), + description: None, + members: Vec::new(), + }) + .await + .unwrap(); + let join = json!({"hive_id": "side", "agent_id": "a", "turn": hive.turn_id(), "call": "j1"}); + let first = hive.a.call("hivemind_join_hive", join.clone()).await; + assert_eq!(first, (r#"{"joined":true}"#.into(), false)); + hive.coordinator.leave_hive("side", "a").await.unwrap(); + assert_eq!(hive.a.call("hivemind_join_hive", join).await, first); + let side = hive + .coordinator + .list_hives() + .unwrap() + .into_iter() + .find(|h| h.hive_id == "side") + .unwrap(); + assert_eq!(side.members, Vec::::new()); +} + +#[tokio::test] +async fn a_failed_agent_creation_is_recorded_and_not_retried() { + let hive = Hive::start( + |services| services.with_management(Arc::new(Open), Arc::new(Open)), + |seat, _| seat, + ) + .await; + let create = json!({"template": "t", "config": {}, "turn": hive.turn_id(), "call": "c1"}); + let first = hive.a.call("hivemind_create_agent", create.clone()).await; + assert!(first.1 && first.0.contains("no templates"), "{first:?}"); + assert_eq!(hive.a.call("hivemind_create_agent", create).await, first); +} + +#[tokio::test] +async fn a_hook_denied_call_is_recorded_and_a_corrected_call_uses_a_new_call() { + let mut hive = Hive::start( + |services| services, + |seat, context| { + seat.with_context(context).with_hooks(vec![hook( + "guard", + "pre_tool_use", + "hivemind_post", + "guard", + )]) + }, + ) + .await; + let denied = hive + .a + .call("hivemind_post", post(&hive, "p1", "forbidden")) + .await; + assert_eq!(denied, ("forbidden by guard".into(), true)); + assert_eq!(hive.lines("guard.log"), 1); + // The retry is answered from the record: no hook runs again. + assert_eq!( + hive.a + .call("hivemind_post", post(&hive, "p1", "forbidden")) + .await, + denied + ); + assert_eq!(hive.lines("guard.log"), 1); + let corrected = hive + .a + .call("hivemind_post", post(&hive, "p2", "allowed")) + .await; + assert!(!corrected.1, "{corrected:?}"); + assert_eq!( + hive.a + .call("hivemind_post", post(&hive, "p2", "allowed")) + .await, + corrected + ); + assert_eq!(hive.lines("guard.log"), 2); + hive.settle().await; + assert_eq!(hive.written("a", "forbidden"), 0); + assert_eq!(hive.written("a", "allowed"), 1); +} + +/// Refuses direct messages whose body says "secret", and joins to `closed`. +struct Strict; +impl SendAuthorizer for Strict { + fn authorize(&self, _: &str, request: &SendRequest) -> HostResult<()> { + match request { + SendRequest::Agent { body, .. } if body.contains("secret") => { + Err(tinyhivemind_host::Error::SendDenied("no secrets".into())) + } + _ => Ok(()), + } + } +} +impl ManagementAuthorizer for Strict { + fn authorize(&self, _: &str, request: &ManagementRequest) -> HostResult<()> { + match request { + ManagementRequest::JoinHive { hive_id, .. } if hive_id == "closed" => { + Err(tinyhivemind_host::Error::Unauthorized("closed hive".into())) + } + _ => Ok(()), + } + } +} + +async fn guarded() -> Hive { + Hive::start( + |services| { + services + .with_send_policy(Arc::new(Strict)) + .with_management(Arc::new(Strict), Arc::new(Open)) + }, + |seat, context| { + seat.with_context(context).with_hooks(vec![ + hook("guard", "pre_tool_use", "hivemind_*", "guard"), + hook("audit", "post_tool_use", "hivemind_*", "audit"), + ]) + }, + ) + .await +} + +#[tokio::test] +async fn a_send_the_policy_refuses_runs_no_hook_and_records_nothing() { + let hive = guarded().await; + let send = |call: &str, body: &str| json!({"agent_id": "b", "message_id": call, "body": body, "turn": hive.turn_id(), "call": call}); + let (text, failed) = hive + .a + .call("hivemind_send_agent", send("s1", "a secret")) + .await; + assert!(failed && text.contains("no secrets"), "{text}"); + assert_eq!((hive.lines("guard.log"), hive.lines("audit.log")), (0, 0)); + // Nothing was recorded: the same call is judged again, not answered. + let (_, failed) = hive + .a + .call("hivemind_send_agent", send("s1", "a secret")) + .await; + assert!(failed); + assert_eq!((hive.lines("guard.log"), hive.lines("audit.log")), (0, 0)); + assert_eq!( + hive.coordinator.read_direct("a", "b", None).unwrap().len(), + 0 + ); + // An allowed send runs each hook once, and its retry runs none. + let (text, failed) = hive + .a + .call("hivemind_send_agent", send("s2", "hello")) + .await; + assert!(!failed, "{text}"); + hive.a + .call("hivemind_send_agent", send("s2", "hello")) + .await; + assert_eq!((hive.lines("guard.log"), hive.lines("audit.log")), (1, 1)); + assert_eq!( + hive.coordinator.read_direct("a", "b", None).unwrap().len(), + 1 + ); +} + +#[tokio::test] +async fn a_join_management_refuses_runs_no_hook_and_records_nothing() { + let hive = guarded().await; + for id in ["closed", "open"] { + hive.coordinator + .create_hive(HiveInfo { + hive_id: id.into(), + name: id.into(), + description: None, + members: Vec::new(), + }) + .await + .unwrap(); + } + let join = |call: &str, hive_id: &str| json!({"hive_id": hive_id, "agent_id": "a", "turn": hive.turn_id(), "call": call}); + let (text, failed) = hive + .a + .call("hivemind_join_hive", join("j1", "closed")) + .await; + assert!(failed && text.contains("closed hive"), "{text}"); + assert_eq!(hive.lines("guard.log"), 0); + let (text, failed) = hive.a.call("hivemind_join_hive", join("j2", "open")).await; + assert!(!failed, "{text}"); + assert_eq!((hive.lines("guard.log"), hive.lines("audit.log")), (1, 1)); +} + +/// Admits sends until told to refuse them. +#[derive(Default)] +struct Toggle(std::sync::atomic::AtomicBool); +impl SendAuthorizer for Toggle { + fn authorize(&self, _: &str, _: &SendRequest) -> HostResult<()> { + if self.0.load(std::sync::atomic::Ordering::SeqCst) { + Err(tinyhivemind_host::Error::SendDenied( + "sends are closed".into(), + )) + } else { + Ok(()) + } + } +} + +#[tokio::test] +async fn a_recorded_send_is_answered_even_after_the_policy_changes() { + let toggle = Arc::new(Toggle::default()); + let policy = toggle.clone(); + let hive = Hive::start( + move |services| services.with_send_policy(policy), + |seat, _| seat, + ) + .await; + let send = |call: &str| json!({"agent_id": "b", "message_id": call, "body": "hi", "turn": hive.turn_id(), "call": call}); + let first = hive.a.call("hivemind_send_agent", send("s1")).await; + assert!(!first.1, "{first:?}"); + toggle.0.store(true, std::sync::atomic::Ordering::SeqCst); + assert_eq!(hive.a.call("hivemind_send_agent", send("s1")).await, first); + let (text, failed) = hive.a.call("hivemind_send_agent", send("s2")).await; + assert!(failed && text.contains("sends are closed"), "{text}"); +} diff --git a/crates/tinyhivemind-mcp/tests/e2e.rs b/crates/tinyhivemind-mcp/tests/e2e.rs new file mode 100644 index 00000000..d440580c --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/e2e.rs @@ -0,0 +1,53 @@ +//! A harness's whole MCP session, as the three harnesses ran it in the spike. +#![allow(clippy::unwrap_used, clippy::expect_used)] +mod support; + +use http_body_util::Full; +use hyper::body::Bytes; +use hyper::{Request, StatusCode}; +use serde_json::json; +use support::{Hive, send}; + +#[tokio::test] +async fn a_client_lists_tools_and_posts_as_seat_a_and_is_refused_as_seat_b() { + let mut hive = Hive::start(|services| services, |seat, _| seat).await; + let addr = hive.server.local_addr(); + for client in [&hive.a, &hive.b] { + let init = client + .rpc("initialize", json!({"protocolVersion": "2025-11-25", "capabilities": {}, "clientInfo": {"name": "e2e", "version": "0"}})) + .await; + assert_eq!(init["result"]["protocolVersion"], "2025-11-25"); + let note = client + .message(&json!({"jsonrpc": "2.0", "method": "notifications/initialized"})) + .await; + assert_eq!(note.status, StatusCode::ACCEPTED); + // OpenClaw opens the optional event stream; it is not offered. + let stream = Request::get("/mcp") + .header("host", format!("127.0.0.1:{}", addr.port())) + .header("authorization", format!("Bearer {}", client.bearer)) + .header("accept", "text/event-stream") + .body(Full::new(Bytes::new())) + .unwrap(); + assert_eq!( + send(addr, stream).await.status, + StatusCode::METHOD_NOT_ALLOWED + ); + let names: Vec = client + .tools() + .await + .into_iter() + .map(|(name, _)| name) + .collect(); + assert!(names.contains(&"hivemind_post".to_owned())); + } + let args = json!({"episode_id": hive.episode(), "body": "hello hive", "turn": hive.turn_id(), "call": "post-1"}); + assert_eq!( + hive.a.call("hivemind_post", args.clone()).await, + (r#"{"accepted":true}"#.into(), false) + ); + let (text, refused) = hive.b.call("hivemind_post", args).await; + assert!(refused, "{text}"); + hive.settle().await; + assert_eq!(hive.written("a", "hello hive"), 1); + assert_eq!(hive.written("b", "hello hive"), 0); +} diff --git a/crates/tinyhivemind-mcp/tests/fixtures/README.md b/crates/tinyhivemind-mcp/tests/fixtures/README.md new file mode 100644 index 00000000..1d7de0dd --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/README.md @@ -0,0 +1,13 @@ +# Fixtures + +A package root for the integration tests. Every script runs in the seat's +temporary workspace, so the logs it writes are the test's evidence of how many +times it ran. + +| File | Does | +| --- | --- | +| `tools/stamp.sh` | Write tool; appends its arguments to `stamp.log`. | +| `tools/slow.sh` | Write tool; logs a start to `slow.log`, then waits for a `release` file. | +| `tools/look.sh` | Read tool; logs each run to `look.log`. | +| `tools/guard.sh` | `pre_tool_use` hook; logs to `guard.log` and refuses an event naming `forbidden`. | +| `tools/audit.sh` | `post_tool_use` hook; logs to `audit.log`. | diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/audit.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/audit.sh new file mode 100755 index 00000000..cf258fcf --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/audit.sh @@ -0,0 +1,4 @@ +#!/bin/sh +# A post_tool_use hook: logs each event. +input=$(cat) +printf '%s\n' "$input" >> audit.log diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/guard.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/guard.sh new file mode 100755 index 00000000..8c023d41 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/guard.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# A pre_tool_use hook: logs each event and refuses one naming "forbidden". +input=$(cat) +printf '%s\n' "$input" >> guard.log +case "$input" in + *forbidden*) printf '{"permission": "deny", "message": "forbidden by guard"}\n' ;; + *) echo '{}' ;; +esac diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/look.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/look.sh new file mode 100755 index 00000000..dca37896 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/look.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# A read tool: counts its runs in look.log. +cat > /dev/null +echo look >> look.log +echo seen diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/slow.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/slow.sh new file mode 100755 index 00000000..ee53a944 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/slow.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# A write tool that starts, then waits until the test creates `release`. +cat > /dev/null +echo started >> slow.log +while [ ! -e release ]; do sleep 0.02; done +echo released diff --git a/crates/tinyhivemind-mcp/tests/fixtures/tools/stamp.sh b/crates/tinyhivemind-mcp/tests/fixtures/tools/stamp.sh new file mode 100755 index 00000000..f7f78bd4 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/fixtures/tools/stamp.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# A write tool: appends its argument object to stamp.log in the workspace. +input=$(cat) +printf '%s\n' "$input" >> stamp.log +printf 'stamped %s\n' "$THM_CALL_ID" diff --git a/crates/tinyhivemind-mcp/tests/http.rs b/crates/tinyhivemind-mcp/tests/http.rs new file mode 100644 index 00000000..c2760e94 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/http.rs @@ -0,0 +1,263 @@ +//! Who may reach the server, how a request is bounded, and MCP framing. +#![allow(clippy::unwrap_used, clippy::expect_used)] +mod support; + +use http_body_util::Full; +use hyper::body::Bytes; +use hyper::{Request, StatusCode}; +use serde_json::json; +use support::{Hive, post, send}; +use tinyhivemind_mcp::{PROTOCOL_VERSIONS, ServerOptions}; + +fn body(value: &serde_json::Value) -> Vec { + serde_json::to_vec(value).unwrap() +} +const LIST: &str = r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#; + +async fn hive() -> Hive { + Hive::start(|services| services, |seat, _| seat).await +} + +#[tokio::test] +async fn a_wrong_or_missing_bearer_is_refused() { + let hive = hive().await; + let addr = hive.server.local_addr(); + for bearer in [Some("not-a-seat"), None] { + let request = post(addr, bearer, LIST.as_bytes()) + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + let reply = send(addr, request).await; + assert_eq!(reply.status, StatusCode::UNAUTHORIZED); + assert_eq!(reply.headers["www-authenticate"], "Bearer"); + } +} + +fn to_host(addr: std::net::SocketAddr, bearer: &str, hosts: &[&str]) -> Request> { + let mut builder = Request::post("/mcp").header("authorization", format!("Bearer {bearer}")); + let _ = addr; + for host in hosts { + builder = builder.header("host", *host); + } + builder.body(Full::new(Bytes::from(LIST))).unwrap() +} + +#[tokio::test] +async fn a_bad_host_is_refused() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let own = format!("127.0.0.1:{}", addr.port()); + let named = format!("localhost:{}", addr.port()); + for hosts in [ + vec!["evil.example"], + vec!["127.0.0.1:1"], + vec!["localhost"], + vec![own.as_str(), "evil.example"], + ] { + let reply = send(addr, to_host(addr, &hive.a.bearer, &hosts)).await; + assert_eq!(reply.status, StatusCode::FORBIDDEN, "{hosts:?}"); + } + for host in [own.as_str(), named.as_str()] { + let reply = send(addr, to_host(addr, &hive.a.bearer, &[host])).await; + assert_eq!(reply.status, StatusCode::OK, "{host}"); + } +} + +#[tokio::test] +async fn any_origin_is_refused() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let own = format!("http://127.0.0.1:{}", addr.port()); + for origin in ["https://evil.example", "null", own.as_str()] { + let request = post(addr, Some(&hive.a.bearer), LIST.as_bytes()) + .header("origin", origin) + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + assert_eq!(send(addr, request).await.status, StatusCode::FORBIDDEN); + } +} + +#[tokio::test] +async fn an_oversized_body_is_refused() { + let options = ServerOptions { + max_body_bytes: 64, + ..ServerOptions::default() + }; + let hive = Hive::start_with(|services| services, |seat, _| seat, options).await; + let addr = hive.server.local_addr(); + let big = body( + &json!({"jsonrpc": "2.0", "id": 1, "method": "ping", "params": {"pad": "x".repeat(100)}}), + ); + let request = post(addr, Some(&hive.a.bearer), &big) + .body(Full::new(Bytes::from(big.clone()))) + .unwrap(); + assert_eq!( + send(addr, request).await.status, + StatusCode::PAYLOAD_TOO_LARGE + ); +} + +#[tokio::test] +async fn only_post_to_the_mcp_path_is_served_and_nothing_redirects() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let host = format!("127.0.0.1:{}", addr.port()); + let auth = format!("Bearer {}", hive.a.bearer); + for method in ["GET", "DELETE", "PUT"] { + let request = Request::builder() + .method(method) + .uri("/mcp") + .header("host", &host) + .header("authorization", &auth) + .body(Full::new(Bytes::new())) + .unwrap(); + let reply = send(addr, request).await; + assert_eq!(reply.status, StatusCode::METHOD_NOT_ALLOWED); + assert_eq!(reply.headers["allow"], "POST"); + } + for path in ["/", "/mcp/", "/other"] { + let request = Request::post(path) + .header("host", &host) + .header("authorization", &auth) + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + let reply = send(addr, request).await; + assert_eq!(reply.status, StatusCode::NOT_FOUND); + assert!(reply.headers.get("location").is_none()); + } +} + +#[tokio::test] +async fn initialize_negotiates_every_version_the_harnesses_sent() { + let hive = hive().await; + // Codex 0.171 sent 2025-06-18; OpenHuman 0.64.15 and OpenClaw 2025-11-25. + for version in ["2025-06-18", "2025-11-25", "2025-03-26"] { + let response = hive + .a + .rpc( + "initialize", + json!({"protocolVersion": version, "capabilities": {}, "clientInfo": {"name": "t", "version": "0"}}), + ) + .await; + assert_eq!(response["result"]["protocolVersion"], version); + assert_eq!( + response["result"]["capabilities"], + json!({"tools": {"listChanged": false}}) + ); + assert_eq!(response["result"]["serverInfo"]["name"], "hivemind"); + } + let response = hive + .a + .rpc("initialize", json!({"protocolVersion": "1999-01-01"})) + .await; + assert_eq!(response["result"]["protocolVersion"], PROTOCOL_VERSIONS[0]); +} + +#[tokio::test] +async fn an_unsupported_protocol_version_header_is_refused() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let request = post(addr, Some(&hive.a.bearer), LIST.as_bytes()) + .header("mcp-protocol-version", "1999-01-01") + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + assert_eq!(send(addr, request).await.status, StatusCode::BAD_REQUEST); + let request = post(addr, Some(&hive.a.bearer), LIST.as_bytes()) + .header("mcp-protocol-version", "2025-06-18") + .body(Full::new(Bytes::from(LIST))) + .unwrap(); + assert_eq!(send(addr, request).await.status, StatusCode::OK); +} + +#[tokio::test] +async fn notifications_and_responses_are_accepted_without_a_body() { + let hive = hive().await; + for message in [ + json!({"jsonrpc": "2.0", "method": "notifications/initialized"}), + json!({"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": 1}}), + json!({"jsonrpc": "2.0", "id": 7, "result": {}}), + ] { + let reply = hive.a.message(&message).await; + assert_eq!(reply.status, StatusCode::ACCEPTED); + assert!(reply.body.is_none()); + } +} + +#[tokio::test] +async fn malformed_messages_get_json_rpc_errors() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let request = post(addr, Some(&hive.a.bearer), b"{nope") + .body(Full::new(Bytes::from_static(b"{nope"))) + .unwrap(); + let reply = send(addr, request).await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST); + assert_eq!(reply.body.unwrap()["error"]["code"], -32700); + for message in [ + json!([{"jsonrpc": "2.0", "id": 1, "method": "ping"}]), + json!({"id": 1}), + ] { + let reply = hive.a.message(&message).await; + assert_eq!(reply.status, StatusCode::BAD_REQUEST); + assert_eq!(reply.body.unwrap()["error"]["code"], -32600); + } + let response = hive.a.rpc("sampling/createMessage", json!({})).await; + assert_eq!(response["error"]["code"], -32601); +} + +#[tokio::test] +async fn the_surface_is_tools_only() { + let hive = hive().await; + assert_eq!(hive.a.rpc("ping", json!({})).await["result"], json!({})); + assert_eq!( + hive.a.rpc("resources/list", json!({})).await["result"], + json!({"resources": []}) + ); + assert_eq!( + hive.a.rpc("resources/templates/list", json!({})).await["result"], + json!({"resourceTemplates": []}) + ); + assert_eq!( + hive.a.rpc("prompts/list", json!({})).await["result"], + json!({"prompts": []}) + ); +} + +#[tokio::test] +async fn debug_output_never_carries_a_bearer() { + let hive = hive().await; + for printed in [format!("{:?}", hive.server), format!("{:?}", hive.endpoint)] { + assert!(!printed.contains(&hive.a.bearer), "{printed}"); + assert!(!printed.contains(&hive.b.bearer), "{printed}"); + } + assert!(hive.endpoint.url.starts_with("http://127.0.0.1:")); + assert!(hive.endpoint.url.ends_with("/mcp")); + assert_ne!(hive.a.bearer, hive.b.bearer); + assert_eq!(hive.a.bearer.len(), 64); +} + +#[tokio::test] +async fn idle_unauthenticated_sockets_cannot_block_a_seat() { + let hive = hive().await; + let addr = hive.server.local_addr(); + let mut idle = Vec::new(); + for _ in 0..40 { + idle.push(tokio::net::TcpStream::connect(addr).await.unwrap()); + } + let ping = tokio::time::timeout( + std::time::Duration::from_secs(3), + hive.a.rpc("ping", json!({})), + ) + .await + .expect("a seat is served while idle sockets are open"); + assert_eq!(ping["result"], json!({})); + drop(idle); +} + +#[tokio::test] +async fn shutdown_closes_the_listener() { + let hive = hive().await; + let addr = hive.server.local_addr(); + assert_eq!(hive.a.rpc("ping", json!({})).await["result"], json!({})); + hive.server.shutdown().await.unwrap(); + assert!(tokio::net::TcpStream::connect(addr).await.is_err()); +} diff --git a/crates/tinyhivemind-mcp/tests/policy.rs b/crates/tinyhivemind-mcp/tests/policy.rs new file mode 100644 index 00000000..acb93aaf --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/policy.rs @@ -0,0 +1,46 @@ +//! The host's send policy and secrets reach the calls the server dispatches. +#![allow(clippy::unwrap_used, clippy::expect_used)] +mod support; + +use serde_json::json; +use std::sync::Arc; +use support::Hive; +use tinyhivemind_exec::EnvSecrets; +use tinyhivemind_host::policy::{SendAuthorizer, SendRequest}; + +/// Refuses every direct message. +struct NoDirect; +impl SendAuthorizer for NoDirect { + fn authorize(&self, _: &str, request: &SendRequest) -> tinyhivemind_host::Result<()> { + match request { + SendRequest::Agent { .. } => Err(tinyhivemind_host::Error::SendDenied( + "no direct messages".into(), + )), + _ => Ok(()), + } + } +} + +#[tokio::test] +async fn the_send_policy_refuses_before_anything_is_sent() { + let hive = Hive::start( + |services| { + let services = services + .with_send_policy(Arc::new(NoDirect)) + .with_secrets(Arc::new(EnvSecrets)); + assert!(format!("{services:?}").contains("send_policy: true")); + services + }, + |seat, _| seat, + ) + .await; + let send = json!({"agent_id": "b", "message_id": "m1", "body": "hi", "turn": hive.turn_id(), "call": "s1"}); + let (text, failed) = hive.a.call("hivemind_send_agent", send).await; + assert!(failed && text.contains("no direct messages"), "{text}"); + let delivered = hive.coordinator.read_direct("a", "b", None).unwrap(); + assert_eq!(delivered.len(), 0); + assert_eq!( + hive.server.url(), + format!("http://{}/mcp", hive.server.local_addr()) + ); +} diff --git a/crates/tinyhivemind-mcp/tests/programs.rs b/crates/tinyhivemind-mcp/tests/programs.rs new file mode 100644 index 00000000..26e202c4 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/programs.rs @@ -0,0 +1,306 @@ +//! Executable tools: at most once per call, hooks, and the autonomy gate. +#![allow(clippy::unwrap_used, clippy::expect_used)] +mod support; + +use serde_json::{Value, json}; +use std::sync::{Arc, Mutex}; +use support::{Hive, hook, tool}; +use tinyhivemind_host::harness::{ApprovalFuture, Approver, ToolApproval, ToolDecision}; +use tinyhivemind_lang::{Access, ExecTool}; + +fn stamp() -> ExecTool { + tool( + "stamp", + "stamp", + "write", + json!({"type": "object", "properties": {"note": {"type": "string"}}}), + ) +} +fn look() -> ExecTool { + tool("look", "look", "read", json!({"type": "object"})) +} +fn identified(hive: &Hive, call: &str, mut args: Value) -> Value { + args["turn"] = json!(hive.turn_id()); + args["call"] = json!(call); + args +} +async fn with(programs: Vec, access: Access) -> Hive { + Hive::start( + |services| services, + move |seat, context| { + seat.with_context(context) + .with_programs(programs) + .with_access(access) + }, + ) + .await +} + +#[tokio::test] +async fn a_retried_executable_tool_runs_once_and_returns_the_first_result() { + let hive = with(vec![stamp()], Access::Autonomous).await; + let first = hive + .a + .call("stamp", identified(&hive, "s1", json!({"note": "x"}))) + .await; + assert_eq!(first, ("stamped stamp-1\n".into(), false)); + assert_eq!( + hive.a + .call("stamp", identified(&hive, "s1", json!({"note": "x"}))) + .await, + first + ); + assert_eq!(hive.lines("stamp.log"), 1); + // The tool saw its own arguments only: `turn` and `call` were removed. + let logged = std::fs::read_to_string(hive.workspace.path().join("stamp.log")).unwrap(); + assert_eq!( + serde_json::from_str::(&logged).unwrap(), + json!({"note": "x"}) + ); + let (text, failed) = hive + .a + .call("stamp", identified(&hive, "s1", json!({"note": "y"}))) + .await; + assert!(failed && text.contains("already made"), "{text}"); + let second = hive + .a + .call("stamp", identified(&hive, "s2", json!({"note": "x"}))) + .await; + assert_eq!(second, ("stamped stamp-2\n".into(), false)); + assert_eq!(hive.lines("stamp.log"), 2); +} + +#[tokio::test] +async fn an_executable_tool_retried_while_its_outcome_is_unknown_is_refused_and_runs_once() { + let hive = with( + vec![tool("slow", "slow", "write", json!({"type": "object"}))], + Access::Autonomous, + ) + .await; + let first = tokio::spawn({ + let (a, args) = (hive.a.clone(), identified(&hive, "s1", json!({}))); + async move { a.call("slow", args).await } + }); + while hive.lines("slow.log") == 0 { + tokio::time::sleep(std::time::Duration::from_millis(10)).await; + } + let (text, failed) = hive + .a + .call("slow", identified(&hive, "s1", json!({}))) + .await; + assert!(failed && text.contains("outcome is not known"), "{text}"); + std::fs::write(hive.workspace.path().join("release"), "").unwrap(); + assert_eq!(first.await.unwrap(), ("released\n".into(), false)); + assert_eq!(hive.lines("slow.log"), 1); + assert_eq!( + hive.a + .call("slow", identified(&hive, "s1", json!({}))) + .await, + ("released\n".into(), false) + ); + assert_eq!(hive.lines("slow.log"), 1); +} + +#[tokio::test] +async fn a_read_tool_without_a_hook_needs_no_identity_and_passes_every_gate() { + let hive = with(vec![look()], Access::ReadOnly).await; + let tools = hive.a.tools().await; + let schema = &tools.iter().find(|(name, _)| name == "look").unwrap().1; + assert!(schema["properties"].get("call").is_none(), "{schema}"); + assert_eq!( + hive.a.call("look", json!({})).await, + ("seen\n".into(), false) + ); +} + +#[tokio::test] +async fn a_retried_read_with_a_hook_reruns_neither() { + let hive = Hive::start( + |services| services, + |seat, context| { + seat.with_context(context) + .with_programs(vec![look()]) + .with_hooks(vec![ + hook("guard", "pre_tool_use", "look", "guard"), + hook("audit", "post_tool_use", "look", "audit"), + ]) + }, + ) + .await; + let tools = hive.a.tools().await; + let schema = &tools.iter().find(|(name, _)| name == "look").unwrap().1; + assert!( + schema["properties"].get("call").is_some(), + "a hooked read changes state: {schema}" + ); + let first = hive + .a + .call("look", identified(&hive, "l1", json!({}))) + .await; + assert_eq!(first, ("seen\n".into(), false)); + assert_eq!( + hive.a + .call("look", identified(&hive, "l1", json!({}))) + .await, + first + ); + assert_eq!( + ( + hive.lines("look.log"), + hive.lines("guard.log"), + hive.lines("audit.log") + ), + (1, 1, 1) + ); + let audited: Value = serde_json::from_str( + &std::fs::read_to_string(hive.workspace.path().join("audit.log")).unwrap(), + ) + .unwrap(); + assert_eq!(audited["result"], "seen\n"); + assert_eq!(audited["arguments"], json!({})); +} + +#[tokio::test] +async fn a_package_hook_denies_a_call_before_it_runs() { + let hive = Hive::start( + |services| services, + |seat, context| { + seat.with_context(context) + .with_programs(vec![stamp()]) + .with_access(Access::Autonomous) + .with_hooks(vec![hook("guard", "pre_tool_use", "st*", "guard")]) + }, + ) + .await; + let denied = hive + .a + .call( + "stamp", + identified(&hive, "s1", json!({"note": "forbidden"})), + ) + .await; + assert_eq!(denied, ("forbidden by guard".into(), true)); + assert_eq!(hive.lines("stamp.log"), 0); + assert_eq!( + hive.a + .call( + "stamp", + identified(&hive, "s1", json!({"note": "forbidden"})) + ) + .await, + denied + ); + assert_eq!(hive.lines("guard.log"), 1); + let (_, failed) = hive + .a + .call("stamp", identified(&hive, "s2", json!({"note": "fine"}))) + .await; + assert!(!failed); + assert_eq!(hive.lines("stamp.log"), 1); +} + +#[tokio::test] +async fn read_only_refuses_an_effectful_tool() { + let hive = with(vec![stamp(), look()], Access::ReadOnly).await; + let (text, failed) = hive + .a + .call("stamp", identified(&hive, "s1", json!({}))) + .await; + assert!(failed && text.contains("read_only"), "{text}"); + assert_eq!(hive.lines("stamp.log"), 0); + // Refused by policy before any hook: nothing recorded, so a retry is judged again. + let (_, failed) = hive + .a + .call("stamp", identified(&hive, "s1", json!({}))) + .await; + assert!(failed); + // Hive tools stay under send policy, not the access gate. + let post = + json!({"episode_id": hive.episode(), "body": "b", "turn": hive.turn_id(), "call": "p1"}); + assert!(!hive.a.call("hivemind_post", post).await.1); +} + +#[tokio::test] +async fn supervised_without_an_approver_refuses_an_effectful_tool() { + let hive = with(vec![stamp()], Access::Supervised).await; + let (text, failed) = hive + .a + .call("stamp", identified(&hive, "s1", json!({}))) + .await; + assert!(failed && text.contains("no approver"), "{text}"); + assert_eq!(hive.lines("stamp.log"), 0); +} + +/// Approves notes other than "no", and remembers what it was asked. +#[derive(Default)] +struct Judge(Mutex>); +impl Approver for Judge { + fn decide(&self, request: ToolApproval) -> ApprovalFuture { + let refuse = request.arguments["note"] == "no"; + self.0.lock().unwrap().push(request); + Box::pin(async move { + if refuse { + ToolDecision::Deny { + reason: "the operator said no".into(), + } + } else { + ToolDecision::Allow + } + }) + } +} + +#[tokio::test] +async fn supervised_asks_the_hosts_approver() { + let judge = Arc::new(Judge::default()); + let hive = Hive::start( + { + let judge = judge.clone(); + move |services| services.with_approver(judge) + }, + |seat, context| seat.with_context(context).with_programs(vec![stamp()]), + ) + .await; + assert!( + !hive + .a + .call("stamp", identified(&hive, "s1", json!({"note": "yes"}))) + .await + .1 + ); + let (text, failed) = hive + .a + .call("stamp", identified(&hive, "s2", json!({"note": "no"}))) + .await; + assert!(failed && text.contains("the operator said no"), "{text}"); + assert_eq!(hive.lines("stamp.log"), 1); + let asked = judge.0.lock().unwrap().clone(); + assert_eq!(asked.len(), 2); + assert_eq!( + asked[0], + ToolApproval { + seat: "a".into(), + turn_id: hive.turn_id(), + call_id: "s1".into(), + tool: "stamp".into(), + arguments: json!({"note": "yes"}), + } + ); +} + +#[tokio::test] +async fn a_failing_tool_is_an_error_result_answered_from_its_record() { + let broken = tool("broken", "missing", "write", json!({"type": "object"})); + let hive = with(vec![broken], Access::Autonomous).await; + let first = hive + .a + .call("broken", identified(&hive, "b1", json!({}))) + .await; + assert!(first.1, "{first:?}"); + assert_eq!( + hive.a + .call("broken", identified(&hive, "b1", json!({}))) + .await, + first + ); +} diff --git a/crates/tinyhivemind-mcp/tests/review.rs b/crates/tinyhivemind-mcp/tests/review.rs new file mode 100644 index 00000000..fb5dae3b --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/review.rs @@ -0,0 +1,299 @@ +//! Defects a security review found: turn changes, hang-ups, bounds, schemas. +#![allow(clippy::unwrap_used, clippy::expect_used)] +mod support; + +use serde_json::{Value, json}; +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::time::Duration; +use support::{Hive, hook, raw_post, started, tool}; +use tinyhivemind_host::harness::{ApprovalFuture, Approver, ToolApproval, ToolDecision}; +use tinyhivemind_lang::{Access, ExecTool}; +use tinyhivemind_mcp::ServerOptions; +use tokio::sync::Notify; + +fn stamp() -> ExecTool { + tool( + "stamp", + "stamp", + "write", + json!({"type": "object", "properties": {"note": {"type": "string"}}, "required": ["note"], "additionalProperties": false}), + ) +} +fn slow() -> ExecTool { + tool("slow", "slow", "write", json!({"type": "object"})) +} +fn identified(hive: &Hive, call: &str, mut args: Value) -> Value { + args["turn"] = json!(hive.turn_id()); + args["call"] = json!(call); + args +} +fn call_message(name: &str, arguments: &Value) -> Value { + json!({"jsonrpc": "2.0", "id": 9, "method": "tools/call", "params": {"name": name, "arguments": arguments}}) +} + +/// Approves everything, holding a note "hold" until released; counts asks. +#[derive(Clone, Default)] +struct Gate { + asked: Arc, + waiting: Arc, + release: Arc, +} +impl Approver for Gate { + fn decide(&self, request: ToolApproval) -> ApprovalFuture { + self.asked.fetch_add(1, Ordering::SeqCst); + let gate = self.clone(); + Box::pin(async move { + if request.arguments["note"] == "hold" { + gate.waiting.notify_one(); + gate.release.notified().await; + } + ToolDecision::Allow + }) + } +} +async fn gated(gate: &Gate, options: ServerOptions) -> Hive { + let approver = gate.clone(); + Hive::start_with( + move |services| services.with_approver(Arc::new(approver)), + |seat, context| { + seat.with_context(context) + .with_programs(vec![stamp(), slow()]) + }, + options, + ) + .await +} + +#[tokio::test] +async fn an_approval_in_flight_across_a_turn_change_runs_nothing_and_keeps_the_new_turns_record() { + let gate = Gate::default(); + let mut hive = gated(&gate, ServerOptions::default()).await; + let held = tokio::spawn({ + let (a, args) = ( + hive.a.clone(), + identified(&hive, "s1", json!({"note": "hold"})), + ); + async move { a.call("stamp", args).await } + }); + gate.waiting.notified().await; + hive.next_turn().await; + let fresh = hive + .a + .call("stamp", identified(&hive, "s1", json!({"note": "new"}))) + .await; + assert!(!fresh.1, "{fresh:?}"); + gate.release.notify_one(); + let (text, failed) = held.await.unwrap(); + assert!(failed && text.contains("not the running turn"), "{text}"); + assert_eq!(hive.lines("stamp.log"), 1); + // The new turn's record survived the stale call. + let again = hive + .a + .call("stamp", identified(&hive, "s1", json!({"note": "new"}))) + .await; + assert_eq!(again, fresh); + assert_eq!(hive.lines("stamp.log"), 1); +} + +#[tokio::test] +async fn a_retry_while_approval_is_pending_does_not_ask_twice() { + let gate = Gate::default(); + let hive = gated(&gate, ServerOptions::default()).await; + let held = tokio::spawn({ + let (a, args) = ( + hive.a.clone(), + identified(&hive, "s1", json!({"note": "hold"})), + ); + async move { a.call("stamp", args).await } + }); + gate.waiting.notified().await; + let (text, failed) = hive + .a + .call("stamp", identified(&hive, "s1", json!({"note": "hold"}))) + .await; + assert!(failed && text.contains("outcome is not known"), "{text}"); + assert_eq!(gate.asked.load(Ordering::SeqCst), 1); + gate.release.notify_one(); + assert!(!held.await.unwrap().1); + assert_eq!(hive.lines("stamp.log"), 1); +} + +#[tokio::test] +async fn a_client_hanging_up_mid_call_leaves_one_run_and_the_retry_gets_its_result() { + let hive = Hive::start( + |services| services, + |seat, context| { + seat.with_context(context) + .with_programs(vec![slow()]) + .with_access(Access::Autonomous) + }, + ) + .await; + let addr = hive.server.local_addr(); + let socket = raw_post( + addr, + &hive.a.bearer, + &call_message("slow", &identified(&hive, "s1", json!({}))), + ) + .await; + started(&hive, "slow.log").await; + drop(socket); + std::fs::write(hive.workspace.path().join("release"), "").unwrap(); + let answer = loop { + let answer = hive + .a + .call("slow", identified(&hive, "s1", json!({}))) + .await; + if !answer.0.contains("outcome is not known") { + break answer; + } + tokio::time::sleep(Duration::from_millis(20)).await; + }; + assert_eq!(answer, ("released\n".into(), false)); + assert_eq!(hive.lines("slow.log"), 1); +} + +#[tokio::test] +async fn calls_in_flight_are_bounded_per_seat_even_after_a_hang_up() { + let options = ServerOptions { + max_calls_per_seat: 1, + ..ServerOptions::default() + }; + let hive = Hive::start_with( + |services| services, + |seat, context| { + seat.with_context(context) + .with_programs(vec![ + slow(), + tool("look", "look", "read", json!({"type": "object"})), + ]) + .with_access(Access::Autonomous) + }, + options, + ) + .await; + let addr = hive.server.local_addr(); + let socket = raw_post( + addr, + &hive.a.bearer, + &call_message("slow", &identified(&hive, "s1", json!({}))), + ) + .await; + started(&hive, "slow.log").await; + drop(socket); + let waiting = tokio::spawn({ + let a = hive.a.clone(); + async move { a.call("look", json!({})).await } + }); + tokio::time::sleep(Duration::from_millis(200)).await; + assert!(!waiting.is_finished()); + assert_eq!(hive.lines("look.log"), 0); + std::fs::write(hive.workspace.path().join("release"), "").unwrap(); + assert_eq!(waiting.await.unwrap(), ("seen\n".into(), false)); +} + +#[tokio::test] +async fn arguments_outside_the_declared_schema_are_refused_before_anything_runs() { + let gate = Gate::default(); + let approver = gate.clone(); + let hive = Hive::start( + move |services| services.with_approver(Arc::new(approver)), + |seat, context| { + seat.with_context(context) + .with_programs(vec![stamp()]) + .with_hooks(vec![hook("guard", "pre_tool_use", "stamp", "guard")]) + }, + ) + .await; + for (args, field) in [ + (json!({"note": 5}), "note"), + (json!({}), "note"), + (json!({"note": "x", "extra": 1}), "extra"), + ] { + let (text, failed) = hive.a.call("stamp", identified(&hive, "s1", args)).await; + assert!(failed && text.contains(field), "{text}"); + } + assert_eq!((hive.lines("guard.log"), hive.lines("stamp.log")), (0, 0)); + assert_eq!(gate.asked.load(Ordering::SeqCst), 0); + // Nothing was recorded, so the same call with fitting arguments acts. + let (text, failed) = hive + .a + .call("stamp", identified(&hive, "s1", json!({"note": "x"}))) + .await; + assert!(!failed, "{text}"); + assert_eq!(hive.lines("stamp.log"), 1); +} + +#[tokio::test] +async fn a_seats_records_are_bounded_and_refused_rather_than_evicted() { + let options = ServerOptions { + max_records: 2, + max_record_bytes: 4096, + ..ServerOptions::default() + }; + let hive = Hive::start_with( + |services| services, + |seat, context| { + seat.with_context(context) + .with_programs(vec![stamp()]) + .with_access(Access::Autonomous) + }, + options, + ) + .await; + for call in ["s1", "s2"] { + assert!( + !hive + .a + .call("stamp", identified(&hive, call, json!({"note": "x"}))) + .await + .1 + ); + } + let (text, failed) = hive + .a + .call("stamp", identified(&hive, "s3", json!({"note": "x"}))) + .await; + assert!(failed && text.contains("records"), "{text}"); + let big = "x".repeat(5000); + let (text, failed) = hive + .a + .call("stamp", identified(&hive, "s1", json!({"note": big}))) + .await; + assert!(failed, "{text}"); + // The first record is still there, answered without running. + assert!( + !hive + .a + .call("stamp", identified(&hive, "s1", json!({"note": "x"}))) + .await + .1 + ); + assert_eq!(hive.lines("stamp.log"), 2); +} + +#[tokio::test] +async fn absent_arguments_are_empty_and_others_must_fit_even_for_a_read() { + let look = tool( + "look", + "look", + "read", + json!({"type": "object", "additionalProperties": false}), + ); + let hive = Hive::start( + |services| services, + |seat, context| seat.with_context(context).with_programs(vec![look]), + ) + .await; + let listed = hive + .a + .rpc("tools/call", json!({"name": "hivemind_list_hives"})) + .await; + assert_eq!(listed["result"]["isError"], false, "{listed}"); + let (text, failed) = hive.a.call("hivemind_list_hives", json!([])).await; + assert!(failed && text.contains("must be an object"), "{text}"); + let (text, failed) = hive.a.call("look", json!({"extra": 1})).await; + assert!(failed && text.contains("unknown argument extra"), "{text}"); + assert_eq!(hive.lines("look.log"), 0); +} diff --git a/crates/tinyhivemind-mcp/tests/seats.rs b/crates/tinyhivemind-mcp/tests/seats.rs new file mode 100644 index 00000000..0d49ef94 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/seats.rs @@ -0,0 +1,228 @@ +//! A lowered seat becomes the tools it is served, or is refused. +#![allow(clippy::unwrap_used, clippy::expect_used)] +mod support; + +use serde_json::json; +use support::{fixtures, tool}; +use tinyhivemind_exec::ExecContext; +use tinyhivemind_lang::{ + Access, LoweredSeat, LoweredSeatIntegration, PermissionSet, RuntimeSettings, Sandbox, +}; +use tinyhivemind_mcp::{Error, SeatTools}; + +fn seat(integration: LoweredSeatIntegration) -> LoweredSeat { + LoweredSeat { + id: "a".into(), + label: "A".into(), + template: "default".into(), + config: json!({}), + prompt: String::new(), + memory: None, + integration, + } +} +fn context() -> ExecContext { + ExecContext { + package_root: fixtures(), + ..ExecContext::default() + } +} + +#[test] +fn a_lowered_seat_takes_its_tools_hooks_and_the_strictest_access() { + let integration = LoweredSeatIntegration { + programs: vec![tool("stamp", "stamp", "write", json!({"type": "object"}))], + permissions: vec![PermissionSet { + id: "p".into(), + access: Access::ReadOnly, + ..PermissionSet::default() + }], + ..LoweredSeatIntegration::default() + }; + let runtime = RuntimeSettings { + autonomy: Access::Autonomous, + ..RuntimeSettings::default() + }; + let tools = SeatTools::from_lowered(&seat(integration), &runtime, context()).unwrap(); + assert_eq!(tools.seat(), "a"); + assert_eq!(tools.access(), Access::ReadOnly); + assert_eq!(tools.program_names(), ["stamp"]); +} + +#[test] +fn a_sandbox_other_than_none_is_refused() { + for sandbox in [Sandbox::ReadOnly, Sandbox::Sandboxed] { + let runtime = RuntimeSettings { + sandbox, + ..RuntimeSettings::default() + }; + let refused = SeatTools::from_lowered( + &seat(LoweredSeatIntegration::default()), + &runtime, + context(), + ); + assert!(matches!(refused, Err(Error::UnsupportedSandbox(ref s)) if s == "a")); + let integration = LoweredSeatIntegration { + permissions: vec![PermissionSet { + id: "p".into(), + sandbox, + ..PermissionSet::default() + }], + ..LoweredSeatIntegration::default() + }; + let refused = + SeatTools::from_lowered(&seat(integration), &RuntimeSettings::default(), context()); + assert!(matches!(refused, Err(Error::UnsupportedSandbox(_)))); + } +} + +#[test] +fn package_mcp_servers_are_refused_until_they_are_proxied() { + let integration = LoweredSeatIntegration { + mcp: vec![ + serde_json::from_value(json!({"id": "files", "endpoint": "files-server"})).unwrap(), + ], + ..LoweredSeatIntegration::default() + }; + let refused = + SeatTools::from_lowered(&seat(integration), &RuntimeSettings::default(), context()); + assert!(matches!(refused, Err(Error::UnsupportedMcpServers(ref s)) if s == "a")); +} + +#[test] +fn a_tool_declaring_turn_or_call_is_refused() { + for name in ["turn", "call"] { + let args = json!({"type": "object", "properties": {name: {"type": "string"}}}); + let integration = LoweredSeatIntegration { + programs: vec![tool("stamp", "stamp", "write", args)], + ..LoweredSeatIntegration::default() + }; + let refused = + SeatTools::from_lowered(&seat(integration), &RuntimeSettings::default(), context()); + assert!( + matches!(refused, Err(Error::ReservedArgument { ref tool, name: ref n }) if tool == "stamp" && n == name) + ); + } +} + +#[tokio::test] +async fn a_tool_a_permission_denies_or_shadowing_a_hive_tool_is_not_served() { + use std::sync::Arc; + use tinyhivemind_hives::{Coordinator, CoordinatorOptions, MemoryStorage}; + use tinyhivemind_mcp::{HiveToolServer, ServerOptions, Services}; + let coordinator = Coordinator::new( + "r".into(), + Arc::new(MemoryStorage::new()), + CoordinatorOptions::default(), + ) + .await + .unwrap(); + let server = HiveToolServer::start(Services::new(coordinator), ServerOptions::default()) + .await + .unwrap(); + let denied = SeatTools::new("a") + .with_programs(vec![tool( + "stamp", + "stamp", + "write", + json!({"type": "object"}), + )]) + .with_permissions(vec![PermissionSet { + id: "p".into(), + deny_tools: vec!["stamp".into(), "hivemind_broadcast".into()], + ..PermissionSet::default() + }]); + let endpoint = server.serve_seat(denied).unwrap(); + assert!(!endpoint.tools.contains("stamp")); + assert!(!endpoint.tools.contains("hivemind_broadcast")); + assert!(endpoint.tools.contains("hivemind_post")); + let allowed_only = SeatTools::new("b").with_permissions(vec![PermissionSet { + id: "p".into(), + allow_tools: Some(vec!["hivemind_read".into()]), + ..PermissionSet::default() + }]); + let endpoint = server.serve_seat(allowed_only).unwrap(); + assert_eq!(endpoint.tools.iter().collect::>(), ["hivemind_read"]); + assert!( + matches!(server.serve_seat(SeatTools::new("a")), Err(Error::DuplicateSeat(ref s)) if s == "a") + ); + let shadow = SeatTools::new("c").with_programs(vec![tool( + "hivemind_post", + "stamp", + "write", + json!({"type": "object"}), + )]); + assert!( + matches!(server.serve_seat(shadow), Err(Error::DuplicateTool(ref t)) if t == "hivemind_post") + ); + assert!(server.withdraw_seat("a")); + assert!(!server.withdraw_seat("a")); + server.serve_seat(SeatTools::new("a")).unwrap(); + server.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn a_lowered_seats_tool_allow_list_is_all_it_is_served() { + use std::sync::Arc; + use support::Client; + use tinyhivemind_hives::{Coordinator, CoordinatorOptions, MemoryStorage}; + use tinyhivemind_lang::ToolAccess; + use tinyhivemind_mcp::{HiveToolServer, ServerOptions, Services}; + let integration = LoweredSeatIntegration { + tools: ToolAccess { + allow: vec!["hivemind_post".into(), "hivemind_read".into()], + ..ToolAccess::default() + }, + programs: vec![tool("stamp", "stamp", "write", json!({"type": "object"}))], + ..LoweredSeatIntegration::default() + }; + let seat_tools = + SeatTools::from_lowered(&seat(integration), &RuntimeSettings::default(), context()) + .unwrap(); + let coordinator = Coordinator::new( + "r".into(), + Arc::new(MemoryStorage::new()), + CoordinatorOptions::default(), + ) + .await + .unwrap(); + let server = HiveToolServer::start(Services::new(coordinator), ServerOptions::default()) + .await + .unwrap(); + let endpoint = server.serve_seat(seat_tools).unwrap(); + assert_eq!( + endpoint.tools.iter().collect::>(), + ["hivemind_post", "hivemind_read", "stamp"] + ); + let client = Client::of(&server, &endpoint); + let listed: Vec = client + .tools() + .await + .into_iter() + .map(|(name, _)| name) + .collect(); + assert_eq!(listed, ["hivemind_read", "hivemind_post", "stamp"]); + let refused = client + .rpc( + "tools/call", + json!({"name": "hivemind_list_hives", "arguments": {}}), + ) + .await; + assert_eq!(refused["error"]["code"], -32602); +} + +#[test] +fn a_schema_keyword_the_server_cannot_check_is_refused() { + let args = + json!({"type": "object", "properties": {"note": {"type": "string", "pattern": "^a"}}}); + let integration = LoweredSeatIntegration { + programs: vec![tool("stamp", "stamp", "write", args)], + ..LoweredSeatIntegration::default() + }; + let refused = + SeatTools::from_lowered(&seat(integration), &RuntimeSettings::default(), context()); + assert!( + matches!(refused, Err(Error::UnsupportedSchema { ref tool, ref keyword }) if tool == "stamp" && keyword == "pattern"), + "{refused:?}" + ); +} diff --git a/crates/tinyhivemind-mcp/tests/support/README.md b/crates/tinyhivemind-mcp/tests/support/README.md new file mode 100644 index 00000000..53a4241b --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/support/README.md @@ -0,0 +1,5 @@ +# Test support + +| File | Holds | +| --- | --- | +| `mod.rs` | `send` and `Client` over hyper's HTTP/1.1 client; `Hive`, a coordinator with seats `a` and `b` whose `a` turn is held open; tool and hook builders | diff --git a/crates/tinyhivemind-mcp/tests/support/mod.rs b/crates/tinyhivemind-mcp/tests/support/mod.rs new file mode 100644 index 00000000..3d52da08 --- /dev/null +++ b/crates/tinyhivemind-mcp/tests/support/mod.rs @@ -0,0 +1,368 @@ +//! A loopback HTTP client, and a hive whose seat `a` has a turn held open. +#![allow(dead_code, unreachable_pub, clippy::expect_used, clippy::unwrap_used)] +use http_body_util::{BodyExt, Full}; +use hyper::body::Bytes; +use hyper::{HeaderMap, Request, StatusCode}; +use hyper_util::rt::TokioIo; +use serde_json::{Value, json}; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use tinyhivemind_exec::ExecContext; +use tinyhivemind_hives::{ + AgentRegistration, AgentRunner, Coordinator, CoordinatorOptions, Destination, HiveInfo, + MemoryStorage, SendMessage, TurnDisposition, TurnFuture, TurnOutcome, TurnRequest, +}; +use tinyhivemind_host::harness::ToolEndpoint; +use tinyhivemind_mcp::{HiveToolServer, SeatTools, ServerOptions, Services}; +use tokio::sync::{Notify, mpsc}; + +/// What the server answered. +#[derive(Debug)] +pub struct Reply { + pub status: StatusCode, + pub headers: HeaderMap, + pub body: Option, +} + +/// Send `request` to `addr` on a fresh connection. +pub async fn send(addr: SocketAddr, request: Request>) -> Reply { + let stream = tokio::net::TcpStream::connect(addr).await.expect("connect"); + let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) + .await + .expect("handshake"); + tokio::spawn(connection); + let response = sender.send_request(request).await.expect("response"); + let status = response.status(); + let headers = response.headers().clone(); + let bytes = response + .into_body() + .collect() + .await + .expect("body") + .to_bytes(); + let body = (!bytes.is_empty()).then(|| serde_json::from_slice(&bytes).expect("json body")); + Reply { + status, + headers, + body, + } +} + +/// A well-formed MCP POST of `body` to `addr`, with `bearer` if given. +pub fn post(addr: SocketAddr, bearer: Option<&str>, body: &[u8]) -> hyper::http::request::Builder { + let mut builder = Request::post("/mcp") + .header("host", format!("127.0.0.1:{}", addr.port())) + .header("content-type", "application/json") + .header("accept", "application/json, text/event-stream"); + if let Some(bearer) = bearer { + builder = builder.header("authorization", format!("Bearer {bearer}")); + } + let _ = body; + builder +} + +/// One seat's view of the server. +#[derive(Clone, Debug)] +pub struct Client { + pub addr: SocketAddr, + pub bearer: String, +} +impl Client { + pub fn of(server: &HiveToolServer, endpoint: &ToolEndpoint) -> Self { + Self { + addr: server.local_addr(), + bearer: endpoint.bearer().to_owned(), + } + } + /// POST one JSON-RPC message and return what came back. + pub async fn message(&self, message: &Value) -> Reply { + let body = serde_json::to_vec(message).unwrap(); + let request = post(self.addr, Some(&self.bearer), &body) + .body(Full::new(Bytes::from(body))) + .unwrap(); + send(self.addr, request).await + } + /// Call `method` and return the whole JSON-RPC response. + pub async fn rpc(&self, method: &str, params: Value) -> Value { + let reply = self + .message(&json!({"jsonrpc": "2.0", "id": 1, "method": method, "params": params})) + .await; + assert_eq!(reply.status, StatusCode::OK, "{reply:?}"); + reply.body.expect("a response") + } + /// Call tool `name` with `arguments`: its text, and whether it is an error. + pub async fn call(&self, name: &str, arguments: Value) -> (String, bool) { + let response = self + .rpc("tools/call", json!({"name": name, "arguments": arguments})) + .await; + let result = &response["result"]; + assert!(result.is_object(), "{response}"); + ( + result["content"][0]["text"].as_str().unwrap().to_owned(), + result["isError"].as_bool().unwrap(), + ) + } + /// The served tools, by name, with their input schemas. + pub async fn tools(&self) -> Vec<(String, Value)> { + let response = self.rpc("tools/list", json!({})).await; + response["result"]["tools"] + .as_array() + .unwrap() + .iter() + .map(|tool| { + ( + tool["name"].as_str().unwrap().to_owned(), + tool["inputSchema"].clone(), + ) + }) + .collect() + } +} + +/// Where a runner hands the next turn it should hold; empty, it holds none. +type Slot = Arc>>>; + +/// Holds a turn open, until told to finish, whenever its slot is armed. +struct Holds { + slot: Slot, + finish: Arc, +} +impl AgentRunner for Holds { + fn run(&self, request: TurnRequest) -> TurnFuture { + let (slot, finish) = (self.slot.clone(), self.finish.clone()); + Box::pin(async move { + let started = slot.lock().unwrap().take(); + if let Some(started) = started + && started.send(request.clone()).is_ok() + { + finish.notified().await; + } + Ok(TurnOutcome { + session_id: format!("session:{}", request.agent_id), + reply: None, + disposition: TurnDisposition::Completed, + }) + }) + } +} + +/// A coordinator with seats `a` and `b` in hive `work`, `a`'s turn held +/// open on an episode, and a server serving both seats. +pub struct Hive { + pub coordinator: Coordinator, + pub server: HiveToolServer, + pub turn: TurnRequest, + pub finish: Arc, + pub a: Client, + pub b: Client, + pub endpoint: ToolEndpoint, + pub workspace: tempfile::TempDir, + drain: + Option>>, + slot: Slot, + turns: usize, +} +impl Hive { + /// Start with `services` adjusted by `configure` and seat `a` by `seat`. + pub async fn start( + configure: impl FnOnce(Services) -> Services, + seat: impl FnOnce(SeatTools, ExecContext) -> SeatTools, + ) -> Self { + Self::start_with(configure, seat, ServerOptions::default()).await + } + pub async fn start_with( + configure: impl FnOnce(Services) -> Services, + seat: impl FnOnce(SeatTools, ExecContext) -> SeatTools, + options: ServerOptions, + ) -> Self { + let coordinator = Coordinator::new( + "runtime".into(), + Arc::new(MemoryStorage::new()), + CoordinatorOptions::default(), + ) + .await + .unwrap(); + let (started, mut requests) = mpsc::unbounded_channel(); + let finish = Arc::new(Notify::new()); + let slot: Slot = Arc::new(std::sync::Mutex::new(Some(started))); + for (id, slot) in [("a", slot.clone()), ("b", Slot::default())] { + coordinator + .register_agent(AgentRegistration { + agent_id: id.into(), + runtime_id: "runtime".into(), + runner: Arc::new(Holds { + slot, + finish: finish.clone(), + }), + }) + .await + .unwrap(); + } + coordinator + .create_hive(HiveInfo { + hive_id: "work".into(), + name: "Work".into(), + description: None, + members: vec!["a".into(), "b".into()], + }) + .await + .unwrap(); + let workspace = tempfile::tempdir().unwrap(); + let context = ExecContext { + package_root: fixtures(), + workspace: Some(workspace.path().to_path_buf()), + hive: "work".into(), + seat: "a".into(), + ..ExecContext::default() + }; + let server = HiveToolServer::start(configure(Services::new(coordinator.clone())), options) + .await + .unwrap(); + let endpoint = server + .serve_seat(seat(SeatTools::new("a"), context)) + .unwrap(); + let other = server.serve_seat(SeatTools::new("b")).unwrap(); + coordinator + .send_as_host(SendMessage { + message_id: "task".into(), + sender: String::new(), + destination: Destination::Hive("work".into()), + body: "decide".into(), + thread: None, + only_for: Vec::new(), + starters: vec!["a".into()], + }) + .await + .unwrap(); + let drain = tokio::spawn({ + let coordinator = coordinator.clone(); + async move { coordinator.run_until_idle().await } + }); + let turn = requests.recv().await.unwrap(); + Self { + a: Client::of(&server, &endpoint), + b: Client::of(&server, &other), + coordinator, + server, + turn, + finish, + endpoint, + workspace, + drain: Some(drain), + slot, + turns: 1, + } + } + /// Settle `a`'s turn, then start and hold its next one, on a direct + /// message from the host. + pub async fn next_turn(&mut self) { + self.settle().await; + let (started, mut requests) = mpsc::unbounded_channel(); + *self.slot.lock().unwrap() = Some(started); + self.turns += 1; + self.coordinator + .send_as_host(SendMessage { + message_id: format!("again-{}", self.turns), + sender: String::new(), + destination: Destination::Agent("a".into()), + body: "again".into(), + thread: None, + only_for: Vec::new(), + starters: Vec::new(), + }) + .await + .unwrap(); + self.drain = Some(tokio::spawn({ + let coordinator = self.coordinator.clone(); + async move { coordinator.run_until_idle().await } + })); + self.turn = requests.recv().await.unwrap(); + } + /// Let `a`'s turn end and the coordinator go idle. + pub async fn settle(&mut self) { + self.finish.notify_one(); + if let Some(drain) = self.drain.take() { + drain.await.unwrap().unwrap(); + } + } + /// Messages `sender` wrote with exactly `body`, in the whole transcript. + pub fn written(&self, sender: &str, body: &str) -> usize { + let rows = self.coordinator.read_transcript(None).unwrap(); + rows.iter() + .filter(|row| row.sender == sender && row.body == body) + .count() + } + /// The episode `a`'s turn works on. + pub fn episode(&self) -> String { + self.turn.episode.as_ref().unwrap().episode_id.clone() + } + /// `a`'s running turn id. + pub fn turn_id(&self) -> String { + self.turn.turn_id.clone() + } + /// Lines `file` holds in the seat's workspace. + pub fn lines(&self, file: &str) -> usize { + std::fs::read_to_string(self.workspace.path().join(file)) + .unwrap_or_default() + .lines() + .count() + } +} + +/// The fixture package root. +pub fn fixtures() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures") +} + +/// An executable tool `id` running `tools/