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.

Home Assistant: reads run without asking; LAN sign-in error names the header (26a) (#760)

Oleksandr Ivanchenko57a7ac89fb20
diff --git a/docs/approvals.md b/docs/approvals.md
index 6e09a7ff..109662ff 100644
--- a/docs/approvals.md
+++ b/docs/approvals.md
@@ -112,8 +112,9 @@ earlier in the same turn. Choose `ask` for bots or folders you don't trust.
Known gaps, left as they are: options that follow symlinks (`grep -R`, `rg -L`, `find -L`,
`ls -R`, `zip -r`) run without a card, so a symlink already in the folder that points out of
it can be read through them.
-- **MCP tools** the server marks `readOnlyHint: true` without `destructiveHint: true`. That is
- the server's own claim. If kwnt can't check it, the call asks.
+- **MCP tools** the server marks `readOnlyHint: true`. As the MCP spec says, `destructiveHint`
+ counts only when `readOnlyHint` is false, so a tool marked both (Home Assistant's reads, like
+ GetLiveContext) runs too. That is the server's own claim. If kwnt can't check it, the call asks.
**kwnt itself always asks.** kwnt's person-only routes take no token from this computer, so a
request to kwnt from a bot could turn approvals off or answer its own cards. A curl, wget or
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index e142e9c1..950661bb 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -377,8 +377,9 @@ bad app name; 409 when Composio isn't added, has no key, the key is refused, or
### Approvals
Every MCP tool call needs approval through the permission broker, for both agent kinds, unless the
-bot's approvals are `off`, or `smart` and the server marks the tool `readOnlyHint: true` without
-`destructiveHint: true` (see [approvals.md](approvals.md)):
+bot's approvals are `off`, or `smart` and the server marks the tool `readOnlyHint: true`, whatever
+`destructiveHint` says (the MCP spec reads it only when `readOnlyHint` is false; see
+[approvals.md](approvals.md)):
1. kwnt emits the SSE event
`{"type":"ApprovalRequired","data":{"id":"<ticket>","tool_name":"mcp__echo__echo","details":{"source":"mcp","server":"echo","tool":"echo","arguments":{…},"kwant_id":"…","kwant_name":"…"}}}`
diff --git a/frontend/src/components/McpServersModal.tsx b/frontend/src/components/McpServersModal.tsx
index 78eed9dd..baef8be0 100644
--- a/frontend/src/components/McpServersModal.tsx
+++ b/frontend/src/components/McpServersModal.tsx
@@ -1140,6 +1140,10 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClos
<p className="mt-1.5 text-[11px] text-zinc-500">
Servers that need sign-in (like Notion) don’t need a header. Use <span className="text-zinc-300">Connect</span> on the server after saving.
</p>
+ <p className="mt-1 text-[11px] text-zinc-500">
+ On your home network (Home Assistant on http://…), sign-in won’t work: add{' '}
+ <span className="text-zinc-300 font-mono">Authorization = Bearer &lt;your token&gt;</span> here instead.
+ </p>
</div>
</>
)}
diff --git a/site-src/docs-approvals.html b/site-src/docs-approvals.html
index a0180f11..6529447c 100644
--- a/site-src/docs-approvals.html
+++ b/site-src/docs-approvals.html
@@ -40,7 +40,7 @@ card_art: avatar:qa
<ul>
<li><strong>Shell commands</strong> in the bot's folder that a fail-closed allowlist recognises as safe: file and text tools like <code>ls</code>, <code>cat</code> or <code>jq</code>, and build tools like <code>cargo</code>, <code>npm</code>, <code>make</code> or <code>git</code>, with checks. Network tools, <code>sudo</code>, containers, <code>git push</code>, package installs, <code>npx</code>, inline code, and any path outside the folder still ask.</li>
<li><strong>Reads</strong> outside the folder, unless they touch system data or anything that looks like a credential: <code>.ssh</code>, <code>.aws</code>, <code>.env</code> files, key files, browser profiles, shell histories and more.</li>
- <li><strong>MCP tools</strong> the server marks read-only and not destructive.</li>
+ <li><strong>MCP tools</strong> the server marks read-only.</li>
</ul>
<p id="packages">Since 0.7.4, adding a package the project doesn't list yet asks first, because it downloads code that runs on your computer: <code>npm install &lt;name&gt;</code>, <code>pnpm add</code>, <code>yarn add</code>, <code>bun add</code>, <code>cargo add</code>, <code>uv add</code>, <code>poetry add</code>, <code>go get</code> and <code>dotnet add package</code>. An option or a workspace name in front can't hide it. A plain <code>npm install</code> of what the project already lists still runs on its own. Starters like <code>npm create vite</code>, <code>npx</code>, <code>npm exec</code> and <code>npm x</code> ask too.</p>
<figure>
diff --git a/site-src/docs-mcp.html b/site-src/docs-mcp.html
index 1165cfad..c74a99fd 100644
--- a/site-src/docs-mcp.html
+++ b/site-src/docs-mcp.html
@@ -39,7 +39,7 @@ card_art: avatar:tech_lead
<div class="note warn"><strong>Composio keeps those app sign-ins on its own servers,</strong> not in kwant's vault.</div>
<h2 id="approvals">Approvals for tools</h2>
-<p>MCP tool calls follow the bot's <a href="approvals.html#modes">approval mode</a>. Under "Ask only when risky", tools the server marks read-only and not destructive run without a card. That's the server's own claim, and if kwant can't check it, the call asks. Every call a bot makes is recorded on its reply.</p>
+<p>MCP tool calls follow the bot's <a href="approvals.html#modes">approval mode</a>. Under "Ask only when risky", tools the server marks read-only run without a card, like Home Assistant's reads. That's the server's own claim, and if kwant can't check it, the call asks. Every call a bot makes is recorded on its reply.</p>
<h2 id="api">HTTP API</h2>
<div class="table-wrap"><table>
diff --git a/src/mcp/client.rs b/src/mcp/client.rs
index 16716859..8ac97639 100644
--- a/src/mcp/client.rs
+++ b/src/mcp/client.rs
@@ -50,8 +50,9 @@ pub struct McpTool {
pub name: String,
pub description: Option<String>,
pub input_schema: Value,
- /// The server marks it read-only (`readOnlyHint: true`, not `destructiveHint: true`). The
- /// server's own claim: kwnt can't check it.
+ /// The server marks it read-only (`readOnlyHint: true`). As the MCP spec says,
+ /// `destructiveHint` means something only when `readOnlyHint` is false, so it's ignored here
+ /// (Home Assistant sends both on every read). The server's own claim: kwnt can't check it.
#[serde(default)]
pub read_only: bool,
}
@@ -62,6 +63,16 @@ pub struct ToolCallResult {
pub is_error: bool,
}
+/// One `tools/list` entry, or `None` when it has no name.
+fn tool_from_list_entry(t: &Value) -> Option<McpTool> {
+ Some(McpTool {
+ name: t["name"].as_str()?.to_string(),
+ description: t["description"].as_str().map(str::to_string),
+ input_schema: t.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object"})),
+ read_only: t["annotations"]["readOnlyHint"].as_bool() == Some(true),
+ })
+}
+
type Pending = Arc<StdMutex<HashMap<i64, oneshot::Sender<Value>>>>;
struct StdioTransport {
@@ -308,16 +319,7 @@ impl McpClient {
};
let result = self.request("tools/list", params).await?;
let page = result["tools"].as_array().ok_or_else(|| McpError::Protocol("tools/list without tools".into()))?;
- for t in page {
- let Some(name) = t["name"].as_str() else { continue };
- tools.push(McpTool {
- name: name.to_string(),
- description: t["description"].as_str().map(str::to_string),
- input_schema: t.get("inputSchema").cloned().unwrap_or_else(|| json!({"type": "object"})),
- read_only: t["annotations"]["readOnlyHint"].as_bool() == Some(true)
- && t["annotations"]["destructiveHint"].as_bool() != Some(true),
- });
- }
+ tools.extend(page.iter().filter_map(tool_from_list_entry));
cursor = result["nextCursor"].as_str().map(str::to_string);
if cursor.is_none() {
break;
@@ -500,3 +502,38 @@ impl Drop for StdioTransport {
}
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn tools(fixture: &str) -> Vec<McpTool> {
+ let v: Value = serde_json::from_str(fixture).unwrap();
+ v["tools"].as_array().unwrap().iter().filter_map(tool_from_list_entry).collect()
+ }
+
+ fn read_only(tools: &[McpTool], name: &str) -> bool {
+ tools.iter().find(|t| t.name == name).unwrap_or_else(|| panic!("no {name}")).read_only
+ }
+
+ #[test]
+ fn home_assistant_reads_are_read_only_even_with_destructive_hint() {
+ let ha = tools(include_str!("../../tests/fixtures/mcp/home-assistant-tools.json"));
+ assert!(read_only(&ha, "GetLiveContext"), "readOnlyHint wins over destructiveHint (MCP spec)");
+ assert!(read_only(&ha, "HassGetState"));
+ assert!(!read_only(&ha, "HassTurnOn"), "no readOnlyHint asks");
+ assert!(!read_only(&ha, "HassTurnOff"), "idempotent isn't read-only");
+ }
+
+ #[test]
+ fn only_a_true_read_only_hint_counts() {
+ let t = tools(r#"{"tools": [
+ {"name": "a", "annotations": {"readOnlyHint": "true"}},
+ {"name": "b", "annotations": {"readOnlyHint": false, "destructiveHint": false}},
+ {"name": "c"},
+ {"description": "no name"}
+ ]}"#);
+ assert_eq!(t.len(), 3);
+ assert!(t.iter().all(|t| !t.read_only), "{t:?}");
+ }
+}
diff --git a/src/mcp/echo_server.rs b/src/mcp/echo_server.rs
index e913e48b..d18cefd2 100644
--- a/src/mcp/echo_server.rs
+++ b/src/mcp/echo_server.rs
@@ -1,9 +1,10 @@
//! A tiny stdio MCP server, run with the hidden `kwnt mcp-echo-server` subcommand. It exists so
//! tests and smoke checks have a real MCP server without Python, Node or network access.
//!
-//! Tools: `echo {text}`, `add {a, b}`, `sleep {ms}`, `env {name}` (reads its own environment)
-//! and `crash` (exits mid-call). `echo` is marked read-only; `add` claims both read-only and
-//! destructive, so it counts as not read-only.
+//! Tools: `echo {text}`, `add {a, b}`, `sleep {ms}`, `env {name}` (reads its own environment),
+//! `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.
use serde_json::{json, Value};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
@@ -16,13 +17,16 @@ fn tools() -> Value {
"annotations": {"readOnlyHint": true}},
{"name": "add", "description": "Adds two numbers.",
"inputSchema": obj(json!({"a": {"type": "number"}, "b": {"type": "number"}}), json!(["a", "b"])),
- "annotations": {"readOnlyHint": true, "destructiveHint": true}},
+ "annotations": {"destructiveHint": true}},
{"name": "sleep", "description": "Waits for the given milliseconds, then answers.",
"inputSchema": obj(json!({"ms": {"type": "integer"}}), json!(["ms"]))},
{"name": "env", "description": "Returns the value of one of this server's environment variables.",
"inputSchema": obj(json!({"name": {"type": "string"}}), json!(["name"]))},
{"name": "crash", "description": "Exits the server without answering.",
"inputSchema": obj(json!({}), json!([]))},
+ {"name": "peek", "description": "Returns a fixed reading, like a sensor.",
+ "inputSchema": obj(json!({}), json!([])),
+ "annotations": {"readOnlyHint": true, "destructiveHint": true, "openWorldHint": false, "idempotentHint": false}},
])
}
@@ -49,6 +53,7 @@ async fn call(name: &str, args: &Value) -> Value {
Err(_) => text_result(format!("{var} is not set"), true),
}
}
+ "peek" => text_result("21.4".into(), false),
"crash" => {
eprintln!("mcp-echo-server: crashing on request");
std::process::exit(3);
diff --git a/src/mcp/oauth.rs b/src/mcp/oauth.rs
index 008f6a02..50f7db9e 100644
--- a/src/mcp/oauth.rs
+++ b/src/mcp/oauth.rs
@@ -200,6 +200,21 @@ pub fn acceptable_endpoint(endpoint: &str) -> bool {
}
}
+/// Said when a sign-in endpoint is plain http off this computer (a Home Assistant on the home
+/// network, say). There's no sign-in over plain http there, since the token would cross the network
+/// unencrypted; a Bearer header works instead. Keeps "must use https" for anything matching on it.
+pub const LAN_HTTP_SIGN_IN: &str = "This server's sign-in must use https (plain http works only on this computer). \
+For a server on your home network, like Home Assistant, add a header instead: Authorization = Bearer <token>, \
+then Test connection.";
+
+/// Why discovery refuses `endpoint` (one [`acceptable_endpoint`] said no to): plain http names
+/// the header way; anything else keeps `other`.
+fn refused_endpoint(endpoint: &str, other: &str) -> OAuthError {
+ let plain_http = Url::parse(endpoint).is_ok_and(|u| u.scheme() == "http");
+ let message = if plain_http { LAN_HTTP_SIGN_IN } else { other };
+ OAuthError::Discovery(message.to_string())
+}
+
fn random_token() -> String {
// Two v4 UUIDs: 244 random bits from the OS generator, 64 unreserved characters
format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple())
@@ -431,7 +446,7 @@ pub async fn discover(
.map(str::to_string)
.unwrap_or_else(|| origin.clone());
if !acceptable_endpoint(&issuer) {
- return Err(OAuthError::Discovery("the authorization server must use https".into()));
+ return Err(refused_endpoint(&issuer, "the authorization server must use https"));
}
let resource = resource_meta
.as_ref()
@@ -477,7 +492,7 @@ pub async fn discover(
.flatten()
{
if !acceptable_endpoint(endpoint) {
- return Err(OAuthError::Discovery("the server's sign-in endpoints must use https".into()));
+ return Err(refused_endpoint(endpoint, "the server's sign-in endpoints must use https"));
}
}
if let Some(methods) = &metadata.code_challenge_methods_supported {
@@ -848,10 +863,35 @@ mod tests {
assert!(acceptable_endpoint("http://[::1]:8/token"));
assert!(!acceptable_endpoint("http://auth.dev/token"));
assert!(!acceptable_endpoint("http://10.0.0.1/token"));
+ // Home networks too: no plain-http sign-in off this computer
+ assert!(!acceptable_endpoint("http://homeassistant.lan/token"));
+ assert!(!acceptable_endpoint("http://homeassistant.local/token"));
+ assert!(!acceptable_endpoint("http://192.168.0.1/token"));
+ assert!(!acceptable_endpoint("http://homeassistant.lan:8123/api/mcp"));
assert!(!acceptable_endpoint("javascript:alert(1)"));
assert!(!acceptable_endpoint("file:///etc/passwd"));
}
+ #[test]
+ fn a_plain_http_refusal_names_the_header() {
+ for http in ["http://homeassistant.lan:8123", "http://192.168.0.1/token", "http://auth.dev/token"] {
+ let e = refused_endpoint(http, "x").to_string();
+ assert!(e.contains("must use https") && e.contains("Authorization = Bearer <token>"), "{http}: {e}");
+ }
+ assert!(LAN_HTTP_SIGN_IN.contains("Home Assistant") && LAN_HTTP_SIGN_IN.contains("Test connection"));
+ let other = refused_endpoint("ftp://auth.dev/token", "the authorization server must use https").to_string();
+ assert!(other.ends_with("the authorization server must use https") && !other.contains("Bearer"), "{other}");
+ }
+
+ #[tokio::test]
+ async fn discovery_on_a_lan_http_server_says_to_use_a_header() {
+ // No request leaves: every metadata url is plain http off this computer, so the server is
+ // its own (refused) authorization server.
+ let http = reqwest::Client::builder().no_proxy().build().unwrap();
+ let err = discover(&http, "http://homeassistant.lan:8123/api/mcp", None).await.unwrap_err().to_string();
+ assert!(err.contains(LAN_HTTP_SIGN_IN), "{err}");
+ }
+
#[test]
fn pkce_s256_matches_rfc7636_example() {
let p = Pkce::from_verifier("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk".into());
diff --git a/tests/fixtures/mcp/home-assistant-tools.json b/tests/fixtures/mcp/home-assistant-tools.json
new file mode 100644
index 00000000..3c4ec675
--- /dev/null
+++ b/tests/fixtures/mcp/home-assistant-tools.json
@@ -0,0 +1,9 @@
+{
+ "_comment": "tools/list as Home Assistant's mcp_server sends it (core dev, Nov 2026): names and annotations only. Its ToolAnnotations default destructive=True, and read tools set only read_only=True.",
+ "tools": [
+ {"name": "GetLiveContext", "annotations": {"readOnlyHint": true, "destructiveHint": true, "openWorldHint": false, "idempotentHint": false}},
+ {"name": "HassGetState", "annotations": {"readOnlyHint": true, "destructiveHint": true, "openWorldHint": false, "idempotentHint": false}},
+ {"name": "HassTurnOn", "annotations": {"openWorldHint": false}},
+ {"name": "HassTurnOff", "annotations": {"idempotentHint": true, "openWorldHint": false}}
+ ]
+}
diff --git a/tests/mcp_api_loop_test.rs b/tests/mcp_api_loop_test.rs
index 45879ce7..8b96f3ba 100644
--- a/tests/mcp_api_loop_test.rs
+++ b/tests/mcp_api_loop_test.rs
@@ -170,7 +170,7 @@ async fn model_lists_and_calls_mcp_tools() {
assert_eq!(requests.len(), 2);
let names: Vec<_> = requests[0]["tools"].as_array().unwrap().iter().map(|t| t["function"]["name"].as_str().unwrap()).collect();
// The read-back tool for trimmed results comes last, on OpenAI-style endpoints
- assert_eq!(names, ["mcp__echo__echo", "mcp__echo__add", "mcp__echo__sleep", "mcp__echo__env", "mcp__echo__crash", "kwnt_read_tool_result"]);
+ assert_eq!(names, ["mcp__echo__echo", "mcp__echo__add", "mcp__echo__sleep", "mcp__echo__env", "mcp__echo__crash", "mcp__echo__peek", "kwnt_read_tool_result"]);
assert_eq!(requests[0]["tools"][0]["function"]["parameters"]["required"], json!(["text"]));
// Second request carries the assistant tool call and its result
let msgs = requests[1]["messages"].as_array().unwrap();
diff --git a/tests/mcp_lan_http_test.rs b/tests/mcp_lan_http_test.rs
new file mode 100644
index 00000000..f596c426
--- /dev/null
+++ b/tests/mcp_lan_http_test.rs
@@ -0,0 +1,153 @@
+//! A Home Assistant on the home network over plain http (26a): sign-in is refused with an error
+//! that names the header way, and the header way lists its tools, reads marked read-only.
+//!
+//! `homeassistant.lan` doesn't resolve in CI, so this binary sends kwnt's outgoing http through
+//! a local proxy (`http_proxy`), which is the fake Home Assistant itself. That's why it lives in
+//! its own test binary: the proxy setting is process-wide.
+
+use axum::{
+ body::Body,
+ extract::State,
+ http::{HeaderMap, Request, StatusCode},
+ response::{IntoResponse, Response},
+ routing::post,
+ Json, Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::Database,
+ router::LayaRouter,
+ server::{create_router, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::sync::atomic::{AtomicUsize, Ordering};
+use std::sync::Arc;
+use tempfile::tempdir;
+use tower::ServiceExt;
+
+const HOST: &str = "kwnt.example.test";
+const ORIGIN: &str = "https://kwnt.example.test";
+const TOKEN: &str = "test-token-0123456789abcdef";
+const HA_URL: &str = "http://homeassistant.lan:8123/api/mcp";
+const HA_TOKEN: &str = "ha-long-lived-token";
+
+#[derive(Default)]
+struct Ha {
+ /// Requests that reached it addressed to homeassistant.lan:8123 (through the proxy).
+ lan_requests: AtomicUsize,
+}
+
+/// Home Assistant's MCP endpoint: 401 without its token, otherwise its tools as it lists them.
+async fn ha_mcp(State(ha): State<Arc<Ha>>, headers: HeaderMap, Json(msg): Json<Value>) -> Response {
+ if headers.get("host").and_then(|h| h.to_str().ok()) == Some("homeassistant.lan:8123") {
+ ha.lan_requests.fetch_add(1, Ordering::SeqCst);
+ }
+ let bearer = format!("Bearer {HA_TOKEN}");
+ if headers.get("authorization").and_then(|v| v.to_str().ok()) != Some(bearer.as_str()) {
+ return (StatusCode::UNAUTHORIZED, "401: Unauthorized").into_response();
+ }
+ let Some(id) = msg.get("id").cloned() else {
+ return StatusCode::ACCEPTED.into_response();
+ };
+ let result = match msg["method"].as_str().unwrap_or("") {
+ "initialize" => json!({
+ "protocolVersion": msg["params"]["protocolVersion"],
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "home-assistant", "version": "1.26.0"},
+ }),
+ "tools/list" => {
+ let fixture: Value = serde_json::from_str(include_str!("fixtures/mcp/home-assistant-tools.json")).unwrap();
+ json!({"tools": fixture["tools"]})
+ }
+ _ => return Json(json!({"jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": "method not found"}})).into_response(),
+ };
+ Json(json!({"jsonrpc": "2.0", "id": id, "result": result})).into_response()
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let req = Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("host", HOST)
+ .header("authorization", format!("Bearer {TOKEN}"))
+ .header("content-type", "application/json")
+ .body(body.map(|b| Body::from(b.to_string())).unwrap_or_else(Body::empty))
+ .unwrap();
+ let resp = app.clone().oneshot(req).await.unwrap();
+ let status = resp.status();
+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+#[tokio::test]
+async fn home_assistant_on_lan_http_signs_in_with_a_header_not_oauth() {
+ let ha = Arc::new(Ha::default());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let proxy = format!("http://{}", listener.local_addr().unwrap());
+ let fake = Router::new()
+ .route("/api/mcp", post(ha_mcp).delete(|| async { StatusCode::OK }))
+ .with_state(ha.clone());
+ tokio::spawn(async move { axum::serve(listener, fake).await.unwrap() });
+ // Before any http client is built (kwnt reads the proxy when it makes one)
+ for var in ["http_proxy", "HTTP_PROXY"] {
+ std::env::set_var(var, &proxy);
+ }
+ for var in ["no_proxy", "NO_PROXY", "all_proxy", "ALL_PROXY"] {
+ std::env::remove_var(var);
+ }
+
+ let tmp = tempdir().unwrap();
+ let db = Database::init(tmp.path()).await.unwrap();
+ let config = Config { data_dir: tmp.path().to_path_buf(), browser_cdp_url: Some("http://127.0.0.1:9".into()), ..Config::default() };
+ let mut state = AppState::new(
+ config.clone(),
+ db,
+ ToolRunner::new(tmp.path().join("workspace")),
+ PermissionBroker::new(),
+ LayaRouter::new(config.laya_url.clone()),
+ );
+ state.api_token = Arc::new(kwnt::server::auth::ApiToken::for_tests(TOKEN, kwnt::server::auth::Require::Auto, config.port));
+ let app = create_router(state);
+
+ // Added without a header, then Connect: refused, and the error says what to do instead
+ let (status, created) =
+ call(&app, "POST", "/api/mcp/servers", Some(json!({"name": "homeassistant", "transport": "http", "url": HA_URL}))).await;
+ assert_eq!(status, StatusCode::OK, "{created}");
+ let id = created["id"].as_str().unwrap().to_string();
+ let (status, body) = call(&app, "POST", &format!("/api/mcp/servers/{id}/oauth/start"), Some(json!({"origin": ORIGIN}))).await;
+ assert_eq!(status, StatusCode::BAD_GATEWAY, "{body}");
+ let error = body["error"].as_str().unwrap();
+ assert!(error.contains("must use https"), "{error}");
+ assert!(error.contains("Authorization = Bearer <token>") && error.contains("Test connection"), "{error}");
+ assert!(ha.lan_requests.load(Ordering::SeqCst) >= 1, "kwnt asked the LAN server for its challenge through the proxy");
+
+ // Without a header, Test connection asks for sign-in
+ let (_, tested) = call(&app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;
+ assert_eq!(tested["ok"], false, "{tested}");
+
+ // With the Bearer header the same plain-http LAN server works, and its reads are read-only
+ let (status, updated) = call(
+ &app,
+ "PUT",
+ &format!("/api/mcp/servers/{id}"),
+ Some(json!({"name": "homeassistant", "transport": "http", "url": HA_URL,
+ "headers": {"Authorization": format!("Bearer {HA_TOKEN}")}})),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "{updated}");
+ let (status, tested) = call(&app, "POST", &format!("/api/mcp/servers/{id}/test"), None).await;
+ assert_eq!(status, StatusCode::OK);
+ assert_eq!(tested["ok"], true, "{tested}");
+ assert_eq!(tested["server_info"]["name"], "home-assistant");
+ let read_only = |name: &str| {
+ tested["tools"].as_array().unwrap().iter().find(|t| t["name"] == name).unwrap_or_else(|| panic!("{name}: {tested}"))["read_only"]
+ .clone()
+ };
+ assert_eq!(read_only("GetLiveContext"), true);
+ assert_eq!(read_only("HassGetState"), true);
+ assert_eq!(read_only("HassTurnOn"), false);
+ assert_eq!(read_only("HassTurnOff"), false);
+ assert!(!tested.to_string().contains(HA_TOKEN), "the token never comes back");
+}
diff --git a/tests/mcp_test.rs b/tests/mcp_test.rs
index aace41d8..5b8bcf99 100644
--- a/tests/mcp_test.rs
+++ b/tests/mcp_test.rs
@@ -70,7 +70,7 @@ async fn stdio_client_lists_and_calls_tools() {
let tools = client.list_tools().await.unwrap();
let names: Vec<_> = tools.iter().map(|t| t.name.as_str()).collect();
- assert_eq!(names, ["echo", "add", "sleep", "env", "crash"]);
+ assert_eq!(names, ["echo", "add", "sleep", "env", "crash", "peek"]);
assert_eq!(tools[0].input_schema["required"], json!(["text"]));
let out = client.call_tool("echo", json!({"text": "hello mcp"})).await.unwrap();
@@ -186,7 +186,7 @@ async fn test_endpoint_lists_tools_and_redacts_errors() {
let (status, result) = call(&app, "POST", &format!("/api/mcp/servers/{}/test", ok_server["id"].as_str().unwrap()), None).await;
assert_eq!(status, StatusCode::OK);
assert_eq!(result["ok"], true, "{result}");
- assert_eq!(result["tools"].as_array().unwrap().len(), 5);
+ assert_eq!(result["tools"].as_array().unwrap().len(), 6);
assert_eq!(result["server_info"]["name"], "kwnt-echo");
// A server that prints its secret and dies: the error comes back without the secret
diff --git a/tests/smart_approvals_test.rs b/tests/smart_approvals_test.rs
index 12eddde5..e6fc65b3 100644
--- a/tests/smart_approvals_test.rs
+++ b/tests/smart_approvals_test.rs
@@ -294,18 +294,23 @@ async fn smart_runs_read_only_mcp_tools_and_asks_for_the_rest() {
let server = e.state.db.create_mcp_server(&space, &server).await.unwrap();
e.state.db.set_kwant_mcp_servers(&e.bot.id, &[server.id]).await.unwrap();
- // Under ask both tools ask
+ // Under ask every tool asks
assert!(is_card(&ask(&e, "mcp__echo__echo", |_| json!({"text": "hi"})).await));
space_mode(&e, "smart").await;
assert_eq!(ask(&e, "mcp__echo__echo", |_| json!({"text": "hi"})).await, Outcome::Answered(true), "readOnlyHint");
+ // Home Assistant's read shape: readOnlyHint and destructiveHint both true. The MCP spec reads
+ // destructiveHint only when readOnlyHint is false, so this runs without a card.
+ assert_eq!(ask(&e, "mcp__echo__peek", |_| json!({})).await, Outcome::Answered(true), "readOnlyHint wins (MCP spec)");
match ask(&e, "mcp__echo__add", |_| json!({"a": 1, "b": 2})).await {
Outcome::Card(details) => assert_eq!(details["smart_reason"], "this MCP tool can change things"),
- other => panic!("destructiveHint wins over readOnlyHint: {other:?}"),
+ other => panic!("a tool not marked readOnlyHint asks: {other:?}"),
}
assert!(is_card(&ask(&e, "mcp__echo__env", |_| json!({"name": "HOME"})).await), "no hint asks");
let rows = get(&e, "/api/approvals?status=auto_allowed").await;
- assert_eq!(rows[0]["tool_name"], "mcp__echo__echo");
- assert_eq!(rows[0]["details"]["smart_reason"], "the MCP server marks this tool read-only");
+ let mut names: Vec<_> = rows.as_array().unwrap().iter().map(|r| r["tool_name"].as_str().unwrap()).collect();
+ names.sort_unstable();
+ assert_eq!(names, ["mcp__echo__echo", "mcp__echo__peek"], "{rows}");
+ assert!(rows.as_array().unwrap().iter().all(|r| r["details"]["smart_reason"] == "the MCP server marks this tool read-only"), "{rows}");
}
#[tokio::test]