Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
26f: Home Assistant locks, doors and alarms always ask (#765)
Oleksandr Ivanchenkoed069fa37b3e
diff --git a/docs/approvals.md b/docs/approvals.mdindex 9608a89e..388a05d9 100644--- a/docs/approvals.md+++ b/docs/approvals.md@@ -19,6 +19,19 @@ passwords, a new space starts on `ask` instead (see below). An unknown bot alwayWhatever the mode, a call that looks like a payment shows a card, even when `smart` finds itsafe or "Always this session" was given: see [payments.md](payments.md).+Whatever the mode, on a Home Assistant MCP server (it answers `initialize` with `serverInfo.name`+`home-assistant`), a call that acts on a lock, a door, a garage door, a gate or an alarm shows a+card (since 0.9.21), approvals `off` included, the way payments do: a `domain` of `lock` or+`alarm_control_panel`; `cover` with a `device_class` of garage, door or gate, or none; or any+string argument (a name, an area, a `schedule_command` command) with the whole word lock, unlock,+door, garage, gate, alarm or disarm, plurals too, in any case. "Always this session" on such a card,+and an earlier one for the tool, cover that one call; the lights still run on their grant. Reads+(tools the server marks read-only, and `GetLiveContext`) never ask for this. The card carries+`details.home_always_ask: true` and `details.home_reason` ("Locks, doors, garage doors, gates and alarms always ask. Always allow isn’t offered for them.").+What the server is comes from what it said on kwnt's own connections, stored at its test+(`POST /api/mcp/servers/:id/test`) so it holds after a restart, never from its address; a server+kwnt never heard from asks for these calls.+Whatever the mode, a call that names kwnt's own secret files (the vault, its key, the API token)is refused and recorded as `denied`. Calls that run without a card are recorded as`auto_allowed` (`GET /api/approvals?status=auto_allowed`); under `smart` the row's@@ -132,10 +145,10 @@ Under `ask` and `smart`, "Always this session" on a claude tool's card allows th`Bash`) for that bot and conversation, also after kwnt restarts (table `always_allowed`), until theperson takes it back (`DELETE /api/kwants/:id/always-allowed`, see [mcp-api.md](mcp-api.md)). Under `smart`, API drivers'`execute_shell` is remembered the same way, per conversation; under `ask` it covers that one-command only. Neither covers a payment, and "Always this session" on a payment's card allows that-one call.+command only. Neither covers a payment or a Home Assistant lock, door or alarm, and "Always this+session" on such a card allows that one call.## Tests-`cargo test --test smart_approvals_test --test approvals_off_test --test approvals_passwords_test --test payment_floor_test`+`cargo test --test smart_approvals_test --test approvals_off_test --test approvals_passwords_test --test payment_floor_test --test home_locks_always_ask_test`and the classifier tables in `src/mcp/shell_risk.rs` (`cargo test --lib shell_risk`).diff --git a/docs/mcp-api.md b/docs/mcp-api.mdindex f1ff315e..1120ea34 100644--- a/docs/mcp-api.md+++ b/docs/mcp-api.md@@ -398,6 +398,14 @@ bot's approvals are `off`, or `smart` and the server marks the tool `readOnlyHinone, with `{}` all of them → `{"revoked": <count>, "always_allowed": [...what is left]}`.An empty body or only one of the two fields is `400`. The next call asks again, no restartneeded. Deleting the bot, or its thread or channel, removes its answers too.+ On a Home Assistant server (its test or kwnt's last connection got `serverInfo.name`+ `home-assistant`; kept per server in `mcp_server_facts`, forgotten when its address changes),+ a call that acts on a lock, a door, a garage door, a gate or an alarm (see+ [approvals.md](approvals.md)) always gets a card, with approvals `off` and over an+ `always_allow` for the tool, for chats, routines and the chat API alike. Its `details` carry+ `"home_always_ask": true` (not `always_ask`, which means a turn kwnt started) and+ `"home_reason": "Locks, doors, garage doors, gates and alarms always ask. Always allow isn’t offered for them."`; the card offers no `always_allow`, and+ one sent anyway, like `allow_once`, runs that call only and stores nothing.With Flight School on (`flight_school`), a bot below `act` for the task it works gets a card for callsits tier doesn't allow even with approvals `off` or a smart Allow, with `details.tier_reason`; see[mission-control.md](mission-control.md) §14.diff --git a/src/db/mcp_server_facts.rs b/src/db/mcp_server_facts.rsnew file mode 100644index 00000000..163d6132--- /dev/null+++ b/src/db/mcp_server_facts.rs@@ -0,0 +1,92 @@+//! What an MCP server said about itself the last time kwnt connected to it (26f): its+//! `serverInfo.name`. Home Assistant's (`home-assistant`) makes its locks, doors and alarms+//! always ask ([`crate::mcp::home_floor`]). Kept beside `mcp_servers` rather than in it, so an+//! older kwnt reading the servers table is untouched; it goes with its server, and when the+//! server's address changes.++use super::{Database, DbError};+use chrono::Utc;++const CREATE_MCP_SERVER_FACTS: &str = "CREATE TABLE IF NOT EXISTS mcp_server_facts (+ server_id TEXT PRIMARY KEY,+ reported_name TEXT,+ seen_at TIMESTAMP NOT NULL+)";++/// A deleted server takes its facts with it, whichever path deleted it.+const SERVER_GONE: &str = "CREATE TRIGGER IF NOT EXISTS mcp_server_facts_server_gone AFTER DELETE ON mcp_servers BEGIN \+ DELETE FROM mcp_server_facts WHERE server_id = OLD.id; END";++impl Database {+ pub(super) async fn migrate_mcp_server_facts(&self) -> Result<(), DbError> {+ sqlx::query(CREATE_MCP_SERVER_FACTS).execute(&self.pool).await?;+ sqlx::query(SERVER_GONE).execute(&self.pool).await?;+ Ok(())+ }++ /// Stores what server `server_id` said its name is (`None`: it sent none).+ pub async fn save_mcp_reported_name(&self, server_id: &str, reported_name: Option<&str>) -> Result<(), DbError> {+ sqlx::query(+ "INSERT INTO mcp_server_facts (server_id, reported_name, seen_at) VALUES (?, ?, ?) \+ ON CONFLICT(server_id) DO UPDATE SET reported_name = excluded.reported_name, seen_at = excluded.seen_at",+ )+ .bind(server_id)+ .bind(reported_name)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(())+ }++ /// What server `server_id` last said its name is: `None` when kwnt never stored it,+ /// `Some(None)` when the server sent none.+ pub async fn mcp_reported_name(&self, server_id: &str) -> Result<Option<Option<String>>, DbError> {+ let row: Option<(Option<String>,)> = sqlx::query_as("SELECT reported_name FROM mcp_server_facts WHERE server_id = ?")+ .bind(server_id)+ .fetch_optional(&self.pool)+ .await?;+ Ok(row.map(|(name,)| name))+ }++ /// Forgets what server `server_id` said about itself (its address changed).+ pub async fn forget_mcp_server_facts(&self, server_id: &str) -> Result<(), DbError> {+ sqlx::query("DELETE FROM mcp_server_facts WHERE server_id = ?").bind(server_id).execute(&self.pool).await?;+ Ok(())+ }+}++#[cfg(test)]+mod tests {+ use crate::db::{models::McpServer, spaces::SpaceId, Database};++ #[tokio::test]+ async fn facts_are_stored_replaced_and_go_with_their_server() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let server = McpServer {+ id: String::new(),+ name: "house".into(),+ transport: "http".into(),+ command: None,+ args: vec![],+ url: Some("http://homeassistant.lan:8123/api/mcp".into()),+ env: Default::default(),+ headers: Default::default(),+ enabled: true,+ timeout_secs: 10,+ created_at: None,+ };+ let id = db.create_mcp_server(&SpaceId::default_space(), &server).await.unwrap().id;+ assert_eq!(db.mcp_reported_name(&id).await.unwrap(), None);+ db.save_mcp_reported_name(&id, Some("home-assistant")).await.unwrap();+ assert_eq!(db.mcp_reported_name(&id).await.unwrap(), Some(Some("home-assistant".into())));+ db.save_mcp_reported_name(&id, None).await.unwrap();+ assert_eq!(db.mcp_reported_name(&id).await.unwrap(), Some(None));+ db.save_mcp_reported_name(&id, Some("home-assistant")).await.unwrap();+ db.forget_mcp_server_facts(&id).await.unwrap();+ assert_eq!(db.mcp_reported_name(&id).await.unwrap(), None);+ db.save_mcp_reported_name(&id, Some("home-assistant")).await.unwrap();+ assert!(db.delete_mcp_server(&id).await.unwrap());+ assert_eq!(db.mcp_reported_name(&id).await.unwrap(), None, "goes with its server");+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex f51c4cda..b5ddb254 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -22,6 +22,7 @@ pub mod imports;pub mod team_templates;pub mod approval_modes;pub mod always_allowed;+pub mod mcp_server_facts;pub mod parked;pub mod waiting;pub mod decisions;@@ -312,6 +313,9 @@ impl Database {// 0.9.21 25e: "Always allow" kept across restarts (add-only, outside exports). After every// step that can rebuild `kwants`, `threads` or `channels`, which would drop its triggersdb.migrate_always_allowed().await?;+ // 0.9.21 26f: what each MCP server says it is (add-only). After every step that can+ // rebuild `mcp_servers`, which would drop its trigger+ db.migrate_mcp_server_facts().await?;db.pool.close().await;// Said out loud rather than left to sqlx's default: every writer, a goal proposal@@ -1094,7 +1098,7 @@ impl Database {/// connection, so the cascade is done here rather than trusted to SQLite.pub async fn delete_mcp_server(&self, id: &str) -> Result<bool, DbError> {let mut tx = self.pool.begin().await?;- for table in ["kwant_mcp_disabled", "kwant_mcp_servers", "mcp_oauth_tokens", "mcp_oauth_clients"] {+ for table in ["kwant_mcp_disabled", "kwant_mcp_servers", "mcp_oauth_tokens", "mcp_oauth_clients", "mcp_server_facts"] {sqlx::query(&format!("DELETE FROM {table} WHERE server_id = ?")).bind(id).execute(&mut *tx)diff --git a/src/drivers/activity.rs b/src/drivers/activity.rsindex c5647cb3..f0cedf59 100644--- a/src/drivers/activity.rs+++ b/src/drivers/activity.rs@@ -967,11 +967,28 @@ pub fn summarize(name: &str, args: &Value) -> (String, Option<String>) {Some(s) => format!("Using {tool} ({s})"),None => format!("Using {tool}"),};- (shown, url.map(str::to_string))+ (shown, home_target(tool, args).or_else(|| url.map(str::to_string)))}}}+/// 26f: what a Home Assistant intent tool (`intent__Hass*`, or `homeassistant__*` other than+/// `GetLiveContext`) acts on, as a step's detail: its `name`, else its `area`, else its `domain`+/// (the first one of a list). Plain text, at most 60 characters.+fn home_target(tool: &str, args: &Value) -> Option<String> {+ let intent = tool.starts_with("intent__Hass")+ || tool.strip_prefix("homeassistant__").is_some_and(|t| t != "GetLiveContext");+ if !intent {+ return None;+ }+ fn text(v: &Value) -> Option<&str> {+ v.as_str().or_else(|| v.as_array()?.first()?.as_str()).map(str::trim).filter(|t| !t.is_empty())+ }+ let target = text(&args["name"]).or_else(|| text(&args["area"])).or_else(|| text(&args["domain"]))?;+ let plain: String = target.chars().map(|c| if c.is_control() { ' ' } else { c }).collect();+ Some(plain.chars().take(60).collect())+}+/// What an engine can't show of its thinking, as the note opening a turn's steps; `None` when/// it streams its thinking (claude's thinking blocks, codex's reasoning summaries, grok's/// thoughts). `engine` is an `EngineId::as_str`.@@ -988,6 +1005,18 @@ pub fn thinking_note(engine: &str) -> Option<&'static str> {mod tests {use super::*;+ /// 26f: a Home Assistant step says what it acts on.+ #[test]+ fn home_assistant_steps_name_what_they_act_on() {+ let detail = |tool: &str, args: Value| summarize(&format!("mcp__house__{tool}"), &args).1;+ assert_eq!(detail("intent__HassTurnOff", json!({"name": "Living room lamp"})).as_deref(), Some("Living room lamp"));+ assert_eq!(detail("intent__HassTurnOn", json!({"area": "Kitchen", "domain": ["light"]})).as_deref(), Some("Kitchen"));+ assert_eq!(detail("intent__HassTurnOff", json!({"domain": ["light"]})).as_deref(), Some("light"));+ assert_eq!(detail("homeassistant__GetLiveContext", json!({"name": "x"})), None);+ assert_eq!(detail("intent__HassTurnOff", json!({"name": "a".repeat(80)})).map(|d| d.chars().count()), Some(60));+ assert_eq!(detail("other_tool", json!({"name": "Living room lamp"})), None);+ }+/// Rigel's B1 on #294: the hold is cut on char boundaries for any script. Every prefix of/// mixed CJK, accented Latin, emoji, NBSP and U+3000 text around `key:`, `password = "a b"`/// and `Authorization: Bearer X` gets a hold index without a panic, on a char boundary.diff --git a/src/main.rs b/src/main.rsindex 9a69ab77..90b4b237 100644--- a/src/main.rs+++ b/src/main.rs@@ -96,7 +96,14 @@ pub enum Commands {/// Run a tiny MCP test server on stdin/stdout (for tests and smoke checks)#[command(hide = true)]- McpEchoServer,+ McpEchoServer {+ /// The name it answers `initialize` with (`home-assistant` to pass for Home Assistant's)+ #[arg(long)]+ server_name: Option<String>,+ /// Also serve Home Assistant-shaped tools (intent__HassTurnOff and the rest)+ #[arg(long)]+ home_tools: bool,+ },/// Run an OAuth-protected mock MCP server over HTTP (for tests and smoke checks)#[command(hide = true)]@@ -115,9 +122,9 @@ pub enum Commands {async fn main() -> Result<(), Box<dyn std::error::Error>> {let cli = Cli::parse();// Before logging starts: stdout carries the MCP protocol- if matches!(cli.command, Some(Commands::McpEchoServer)) {+ if let Some(Commands::McpEchoServer { server_name, home_tools }) = &cli.command {// A test helper that holds nothing: left dumpable so tests can find it by its environment- kwnt::mcp::echo_server::run_stdio().await?;+ kwnt::mcp::echo_server::run_stdio(server_name.as_deref(), *home_tools).await?;return Ok(());}kwnt::harden_process();@@ -230,7 +237,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {std::process::exit(1);}}- Some(Commands::McpEchoServer) => unreachable!("handled before config loading"),+ Some(Commands::McpEchoServer { .. }) => unreachable!("handled before config loading"),Some(Commands::McpOauthMockServer { .. }) => unreachable!("handled before config loading"),None => {println!("⚡ kwant bots: your team of super-intelligent bots");diff --git a/src/mcp/client.rs b/src/mcp/client.rsindex 8ac97639..944310f5 100644--- a/src/mcp/client.rs+++ b/src/mcp/client.rs@@ -99,6 +99,9 @@ enum Transport {pub struct McpClient {pub server_name: String,+ /// The stored server's id, for what kwnt notes about it ([`super::home_floor`]); empty for+ /// a server that isn't stored.+ server_id: String,pub server_info: Value,timeout: Duration,next_id: AtomicI64,@@ -158,6 +161,7 @@ impl McpClient {};let mut client = Self {server_name: server.name.clone(),+ server_id: server.id.clone(),server_info: Value::Null,timeout,next_id: AtomicI64::new(1),@@ -294,6 +298,8 @@ impl McpClient {).await?;self.server_info = result.get("serverInfo").cloned().unwrap_or(Value::Null);+ // 26f: what the server says it is decides whether its locks always ask+ super::home_floor::note_server_info(&self.server_id, &self.server_info);if let Transport::Http(ref http) = self.transport {let version = result["protocolVersion"].as_str().unwrap_or(PROTOCOL_VERSION).to_string();*http.protocol_version.lock().unwrap() = Some(version);@@ -325,6 +331,7 @@ impl McpClient {break;}}+ super::home_floor::note_tools(&self.server_id, tools.iter().map(|t| (t.name.as_str(), t.read_only)));Ok(tools)}diff --git a/src/mcp/echo_server.rs b/src/mcp/echo_server.rsindex d18cefd2..3f11764b 100644--- a/src/mcp/echo_server.rs+++ b/src/mcp/echo_server.rs@@ -5,6 +5,12 @@//! `crash` (exits mid-call) and `peek` (a fixed reading). `echo` is marked read-only; `add` is//! marked destructive, so it asks; `peek` carries Home Assistant's read-only shape//! (`readOnlyHint` and `destructiveHint` both true), which counts as read-only.+//!+//! `--home-tools` adds Home Assistant-shaped tools (26f): `homeassistant__GetLiveContext`+//! (read-only), `intent__HassTurnOn` and `intent__HassTurnOff` `{name, area, domain,+//! device_class}`, and `homeassistant__schedule_command {command}`; each answers that it did it.+//! `--server-name home-assistant` makes the server say it is Home Assistant's; it says+//! `kwnt-echo` otherwise.use serde_json::{json, Value};use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};@@ -30,12 +36,34 @@ fn tools() -> Value {])}+fn home_tools_list() -> Vec<Value> {+ let target = json!({+ "name": {"type": "string"}, "area": {"type": "string"},+ "domain": {"type": "array", "items": {"type": "string"}},+ "device_class": {"type": "array", "items": {"type": "string"}},+ });+ let obj = |props: Value| json!({"type": "object", "properties": props});+ json!([+ {"name": "homeassistant__GetLiveContext", "description": "Reads the current state of the house.",+ "inputSchema": obj(json!({})), "annotations": {"readOnlyHint": true}},+ {"name": "intent__HassTurnOn", "description": "Turns on, opens or locks a device.", "inputSchema": obj(target.clone())},+ {"name": "intent__HassTurnOff", "description": "Turns off, closes or unlocks a device.", "inputSchema": obj(target)},+ {"name": "homeassistant__schedule_command", "description": "Runs a command later.",+ "inputSchema": obj(json!({"command": {"type": "string"}}))},+ ])+ .as_array()+ .cloned()+ .unwrap_or_default()+}+fn text_result(text: String, is_error: bool) -> Value {json!({"content": [{"type": "text", "text": text}], "isError": is_error})}async fn call(name: &str, args: &Value) -> Value {match name {+ "homeassistant__GetLiveContext" => text_result("Live context: the lights are on, the front door is locked".into(), false),+ "intent__HassTurnOn" | "intent__HassTurnOff" | "homeassistant__schedule_command" => text_result(format!("done: {name} {args}"), false),"echo" => text_result(args["text"].as_str().unwrap_or("").to_string(), false),"add" => {let sum = args["a"].as_f64().unwrap_or(0.0) + args["b"].as_f64().unwrap_or(0.0);@@ -62,8 +90,17 @@ async fn call(name: &str, args: &Value) -> Value {}}-/// Serves MCP on stdin/stdout until stdin closes.-pub async fn run_stdio() -> std::io::Result<()> {+/// Serves MCP on stdin/stdout until stdin closes, saying it is `server_name` (default+/// `kwnt-echo`), with the Home Assistant-shaped tools too when `home_tools`.+pub async fn run_stdio(server_name: Option<&str>, home_tools: bool) -> std::io::Result<()> {+ let server_name = server_name.unwrap_or("kwnt-echo");+ let listed = {+ let mut all = tools();+ if home_tools {+ all.as_array_mut().unwrap().extend(home_tools_list());+ }+ all+ };let mut lines = BufReader::new(tokio::io::stdin()).lines();let mut stdout = tokio::io::stdout();while let Some(line) = lines.next_line().await? {@@ -73,10 +110,10 @@ pub async fn run_stdio() -> std::io::Result<()> {"initialize" => json!({"protocolVersion": msg["params"]["protocolVersion"].as_str().unwrap_or(super::client::PROTOCOL_VERSION),"capabilities": {"tools": {}},- "serverInfo": {"name": "kwnt-echo", "version": env!("CARGO_PKG_VERSION")},+ "serverInfo": {"name": server_name, "version": env!("CARGO_PKG_VERSION")},}),"ping" => json!({}),- "tools/list" => json!({"tools": tools()}),+ "tools/list" => json!({"tools": listed}),"tools/call" => call(msg["params"]["name"].as_str().unwrap_or(""), &msg["params"]["arguments"]).await,_ => {let err = json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": "method not found"}});diff --git a/src/mcp/home_floor.rs b/src/mcp/home_floor.rsnew file mode 100644index 00000000..777a1e5f--- /dev/null+++ b/src/mcp/home_floor.rs@@ -0,0 +1,256 @@+//! 26f: on a Home Assistant server, a call that acts on a lock, a door, a garage door, a gate or+//! an alarm always shows the card, in every approval mode (approvals off too), and "Always allow"+//! never covers it. Home Assistant controls everything through a few generic tools+//! (`intent__HassTurnOff` unlocks a lock, `intent__HassTurnOn`/`HassSetPosition` open covers,+//! `homeassistant__schedule_command` runs a free-text command later inside Home Assistant), so a+//! grant given for the lights would otherwise cover the front door too.+//!+//! What a server is comes from what it says it is: the `serverInfo.name` of its `initialize`+//! answer, `home-assistant` for Home Assistant's MCP server. kwnt notes it here each time one of+//! its own connections finishes the handshake (a turn's tools, the gateway, a server test), with+//! the tools the server marks read-only; the server test also stores it with the server's row+//! (`mcp_server_facts`), so it is known after a restart too.+//!+//! This module only matches; `server::mcp_runtime` asks it and shows the card.++use serde_json::Value;+use std::collections::{HashMap, HashSet};+use std::sync::{LazyLock, Mutex};++/// The `serverInfo.name` Home Assistant's MCP server answers `initialize` with.+pub const HOME_ASSISTANT: &str = "home-assistant";++/// The card's one-line reason. Product copy is Mira's.+pub const REASON: &str = "Locks, doors, garage doors, gates and alarms always ask. Always allow isn’t offered for them.";++/// Words that make a call sensitive, matched as whole words, case-insensitive, in any string+/// argument. `_`, `.`, `-` and spaces all split words, so `lock.front_door` matches too.+const WORDS: &[&str] = &[+ "lock", "locks", "unlock", "unlocks", "door", "doors", "garage", "garages", "gate", "gates", "alarm", "alarms", "disarm",+ "disarms",+];++/// Home Assistant domains that always count.+const DOMAINS: &[&str] = &["lock", "alarm_control_panel"];++/// Cover device classes that count (`cover` with no device class counts too: it can mean every+/// cover in the house, garage doors included).+const COVER_CLASSES: &[&str] = &["garage", "door", "gate"];++/// Home Assistant's own read of the house. It is a read whatever its arguments say, also on a+/// version that doesn't mark it read-only the way kwnt reads the hints.+const READS: &[&str] = &["GetLiveContext", "GetDateTime"];++/// What kwnt saw of one server on its last connection in this run.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct Seen {+ /// Its `serverInfo.name`, trimmed; `None` when it sent none.+ pub reported: Option<String>,+ /// The tools it marks read-only, once it listed them.+ pub read_only: Option<HashSet<String>>,+}++static SEEN: LazyLock<Mutex<HashMap<String, Seen>>> = LazyLock::new(Default::default);++fn seen_map() -> std::sync::MutexGuard<'static, HashMap<String, Seen>> {+ SEEN.lock().unwrap_or_else(|e| e.into_inner())+}++/// The `serverInfo.name` in an `initialize` answer's `serverInfo`, trimmed and at most 100+/// characters; `None` when there is none.+pub fn reported_name(server_info: &Value) -> Option<String> {+ let name = server_info.get("name")?.as_str()?.trim();+ (!name.is_empty()).then(|| name.chars().take(100).collect())+}++/// Notes what server `server_id` said it is on a handshake. A new handshake forgets the tools+/// listed before it.+pub fn note_server_info(server_id: &str, server_info: &Value) {+ if server_id.is_empty() {+ return;+ }+ seen_map().insert(server_id.to_string(), Seen { reported: reported_name(server_info), read_only: None });+}++/// Notes which of server `server_id`'s tools are read-only, after it listed them.+pub fn note_tools<'a>(server_id: &str, tools: impl IntoIterator<Item = (&'a str, bool)>) {+ if server_id.is_empty() {+ return;+ }+ let read_only = tools.into_iter().filter(|(_, ro)| *ro).map(|(name, _)| name.to_string()).collect();+ seen_map().entry(server_id.to_string()).or_default().read_only = Some(read_only);+}++/// What kwnt saw of server `server_id` in this run, if it connected to it.+pub fn seen(server_id: &str) -> Option<Seen> {+ seen_map().get(server_id).cloned()+}++/// Forgets what kwnt saw of `server_id` (its address changed, or it was deleted).+pub fn forget(server_id: &str) {+ seen_map().remove(server_id);+}++/// Whether a server that reported `name` is Home Assistant's.+pub fn is_home_assistant(name: &str) -> bool {+ name.trim().eq_ignore_ascii_case(HOME_ASSISTANT)+}++/// Whether `tool` (the name after the server, `intent__HassTurnOff`) is one of Home Assistant's+/// own reads ([`READS`]), with or without its `homeassistant__` prefix.+pub fn is_home_read(tool: &str) -> bool {+ let bare = tool.rsplit("__").next().unwrap_or(tool);+ READS.contains(&bare)+}++fn words(text: &str) -> impl Iterator<Item = &str> {+ text.split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty())+}++/// Whether `text` holds one of [`WORDS`] as a whole word, in any case.+pub fn names_a_lock(text: &str) -> bool {+ words(text).any(|w| WORDS.iter().any(|k| w.eq_ignore_ascii_case(k)))+}++fn strings(v: &Value) -> Vec<&str> {+ match v {+ Value::String(s) => vec![s.as_str()],+ Value::Array(items) => items.iter().filter_map(Value::as_str).collect(),+ _ => Vec::new(),+ }+}++fn any_string(v: &Value, depth: usize, hit: &dyn Fn(&str) -> bool) -> bool {+ if depth > 8 {+ return false;+ }+ match v {+ Value::String(s) => hit(s),+ Value::Array(items) => items.iter().any(|i| any_string(i, depth + 1, hit)),+ Value::Object(map) => map.values().any(|i| any_string(i, depth + 1, hit)),+ _ => false,+ }+}++/// Whether a call with `args` acts on a lock, a door, a garage door, a gate or an alarm, from its+/// arguments alone: a `domain` of `lock` or `alarm_control_panel`; `cover` with a `device_class`+/// of garage, door or gate, or with none; or any string argument (a name, an area, a free-text+/// command) naming one of [`WORDS`]. A false match only shows one more card.+pub fn sensitive_args(args: &Value) -> bool {+ let domains = strings(&args["domain"]);+ if domains.iter().any(|d| DOMAINS.iter().any(|k| d.trim().eq_ignore_ascii_case(k))) {+ return true;+ }+ if domains.iter().any(|d| d.trim().eq_ignore_ascii_case("cover")) {+ let classes = strings(&args["device_class"]);+ if classes.is_empty() || classes.iter().any(|c| COVER_CLASSES.iter().any(|k| c.trim().eq_ignore_ascii_case(k))) {+ return true;+ }+ }+ any_string(args, 0, &names_a_lock)+}++/// What a sensitive call on a server needs to be known about it, for [`decide`].+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ServerKind {+ HomeAssistant,+ Other,+ /// kwnt never got its `serverInfo` (it couldn't connect): treated as Home Assistant's, the+ /// safe side, but only for a call whose arguments name a lock, a door or an alarm.+ Unknown,+}++impl ServerKind {+ pub fn of(reported: Option<&str>) -> Self {+ match reported {+ Some(name) if is_home_assistant(name) => Self::HomeAssistant,+ Some(_) => Self::Other,+ None => Self::Unknown,+ }+ }+}++/// Whether a call to `tool` with `args` on a server of `kind` must always ask. `read_only` is+/// whether the server marks the tool read-only (`None` when kwnt doesn't know): reads never ask+/// for this reason.+pub fn decide(kind: ServerKind, tool: &str, args: &Value, read_only: Option<bool>) -> bool {+ if kind == ServerKind::Other || read_only == Some(true) || is_home_read(tool) {+ return false;+ }+ sensitive_args(args)+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn locks_doors_gates_and_alarms_are_sensitive_and_lights_are_not() {+ for args in [+ json!({"domain": ["lock"]}),+ json!({"domain": "lock"}),+ json!({"domain": ["alarm_control_panel"]}),+ json!({"domain": ["cover"], "device_class": ["garage"]}),+ json!({"domain": ["cover"], "device_class": "gate"}),+ json!({"domain": ["cover"]}),+ json!({"name": "Front door"}),+ json!({"name": "Garage"}),+ json!({"name": "Back door lock"}),+ json!({"name": "lock.front_door"}),+ json!({"area": "GATES"}),+ json!({"command": "unlock the back door"}),+ json!({"command": "Disarm the alarm at 7"}),+ json!({"data": {"nested": ["the garage, please"]}}),+ ] {+ assert!(sensitive_args(&args), "{args}");+ }+ for args in [+ json!({"domain": ["light"]}),+ json!({"name": "Living room lamp"}),+ json!({"area": "Kitchen", "domain": ["light"]}),+ json!({"domain": ["cover"], "device_class": ["blind"]}),+ json!({"name": "Doorbell camera light"}),+ json!({"name": "Blocked drain"}),+ json!({"name": "Gateway router"}),+ json!({"brightness": 40}),+ json!({}),+ ] {+ assert!(!sensitive_args(&args), "{args}");+ }+ }++ #[test]+ fn only_home_assistant_or_an_unknown_server_asks_and_reads_never_do() {+ let lock = json!({"domain": ["lock"]});+ assert!(decide(ServerKind::HomeAssistant, "intent__HassTurnOff", &lock, None));+ assert!(decide(ServerKind::HomeAssistant, "intent__HassTurnOff", &lock, Some(false)));+ assert!(decide(ServerKind::Unknown, "intent__HassTurnOff", &lock, None));+ assert!(!decide(ServerKind::Other, "intent__HassTurnOff", &lock, None), "a server that isn't Home Assistant");+ assert!(!decide(ServerKind::HomeAssistant, "intent__HassTurnOff", &json!({"domain": ["light"]}), None));+ assert!(!decide(ServerKind::HomeAssistant, "homeassistant__GetLiveContext", &lock, Some(false)), "HA's own read");+ assert!(!decide(ServerKind::HomeAssistant, "todo_get_items", &json!({"name": "Door list"}), Some(true)), "a read-only tool");+ assert!(decide(ServerKind::HomeAssistant, "homeassistant__schedule_command", &json!({"command": "unlock the back door"}), None));+ }++ #[test]+ fn the_server_says_what_it_is() {+ assert_eq!(ServerKind::of(reported_name(&json!({"name": " home-assistant ", "version": "1"})).as_deref()), ServerKind::HomeAssistant);+ assert_eq!(ServerKind::of(Some("Home-Assistant")), ServerKind::HomeAssistant);+ assert_eq!(ServerKind::of(Some("kwnt-echo")), ServerKind::Other);+ assert_eq!(ServerKind::of(reported_name(&json!({"name": ""})).as_deref()), ServerKind::Unknown);+ assert_eq!(ServerKind::of(reported_name(&Value::Null).as_deref()), ServerKind::Unknown);++ note_server_info("srv-unit-1", &json!({"name": "home-assistant"}));+ note_tools("srv-unit-1", [("homeassistant__GetLiveContext", true), ("intent__HassTurnOff", false)]);+ let s = seen("srv-unit-1").unwrap();+ assert_eq!(s.reported.as_deref(), Some("home-assistant"));+ assert!(s.read_only.as_ref().unwrap().contains("homeassistant__GetLiveContext"));+ assert!(!s.read_only.as_ref().unwrap().contains("intent__HassTurnOff"));+ // A new handshake starts over+ note_server_info("srv-unit-1", &json!({"name": "other"}));+ assert_eq!(seen("srv-unit-1").unwrap().read_only, None);+ forget("srv-unit-1");+ assert_eq!(seen("srv-unit-1"), None);+ }+}diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex 62a1b4cb..3574b792 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -8,6 +8,7 @@ pub mod client;pub mod composio;pub mod echo_server;pub mod fetch_risk;+pub mod home_floor;pub mod oauth;pub mod payment_floor;pub mod prod_floor;diff --git a/src/server/mcp_routes.rs b/src/server/mcp_routes.rsindex 6a6a2948..631a5a49 100644--- a/src/server/mcp_routes.rs+++ b/src/server/mcp_routes.rs@@ -122,6 +122,13 @@ pub async fn update_server(// Tokens and registrations belong to the old addressstate.db.clear_mcp_oauth(&id).await.map_err(db_err)?;}+ if updated.is_some()+ && (server.url != existing.url || server.transport != existing.transport || server.command != existing.command || server.args != existing.args)+ {+ // Another address or program may be another server: what it said it was is asked again (26f)+ state.db.forget_mcp_server_facts(&id).await.map_err(db_err)?;+ mcp::home_floor::forget(&id);+ }match updated {Some(s) => Ok(Json(view(&state, &s).await)),None => Err(err(StatusCode::NOT_FOUND, "MCP server not found")),@@ -130,6 +137,7 @@ pub async fn update_server(pub async fn delete_server(State(state): State<AppState>, Path(id): Path<String>) -> ApiResult<Value> {if state.db.delete_mcp_server(&id).await.map_err(db_err)? {+ mcp::home_floor::forget(&id);Ok(Json(json!({ "status": "deleted" })))} else {Err(err(StatusCode::NOT_FOUND, "MCP server not found"))@@ -203,6 +211,13 @@ pub(super) async fn run_test(state: &AppState, stored: &McpServer) -> Value {super::mcp_runtime::remove_mcp_cwd(state, &token).await;}+ if let Ok((server_info, _)) = &result {+ // 26f: stored with the server, so its locks ask also before kwnt next connects to it+ let reported = mcp::home_floor::reported_name(server_info);+ if let Err(e) = state.db.save_mcp_reported_name(id, reported.as_deref()).await {+ tracing::warn!(error = %e, server = %stored.name, "could not store what the MCP server said it is");+ }+ }let mut outcome = match result {Ok((server_info, tools)) => json!({ "ok": true, "server_info": server_info, "tools": tools }),Err((McpError::Unauthorized { .. }, _)) if token_use != TokenUse::UserHeader => {diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rsindex 09abd3dc..92735e79 100644--- a/src/server/mcp_runtime.rs+++ b/src/server/mcp_runtime.rs@@ -318,6 +318,9 @@ impl BrokerApprover {if req.payment.is_some() || mcp::payment_floor::reason(req, None).is_some() {return None;}+ if home_floor(&self.db, req).await {+ return None;+ }if self.tier_gate(req).await.is_some() || super::dev::floor::for_call(&self.db, req).await.is_some() {return None;}@@ -364,7 +367,10 @@ impl BrokerApprover {// (a deploy, a push to the watched branch, a migration, a marked connection) always asks,// and "always allow" covers just that call.let floor = super::dev::floor::for_call(&self.db, &req).await;- let forced = payment.is_some() || tier.is_some() || floor.is_some();+ // 26f: on a Home Assistant server, a lock, a door, a garage door, a gate or an alarm+ // always asks, in every mode, and "always allow" covers just that call+ let home = home_floor(&self.db, &req).await;+ let forced = payment.is_some() || tier.is_some() || floor.is_some() || home;// The two audit calls only record the audit in kwnt (risks the person closes), so they// follow approvals off even in an always-asking audit turn; its other tools still asklet audit_call = req.server == mcp::SELF_SERVER_NAME@@ -414,6 +420,11 @@ impl BrokerApprover {if let Some((_, card)) = &floor {details["prod_floor"] = card.clone();}+ // Its own field: `always_ask` means a turn kwnt started on its own (Ada, Nov 16)+ if home {+ details["home_always_ask"] = json!(true);+ details["home_reason"] = json!(mcp::home_floor::REASON);+ }// Telegram keeps these cards link-only (Q-G6), each with its own line: a turn that read// outside text (an injected request is likeliest there), and a turn kwant started on its// own rather than from the person's message.@@ -460,6 +471,8 @@ impl BrokerApprover {tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, reason = ?payment, "a payment: asking whatever the approvals say");} else if let Some((f, _)) = &floor {tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, kind = ?f.kind, "can reach production: asking whatever the approvals say");+ } else if home {+ tracing::info!(kwant = %req.kwant_id, tool = %req.tool_name, "a lock, a door or an alarm: asking whatever the approvals say");} else if !off && !self.always_ask && self.broker.is_allowed_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await {return (ApprovalOutcome::Allowed, "allowed", None);}@@ -537,6 +550,8 @@ impl BrokerApprover {Ok(Ok(ApprovalDecision::AlwaysAllowSession)) if payment.is_some() => ApprovalOutcome::Allowed,// So does a production step'sOk(Ok(ApprovalDecision::AlwaysAllowSession)) if floor.is_some() => ApprovalOutcome::Allowed,+ // And a lock's, a door's or an alarm's (26f)+ Ok(Ok(ApprovalDecision::AlwaysAllowSession)) if home => ApprovalOutcome::Allowed,Ok(Ok(ApprovalDecision::AlwaysAllowSession)) => {self.broker.allow_for_session(&req.kwant_id, &self.conversation, &req.tool_name).await;ApprovalOutcome::Allowed@@ -577,6 +592,49 @@ impl BrokerApprover {}}+/// 26f: whether `req` acts on a lock, a door, a garage door, a gate or an alarm on a Home+/// Assistant server ([`mcp::home_floor`]), so it always asks. What the server is comes from what+/// it said on kwnt's last connection to it in this run, else from what its last test stored; one+/// learned in this run is stored too. A server kwnt never heard from counts as Home Assistant's+/// (the safe side), and only for a call whose arguments name one of those things.+pub async fn home_floor(db: &Database, req: &ToolApprovalRequest) -> bool {+ if req.builtin.is_some() || req.server.is_empty() || req.server == mcp::SELF_SERVER_NAME {+ return false;+ }+ // Cheap first: most calls name no lock, door or alarm+ if !mcp::home_floor::sensitive_args(&req.arguments) {+ return false;+ }+ let server = match db.list_active_mcp_servers_for_kwant(&req.kwant_id).await {+ Ok(servers) => servers.into_iter().find(|s| s.name == req.server),+ // Can't tell which server it is: ask+ Err(e) => {+ tracing::warn!(error = %e, "could not read the bot's MCP servers; a lock or a door asks");+ return true;+ }+ };+ let Some(server) = server else { return false };+ let seen = mcp::home_floor::seen(&server.id);+ let stored = db.mcp_reported_name(&server.id).await.unwrap_or_else(|e| {+ tracing::warn!(error = %e, "could not read what the MCP server said it is");+ None+ });+ if let Some(s) = &seen {+ if stored.as_ref() != Some(&s.reported) {+ if let Err(e) = db.save_mcp_reported_name(&server.id, s.reported.as_deref()).await {+ tracing::warn!(error = %e, "could not store what the MCP server said it is");+ }+ }+ }+ let kind = match (&seen, &stored) {+ (Some(s), _) => mcp::home_floor::ServerKind::of(s.reported.as_deref()),+ (None, Some(name)) => mcp::home_floor::ServerKind::of(name.as_deref()),+ (None, None) => mcp::home_floor::ServerKind::Unknown,+ };+ let read_only = seen.and_then(|s| s.read_only).map(|tools| tools.contains(&req.tool));+ mcp::home_floor::decide(kind, &req.tool, &req.arguments, read_only)+}+fn max_tool_iterations(setting: Option<String>) -> usize {setting.or_else(|| std::env::var("KWNT_MCP_MAX_TOOL_ITERATIONS").ok())@@ -665,7 +723,11 @@ pub async fn resume_late_approval(state: &AppState, ticket_id: &str, decision: Alet conversation = thread_id.clone().or_else(|| channel_id.clone()).or_else(|| chat["direct_kwant_id"].as_str().map(str::to_string)).unwrap_or_else(|| kwant.id.clone());state.broker.grant_once(&kwant.id, &conversation, &approval.tool_name, &arguments).await;// A payment's "always allow" covers the one call (the payment floor, D8). So does a production step's (plan §3.5)- if decision == ApprovalDecision::AlwaysAllowSession && details.get("payment_reason").is_none() && details.get("prod_floor").is_none() {+ if decision == ApprovalDecision::AlwaysAllowSession+ && details.get("payment_reason").is_none()+ && details.get("prod_floor").is_none()+ && details.get("home_always_ask").is_none()+ {state.broker.allow_for_session(&kwant.id, &conversation, &approval.tool_name).await;}let depth = match &thread_id {@@ -1221,6 +1283,14 @@ async fn decide(session: &PermissionSession, args: &Value, smart: bool, grant: ONone => mcp::SmartVerdict::Ask("kwnt couldn't check whether this MCP tool is read-only".into()),});}+ // 26f: a call that names a lock, a door or an alarm needs to know what the server is;+ // kwnt connects to it once in this turn to hear it say so+ if server != mcp::SELF_SERVER_NAME+ && mcp::home_floor::sensitive_args(&input)+ && session.ctx.servers.iter().any(|s| s.name == server && mcp::home_floor::seen(&s.id).is_none())+ {+ let _ = session.tool_session().await;+ }(server, tool, None)}_ if tool_name.is_empty() || tool_name.starts_with("mcp__") => {diff --git a/tests/home_locks_always_ask_test.rs b/tests/home_locks_always_ask_test.rsnew file mode 100644index 00000000..3867c215--- /dev/null+++ b/tests/home_locks_always_ask_test.rs@@ -0,0 +1,234 @@+//! 26f: on a Home Assistant MCP server (it answers `initialize` as `home-assistant`), a call that+//! acts on a lock, a door, a garage door, a gate or an alarm always shows the card: with an+//! "Always allow" for the tool, and with approvals off. Its "Always allow" and "Allow once" cover+//! that call only. The lights still run on their grant, a server that isn't Home Assistant's is+//! unaffected, and Home Assistant's read of the house (GetLiveContext) still runs.++mod common;++use common::*;+use kwnt::{+ broker::ApprovalDecision,+ db::{models::McpServer, spaces::SpaceId},+ drivers::events::RuntimeEvent,+ mcp::{home_floor, ApprovalOutcome, McpClient, ToolApprovalRequest, ToolApprover},+ server::mcp_runtime::BrokerApprover,+};+use serde_json::{json, Value};+use std::{collections::BTreeMap, sync::Arc, time::Duration};++const OFF: &str = "mcp__house__intent__HassTurnOff";++fn approver(env: &Env, conversation: &str, timeout: Duration) -> BrokerApprover {+ BrokerApprover {+ db: env.state.db.clone(),+ data_dir: env.state.config.data_dir.clone(),+ broker: env.state.broker.clone(),+ events: env.state.event_sender.clone(),+ timeout,+ conversation: conversation.to_string(),+ chat: None,+ always_ask: false,+ strict_ask: false,+ started_by: None,+ }+}++fn mcp_call(env: &Env, tool_name: &str, arguments: Value) -> ToolApprovalRequest {+ let (server, tool) = tool_name.strip_prefix("mcp__").and_then(|r| r.split_once("__")).unwrap();+ ToolApprovalRequest {+ kwant_id: env.a.clone(),+ kwant_name: "A".into(),+ turn_id: "t-home".into(),+ tool_name: tool_name.into(),+ server: server.into(),+ tool: tool.into(),+ arguments,+ builtin: None,+ smart: None,+ payment: None,+ }+}++/// Registers the echo server with the Home Assistant-shaped tools as bot A's `house`, saying it+/// is `server_name`; `connect` has kwnt connect to it once, as a turn would.+async fn house(env: &Env, server_name: &str, connect: bool) -> McpServer {+ let server = McpServer {+ id: String::new(),+ name: "house".into(),+ transport: "stdio".into(),+ command: Some(env!("CARGO_BIN_EXE_kwnt").into()),+ args: vec!["mcp-echo-server".into(), "--home-tools".into(), "--server-name".into(), server_name.into()],+ url: None,+ env: BTreeMap::new(),+ headers: BTreeMap::new(),+ enabled: true,+ timeout_secs: 10,+ created_at: None,+ };+ let server = env.state.db.create_mcp_server(&SpaceId::default_space(), &server).await.unwrap();+ env.state.db.set_kwant_mcp_servers(&env.a, std::slice::from_ref(&server.id)).await.unwrap();+ if connect {+ let mut client = McpClient::connect(&server, None).await.unwrap();+ let tools = client.list_tools().await.unwrap();+ assert!(tools.iter().any(|t| t.name == "intent__HassTurnOff"));+ client.shutdown().await;+ }+ server+}++/// Makes the call, waits for its card and answers it with `decision`: the outcome and the card.+async fn answer_card(env: &Env, conversation: &str, req: ToolApprovalRequest, decision: ApprovalDecision) -> (ApprovalOutcome, Value) {+ let mut events = env.state.event_sender.subscribe();+ let a = Arc::new(approver(env, conversation, Duration::from_secs(10)));+ let pending = tokio::spawn(async move { a.decide(req).await });+ let (id, details) = loop {+ if let RuntimeEvent::ApprovalRequired { id, details, .. } = events.recv().await.unwrap() {+ break (id, details);+ }+ };+ assert!(env.state.broker.resolve(&id, decision).await);+ (pending.await.unwrap(), details)+}++/// Asks without anyone answering: `false` means it ran without a card.+async fn asks(env: &Env, conversation: &str, req: ToolApprovalRequest) -> bool {+ match approver(env, conversation, Duration::from_millis(300)).decide(req).await {+ ApprovalOutcome::Allowed => false,+ ApprovalOutcome::Unanswered => true,+ other => panic!("unexpected outcome {other:?}"),+ }+}++async fn stored_grants(env: &Env) -> i64 {+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", env.state.config.data_dir.join("kwnt.db").display())).await.unwrap();+ let (n,): (i64,) = sqlx::query_as("SELECT COUNT(*) FROM always_allowed").fetch_one(&pool).await.unwrap();+ pool.close().await;+ n+}++fn the_locks(env: &Env) -> Vec<ToolApprovalRequest> {+ vec![+ mcp_call(env, OFF, json!({"domain": ["lock"]})),+ mcp_call(env, OFF, json!({"name": "Front door"})),+ mcp_call(env, OFF, json!({"name": "Garage"})),+ mcp_call(env, "mcp__house__homeassistant__schedule_command", json!({"command": "unlock the back door"})),+ ]+}++#[tokio::test]+async fn the_lights_run_on_their_grant_and_locks_doors_and_alarms_always_ask() {+ let env = setup().await;+ house(&env, "home-assistant", true).await;+ env.state.db.set_kwant_approvals(&env.a, "ask").await.unwrap();+ let a = env.a.clone();+ env.state.broker.allow_for_session(&a, &a, OFF).await;+ env.state.broker.allow_for_session(&a, &a, "mcp__house__homeassistant__schedule_command").await;++ assert!(!asks(&env, &a, mcp_call(&env, OFF, json!({"domain": ["light"]}))).await, "the lights run on the grant");+ for req in the_locks(&env) {+ assert!(asks(&env, &a, req.clone()).await, "with the grant: {}", req.arguments);+ }+ env.state.db.set_kwant_approvals(&env.a, "off").await.unwrap();+ assert!(!asks(&env, &a, mcp_call(&env, OFF, json!({"domain": ["light"]}))).await);+ for req in the_locks(&env) {+ assert!(asks(&env, &a, req.clone()).await, "with approvals off: {}", req.arguments);+ }+ env.state.db.set_kwant_approvals(&env.a, "smart").await.unwrap();+ for req in the_locks(&env) {+ assert!(asks(&env, &a, req.clone()).await, "asking only when risky: {}", req.arguments);+ }+}++#[tokio::test]+async fn the_card_says_why_and_neither_answer_leaves_a_grant() {+ let env = setup().await;+ house(&env, "home-assistant", true).await;+ env.state.db.set_kwant_approvals(&env.a, "off").await.unwrap();+ let a = env.a.clone();+ let front_door = || mcp_call(&env, OFF, json!({"name": "Front door"}));++ let (outcome, card) = answer_card(&env, &a, front_door(), ApprovalDecision::AlwaysAllowSession).await;+ assert_eq!(outcome, ApprovalOutcome::Allowed, "that one call runs");+ assert_eq!(card["home_always_ask"], json!(true), "{card}");+ assert_eq!(card["home_reason"], json!(home_floor::REASON), "{card}");+ assert!(card.get("always_ask").is_none_or(|v| v != &json!(true)), "its own field: {card}");+ assert!(!env.state.broker.is_allowed_for_session(&a, &a, OFF).await, "always allow made no grant");+ assert_eq!(stored_grants(&env).await, 0);+ assert!(asks(&env, &a, front_door()).await, "the next call asks again");++ let (outcome, _) = answer_card(&env, &a, front_door(), ApprovalDecision::AllowOnce).await;+ assert_eq!(outcome, ApprovalOutcome::Allowed);+ assert!(!env.state.broker.is_allowed_for_session(&a, &a, OFF).await, "allow once made no grant");+ assert_eq!(stored_grants(&env).await, 0);+ assert!(asks(&env, &a, front_door()).await);++ let (outcome, _) = answer_card(&env, &a, front_door(), ApprovalDecision::Deny).await;+ assert_eq!(outcome, ApprovalOutcome::Denied);+}++#[tokio::test]+async fn a_server_that_isnt_home_assistant_is_unaffected() {+ let env = setup().await;+ house(&env, "kwnt-echo", true).await;+ env.state.db.set_kwant_approvals(&env.a, "ask").await.unwrap();+ let a = env.a.clone();+ env.state.broker.allow_for_session(&a, &a, OFF).await;+ env.state.broker.allow_for_session(&a, &a, "mcp__house__homeassistant__schedule_command").await;+ for req in the_locks(&env) {+ assert!(!asks(&env, &a, req.clone()).await, "same tool, other server, the grant covers it: {}", req.arguments);+ }+ env.state.db.set_kwant_approvals(&env.a, "off").await.unwrap();+ for req in the_locks(&env) {+ assert!(!asks(&env, &a, req.clone()).await, "approvals off: {}", req.arguments);+ }+}++#[tokio::test]+async fn get_live_context_still_runs() {+ let env = setup().await;+ house(&env, "home-assistant", true).await;+ env.state.db.set_kwant_approvals(&env.a, "off").await.unwrap();+ let a = env.a.clone();+ let read = |args: Value| mcp_call(&env, "mcp__house__homeassistant__GetLiveContext", args);+ assert!(!asks(&env, &a, read(json!({}))).await);+ assert!(!asks(&env, &a, read(json!({"name": "Front door"}))).await, "a read, whatever it names");+}++#[tokio::test]+async fn what_the_server_said_at_its_test_is_kept_and_an_unknown_server_asks() {+ let env = setup().await;+ let server = house(&env, "home-assistant", false).await;+ env.state.db.set_kwant_approvals(&env.a, "off").await.unwrap();+ let a = env.a.clone();+ let lock = || mcp_call(&env, OFF, json!({"domain": ["lock"]}));+ let light = || mcp_call(&env, OFF, json!({"domain": ["light"]}));++ // Never heard from: a lock asks (the safe side); the lights don't+ assert_eq!(env.state.db.mcp_reported_name(&server.id).await.unwrap(), None);+ assert!(asks(&env, &a, lock()).await);+ assert!(!asks(&env, &a, light()).await);++ // Its test stores what it said, and that holds after kwnt forgets this run's connections+ let (s, v) = call(&env.app, "POST", &format!("/api/mcp/servers/{}/test", server.id), None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["ok"], json!(true), "{v}");+ assert_eq!(env.state.db.mcp_reported_name(&server.id).await.unwrap(), Some(Some("home-assistant".into())));+ home_floor::forget(&server.id);+ assert!(asks(&env, &a, lock()).await, "stored: still Home Assistant's");++ // A server stored as something else is unaffected+ env.state.db.save_mcp_reported_name(&server.id, Some("kwnt-echo")).await.unwrap();+ assert!(!asks(&env, &a, lock()).await);++ // A new address forgets what the old one said+ let (s, v) = call(+ &env.app,+ "PUT",+ &format!("/api/mcp/servers/{}", server.id),+ Some(json!({"name": "house", "transport": "stdio", "command": env!("CARGO_BIN_EXE_kwnt"), "args": ["mcp-echo-server"], "enabled": true})),+ )+ .await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(env.state.db.mcp_reported_name(&server.id).await.unwrap(), None);+}