Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

28m home-server-known-first: a Home Assistant server counts from the first turn (#805)

Oleksandr Ivanchenko349d13f3fa94
diff --git a/src/mcp/home_floor.rs b/src/mcp/home_floor.rs
index aa394ac4..75be2573 100644
--- a/src/mcp/home_floor.rs
+++ b/src/mcp/home_floor.rs
@@ -96,6 +96,46 @@ pub fn is_home_assistant(name: &str) -> bool {
name.trim().eq_ignore_ascii_case(HOME_ASSISTANT)
}
+/// 28m: the paths Home Assistant serves its MCP server at: `/api/mcp` (streamable HTTP) and
+/// `/mcp_server/sse` (the older SSE endpoint).
+const PATHS: &[&str] = &["/api/mcp", "/mcp_server/sse"];
+
+/// 28m: whether `address` is an `http(s)` URL at Home Assistant's own MCP path ([`PATHS`]), also
+/// under a prefix a proxy adds (`https://example.com/ha/api/mcp`); a trailing `/`, the query and
+/// the fragment don't matter. Only a hint, for a server kwnt never heard from: what a server says
+/// it is always wins.
+pub fn at_home_assistant_path(address: &str) -> bool {
+ let Some((scheme, rest)) = address.trim().split_once("://") else {
+ return false;
+ };
+ if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") {
+ return false;
+ }
+ let rest = rest.split(['?', '#']).next().unwrap_or_default();
+ let Some(slash) = rest.find('/') else {
+ return false;
+ };
+ let path = rest[slash..].trim_end_matches('/');
+ PATHS.iter().any(|p| path.len().checked_sub(p.len()).and_then(|at| path.get(at..)).is_some_and(|end| end.eq_ignore_ascii_case(p)))
+}
+
+/// 28m: whether a server counts as Home Assistant's for the delivery check. `heard` is what kwnt
+/// heard it say it is (on a connection in this run, else at its last test): `Some(None)` when it
+/// gave no name, `None` when kwnt never heard from it. A server kwnt never heard from counts when
+/// its address is at Home Assistant's MCP path: its `url`, or, for a `stdio` server (a proxy such
+/// as `mcp-proxy`), one of its arguments (`--url=…` too). Counting a server that isn't means at
+/// most one "did that change really happen?" continuation, the safe side; missing one lets a
+/// false "Unlocking the front door now." through.
+pub fn counts_as_home_assistant(heard: Option<Option<&str>>, transport: &str, url: Option<&str>, args: &[String]) -> bool {
+ match heard {
+ Some(name) => name.is_some_and(is_home_assistant),
+ None if transport == "stdio" => {
+ args.iter().any(|a| at_home_assistant_path(a) || a.split_once('=').is_some_and(|(_, v)| at_home_assistant_path(v)))
+ }
+ None => url.is_some_and(at_home_assistant_path),
+ }
+}
+
/// 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 {
@@ -323,6 +363,67 @@ mod tests {
assert_eq!(live_context_hint("homeassistant__GetDateTime", &json!({"name": "x"}), "ok"), None);
}
+ /// 28m: Home Assistant's own MCP paths, also behind a proxy's prefix; other paths aren't.
+ #[test]
+ fn home_assistants_mcp_path_is_known_by_its_address() {
+ for address in [
+ "http://homeassistant.local:8123/api/mcp",
+ "http://192.168.1.20:8123/api/mcp/",
+ "https://abcd1234.ui.nabu.casa/api/mcp",
+ "HTTPS://ha.example.com/API/MCP?x=1",
+ "https://example.com/homeassistant/api/mcp#top",
+ "http://homeassistant.local:8123/mcp_server/sse",
+ " http://localhost:8123/api/mcp ",
+ ] {
+ assert!(at_home_assistant_path(address), "{address}");
+ }
+ for address in [
+ "http://homeassistant.local:8123/",
+ "http://homeassistant.local:8123",
+ "http://127.0.0.1:7777/api/mcp/gateway",
+ "http://127.0.0.1:7777/api/mcp/self",
+ "https://mcp.notion.com/mcp",
+ "https://example.com/xapi/mcp",
+ "https://example.com/?next=/api/mcp",
+ "ftp://ha.local/api/mcp",
+ "/api/mcp",
+ "api/mcp",
+ "",
+ "http://ha.local/ápi/mcp",
+ "http://ha.local/é/ab/mcp",
+ ] {
+ assert!(!at_home_assistant_path(address), "{address}");
+ }
+ }
+
+ /// 28m: what a server said it is always wins; only one kwnt never heard from goes by its
+ /// address (its url, or a proxy's argument for a stdio server).
+ #[test]
+ fn a_server_never_heard_from_counts_by_its_address() {
+ let ha = Some("http://homeassistant.local:8123/api/mcp");
+ let other = Some("https://mcp.notion.com/mcp");
+ let none: &[String] = &[];
+ // Never heard from: the address decides
+ assert!(counts_as_home_assistant(None, "http", ha, none));
+ assert!(!counts_as_home_assistant(None, "http", other, none));
+ assert!(!counts_as_home_assistant(None, "http", None, none));
+ // Heard from: what it said, whatever its address
+ assert!(counts_as_home_assistant(Some(Some("home-assistant")), "http", other, none));
+ assert!(counts_as_home_assistant(Some(Some(" Home-Assistant ")), "http", None, none));
+ assert!(!counts_as_home_assistant(Some(Some("kwnt-echo")), "http", ha, none));
+ assert!(!counts_as_home_assistant(Some(None), "http", ha, none), "it gave no name: not counted");
+ // A stdio proxy to Home Assistant (mcp-proxy, as Home Assistant's docs set it up)
+ let proxy: Vec<String> = ["--transport=streamablehttp", "--stateless", "http://localhost:8123/api/mcp"].map(String::from).into();
+ assert!(counts_as_home_assistant(None, "stdio", None, &proxy));
+ let flag: Vec<String> = ["--url=http://localhost:8123/mcp_server/sse"].map(String::from).into();
+ assert!(counts_as_home_assistant(None, "stdio", None, &flag));
+ let notes: Vec<String> = ["mcp-server-notes", "--root", "/home/me/api/mcp"].map(String::from).into();
+ assert!(!counts_as_home_assistant(None, "stdio", None, &notes));
+ assert!(!counts_as_home_assistant(Some(Some("mcp-proxy")), "stdio", None, &proxy), "heard from: what it said");
+ // A stdio server's url field isn't its address
+ assert!(!counts_as_home_assistant(None, "stdio", ha, none));
+ }
+
/// 27e round 2 (Mira): the miss hint goes with every filtered read that ended in an error
/// (Home Assistant's own "No exposed entities…", bad arguments, Home Assistant down) and with
/// each call, even after a whole read worked, so it claims only what all of those share.
diff --git a/src/server/mcp_runtime.rs b/src/server/mcp_runtime.rs
index badd3b58..b86fd41e 100644
--- a/src/server/mcp_runtime.rs
+++ b/src/server/mcp_runtime.rs
@@ -636,15 +636,19 @@ pub async fn credit_floor(db: &Database, req: &ToolApprovalRequest) -> Option<St
/// 27e: the names (in kwant) of the turn's `servers` that are Home Assistant's: by what each
/// said on kwnt's last connection to it in this run, else by what its last test stored. A server
-/// kwnt never heard from isn't counted (the delivery check only adds a continuation for them).
+/// kwnt never heard from counts when its address is Home Assistant's MCP path (28m: on the Claude
+/// CLI the CLI connects, not kwnt, so a new server is often one kwnt never heard from), see
+/// [`mcp::home_floor::counts_as_home_assistant`]. The delivery check only adds a continuation.
pub async fn home_server_names(db: &Database, servers: &[McpServer]) -> Vec<String> {
let mut names = Vec::new();
for server in servers.iter().filter(|s| s.name != mcp::SELF_SERVER_NAME && s.name != mcp::RESERVED_SERVER_NAME) {
- let reported = match mcp::home_floor::seen(&server.id) {
- Some(seen) => seen.reported,
- None => db.mcp_reported_name(&server.id).await.ok().flatten().flatten(),
+ let heard = match mcp::home_floor::seen(&server.id) {
+ Some(seen) => Some(seen.reported),
+ // A read that failed is a server kwnt can't place: its address decides (the safe side)
+ None => db.mcp_reported_name(&server.id).await.ok().flatten(),
};
- if reported.is_some_and(|n| mcp::home_floor::is_home_assistant(&n)) {
+ let heard = heard.as_ref().map(Option::as_deref);
+ if mcp::home_floor::counts_as_home_assistant(heard, &server.transport, server.url.as_deref(), &server.args) {
names.push(server.name.clone());
}
}
diff --git a/tests/home_server_known_first_test.rs b/tests/home_server_known_first_test.rs
new file mode 100644
index 00000000..c411293d
--- /dev/null
+++ b/tests/home_server_known_first_test.rs
@@ -0,0 +1,106 @@
+//! 28m home-server-known-first: on the Claude CLI engine the CLI connects to a bot's MCP servers,
+//! not kwnt, so a Home Assistant server added without a test is one kwnt never heard from. It
+//! still counts for the delivery check when its address is Home Assistant's MCP path, so the
+//! first false "Unlocking … now." with no tool call gets the continuation. What a server said it
+//! is wins over its address. Full turns on the fake claude (tests/common).
+
+mod common;
+
+use common::*;
+use kwnt::{
+ db::models::McpServer,
+ mcp::home_floor,
+ server::mcp_runtime::home_server_names,
+};
+use serde_json::json;
+use std::{collections::BTreeMap, time::Duration};
+
+/// A closed port: nothing answers there, so kwnt never hears from the server.
+async fn server(env: &Env, name: &str, url: &str) -> McpServer {
+ let space = env.state.db.space_of_kwant(&env.a).await.unwrap().unwrap();
+ let server = McpServer {
+ id: String::new(),
+ name: name.into(),
+ transport: "http".into(),
+ command: None,
+ args: vec![],
+ url: Some(url.into()),
+ env: BTreeMap::new(),
+ headers: BTreeMap::new(),
+ enabled: true,
+ timeout_secs: 5,
+ created_at: None,
+ };
+ let server = env.state.db.create_mcp_server(&space, &server).await.unwrap();
+ env.state.db.set_kwant_mcp_servers(&env.a, std::slice::from_ref(&server.id)).await.unwrap();
+ server
+}
+
+/// The continuation kwnt sends after `claim` (see `delivery_check::home_change_prompt`).
+fn continued(claim: &str) -> String {
+ format!("Your reply says \"{claim}\", but no Home Assistant step changed anything in this turn")
+}
+
+/// Asks bot A (fake claude) something whose first answer is `claim`, and waits for that reply.
+async fn claim_once(env: &Env, tag: &str, claim: &str) {
+ plan_replies(tag, &[claim, "Nothing changed: it stays locked."]);
+ send_direct(env, &env.a, &format!("unlock it REPLYSEQ:{tag}"), json!({})).await;
+ wait_reply(env, &env.a, claim).await;
+}
+
+#[tokio::test]
+async fn a_never_tested_home_assistant_server_counts_from_the_first_claim() {
+ let env = setup().await;
+ let ha = server(&env, "house", "http://127.0.0.1:9/api/mcp").await;
+ // kwnt never heard from it: no test, no call
+ assert_eq!(home_floor::seen(&ha.id), None);
+ assert_eq!(env.state.db.mcp_reported_name(&ha.id).await.unwrap(), None);
+ assert_eq!(home_server_names(&env.state.db, std::slice::from_ref(&ha)).await, vec!["house".to_string()]);
+
+ let claim = "Unlocking the shed door now.";
+ claim_once(&env, "hskf_ha", claim).await;
+ let asked = continued(claim);
+ wait_for("the home-change continuation", || {
+ let n = invocations_with(&asked).len();
+ async move { n > 0 }
+ })
+ .await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ assert_eq!(invocations_with(&asked).len(), 1, "one continuation");
+}
+
+#[tokio::test]
+async fn a_never_tested_server_elsewhere_is_not_home_assistants() {
+ let env = setup().await;
+ let other = server(&env, "notes", "http://127.0.0.1:9/mcp").await;
+ assert!(home_server_names(&env.state.db, std::slice::from_ref(&other)).await.is_empty());
+
+ let claim = "Unlocking the barn door now.";
+ claim_once(&env, "hskf_other", claim).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ assert!(invocations_with(&continued(claim)).is_empty(), "no continuation");
+}
+
+#[tokio::test]
+async fn what_a_server_said_wins_over_its_address() {
+ let env = setup().await;
+ let ha_path = server(&env, "board", "http://127.0.0.1:9/api/mcp").await;
+ // Its test said it is something else: its address doesn't matter any more
+ env.state.db.save_mcp_reported_name(&ha_path.id, Some("kwnt-echo")).await.unwrap();
+ assert!(home_server_names(&env.state.db, std::slice::from_ref(&ha_path)).await.is_empty());
+ // It gave no name at all: not counted either
+ env.state.db.save_mcp_reported_name(&ha_path.id, None).await.unwrap();
+ assert!(home_server_names(&env.state.db, std::slice::from_ref(&ha_path)).await.is_empty());
+
+ let claim = "Unlocking the cellar door now.";
+ claim_once(&env, "hskf_said", claim).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ assert!(invocations_with(&continued(claim)).is_empty(), "no continuation");
+
+ // What kwnt heard on a connection in this run wins over what was stored, both ways
+ home_floor::note_server_info(&ha_path.id, &json!({"name": "home-assistant"}));
+ assert_eq!(home_server_names(&env.state.db, std::slice::from_ref(&ha_path)).await, vec!["board".to_string()]);
+ home_floor::note_server_info(&ha_path.id, &json!({"name": "kwnt-echo"}));
+ assert!(home_server_names(&env.state.db, std::slice::from_ref(&ha_path)).await.is_empty());
+ home_floor::forget(&ha_path.id);
+}