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.

Connections API, optional Composio connector, docs

Lina49bda27dedb
diff --git a/docs/connections.md b/docs/connections.md
new file mode 100644
index 00000000..a4f5d133
--- /dev/null
+++ b/docs/connections.md
@@ -0,0 +1,190 @@
+# Connections: API
+
+One list of everything kwnt's bots reach outside the app, with its status, last check and the
+bots that use it:
+
+- MCP servers
+- engine accounts
+- website logins saved in the vault
+- the mail (IMAP) and GitHub sources of Loose ends
+
+Composio is offered as an **optional** MCP connector. It is off by default, and it is labelled
+everywhere as storing the person's app sign-ins on Composio's servers. Every other login stays in
+kwnt's own vault or database.
+
+Both routes are **person-only**, because the list names saved logins:
+
+- A bot's turn token gets `403`.
+- From another machine, the API token is required (`401` without it).
+
+## `GET /api/connections?space=`
+
+```json
+{
+ "connections": [ <Connection>, … ],
+ "counts": { "connected": 4, "error": 1, "off": 1 },
+ "vault": { "status": "ok", "logins": 3 },
+ "catalog": [ <CatalogEntry> ]
+}
+```
+
+`connections` is ordered by kind (MCP servers, accounts, logins, then Loose ends sources) in the
+order each list comes from. Sort or group it on the client.
+
+### Connection
+
+```json
+{
+ "id": "mcp:7c1e…",
+ "kind": "mcp",
+ "name": "github",
+ "detail": "api.githubcopilot.com",
+ "status": "needs_sign_in",
+ "status_detail": "Sign-in required",
+ "last_check": "2026-10-22T10:04:11Z",
+ "used_by": [ { "id": "k1", "name": "Ada" } ],
+ "logins_stored": "kwnt",
+ "manage": "/api/mcp/servers/7c1e…"
+}
+```
+
+| field | meaning |
+|---|---|
+| `id` | `mcp:<server id>`, `account:<profile id>`, `login:<owner id>:<credential id>`, `source:<source id>`. Stable across calls |
+| `kind` | `mcp`, `account`, `browser_login`, `email` or `github` |
+| `name` | the server or account name, the login's host, or the source label |
+| `detail` | what it points at. It is never a secret. See the per-kind list below |
+| `status` | `connected`, `needs_sign_in`, `limited`, `error`, `off`, `locked` or `unknown` |
+| `status_detail` | optional readable reason ("Out of quota until …", the last error) |
+| `last_check` | RFC 3339, or `null` when never checked |
+| `used_by` | the bots that use it, sorted by name. Empty while it is off |
+| `logins_stored` | `vault` (kwnt's password vault or Bitwarden), `kwnt` (kwnt's database or the engine CLI's own login folder), or `composio` (Composio's servers) |
+| `manage` | the existing API for changing it (link the UI's edit screen from the kind) |
+
+What `detail` holds for each kind:
+
+| kind | `detail` |
+|---|---|
+| MCP over HTTP | the host |
+| MCP over stdio | the command only. Its arguments can carry tokens, so they are left out |
+| account | the engine, plus the account label when known. For a Custom API account, the server host |
+| browser_login | `username @ origin · saved for <bot / team … / channel …>` |
+| email | `username @ imap host` |
+| github | the API host |
+
+### Status rules
+
+**MCP server**
+
+| condition | status |
+|---|---|
+| switched off | `off` |
+| last test passed | `connected` |
+| last test needed a sign-in | `needs_sign_in` |
+| last test failed | `error`, with the error |
+| not tested since kwnt started, but signed in with OAuth | `connected` |
+| not tested since kwnt started | `unknown` |
+
+`last_check` is the last `POST /api/mcp/servers/:id/test`. It is kept **in memory**, so it is
+empty again after a restart. Call the test route to refresh it ("Check now").
+
+**Account** (engine profile)
+
+| condition | status |
+|---|---|
+| switched off | `off` |
+| out of quota | `limited` |
+| Custom API account, by its last check | `ready` → `connected`, `key_rejected` → `needs_sign_in`, `unreachable` or `error` → `error` |
+| last turn refused for auth, or not signed in | `needs_sign_in` |
+| signed in | `connected` |
+| anything else | `unknown` |
+
+`last_check` is the Custom API check time. Other accounts have none.
+
+**Saved login**
+
+- Always `connected`. kwnt doesn't try a saved password on its own.
+- `last_check` is the time it was last filled into a page.
+
+**Loose ends source**
+
+| condition | status |
+|---|---|
+| switched off | `off` |
+| last scan ok | `connected` |
+| last scan failed | `error`, with the error |
+| never scanned | `unknown` |
+
+`last_check` is the last scan.
+
+### Who uses it (`used_by`)
+
+| kind | bots |
+|---|---|
+| MCP server | every bot in the space, minus bots switched off for that server. Nobody while the server is off |
+| account | bots bound to it, plus bots with no binding on its engine while it is the engine's default |
+| browser_login | the bot it was saved for, or the lead and members of the team or channel it was saved for (they share that browser) |
+| email, github | the space's Loose ends bot, when Loose ends ownership is on |
+
+### `vault`
+
+| `status` | meaning |
+|---|---|
+| `ok` | the logins are listed. `logins` is how many there are |
+| `locked` | Bitwarden is locked. Logins are **not** listed. Show "Unlock Bitwarden to list saved logins" and link the Passwords settings |
+| `unavailable` | the store couldn't be read. Logins are not listed |
+
+### Catalog entry
+
+```json
+{
+ "id": "composio",
+ "kind": "mcp",
+ "name": "Composio",
+ "description": "Hundreds of apps (Gmail, Slack, Notion, Linear…) through one MCP server you set up at composio.dev.",
+ "optional": true,
+ "added": false,
+ "connection_id": null,
+ "enabled": false,
+ "logins_stored": "composio",
+ "warning": "Composio keeps your app sign-ins on Composio's servers, not in kwnt's vault, and your bots' tool calls through it pass through Composio.",
+ "add": "/api/connections/composio"
+}
+```
+
+Show `warning` next to the add button and on the connection once it is added. Once added,
+`connection_id` points at the MCP connection.
+
+## `POST /api/connections/composio?space=`
+
+```json
+{ "url": "https://backend.composio.dev/v3/mcp/<id>/mcp?user_id=…", "api_key": "…", "enabled": false }
+```
+
+| field | rules |
+|---|---|
+| `url` | required. Must be `https` on `composio.dev` or one of its subdomains |
+| `api_key` | optional. Sent to Composio as the `x-api-key` header, and stored and masked like any MCP header |
+| `enabled` | optional, default **false**. Only an enabled server reaches bots. Turn it on later with `PATCH /api/mcp/servers/:id` |
+
+Result: `{ "connection_id": "mcp:…", "server": McpServerView, "warning": "…" }`. `McpServerView`
+masks header values.
+
+Errors:
+
+| status | when |
+|---|---|
+| `400` | the URL is not Composio's, or the server is invalid |
+| `409` | Composio is already added (a server named `composio`, or one with a Composio URL). Change that server instead |
+| `403` / `401` | not the person (see above) |
+
+Composio appears as an ordinary MCP server in `/api/mcp/servers`, so switching it on or off, the
+per-bot opt-outs, testing and removing all use those routes.
+
+## Known limits
+
+- MCP `last_check` is kept in memory only (see the MCP status rules).
+- Loose ends sources are global in kwnt rather than per space, so every space lists them, and
+ `used_by` names the current space's Loose ends bot.
+- Engine CLI logins (`~/.claude`, Codex, Grok) live in each CLI's own folder, reported as
+ `logins_stored: "kwnt"`. kwnt doesn't copy them into the vault.
diff --git a/docs/live-activity.md b/docs/live-activity.md
index a4ba4c02..ec50edfe 100644
--- a/docs/live-activity.md
+++ b/docs/live-activity.md
@@ -1,6 +1,7 @@
# Live activity and human steps: API
-Backend for two UI features on branch `live-activity`:
+Backend for two UI features on branch `live-activity` (the third, Connections, is in
+[connections.md](connections.md)):
1. **Live activity**: what a bot is doing while it works (thinking, each tool it runs, waits for
approval or for the person), streamed over SSE and kept on the reply after a reload.
@@ -54,9 +55,9 @@ turn's list (keyed by `turn_id`); append it if it's new.
scoped to the turn). The `activity` step of kind `thinking` only marks start (`running`) and end
(`ok`, with `text`). While it's running, show the `ThinkingDelta` text under it.
-A `note` step (status `ok`) explains a limit, e.g. for engines that don't share thinking:
-"This engine doesn't share its thinking here; you'll see what it says between steps and each
-tool it runs." It is the first step of such turns.
+A `note` step (status `ok`) explains a limit. It is the first step of a turn on an API engine:
+"This engine shares its thinking only when its model returns it; otherwise you'll see what it says
+between steps and each tool it runs." Show it as a muted line, not an error.
### After a reload: `meta.activity` on the reply
@@ -88,7 +89,10 @@ Titles, details and thinking text pass through redaction before they leave the s
| claude (CLI) | yes. Streamed `thinking_delta` blocks (or whole `thinking` blocks), when the model thinks | yes, from `tool_use` / `tool_result`. Failures carry the error text | yes |
| codex (CLI) | yes, from reasoning summaries (`codex exec --json` `reasoning` items) | yes: commands (with exit code), file changes, MCP calls, web searches, plan updates | yes (kwnt MCP tools) |
| grok (CLI) | yes, from `thought` stream events | yes, from `tool_call` / `tool_call_update` (failed status carries the error) | yes (kwnt MCP tools) |
-| API engines (anthropic_api, openai_api, xai_api, ollama, custom_api) | **no**. These get the `note` step. The text the model writes before a tool call still arrives as `ThinkingDelta` | yes | yes |
+| API engines (anthropic_api, openai_api, xai_api, ollama, custom_api) | **when the model returns it**, in full: OpenAI-style `reasoning_content` / `reasoning` (DeepSeek, xAI, Ollama, OpenRouter, vLLM…) and Anthropic `thinking` blocks, streamed (`thinking_delta`, `delta.reasoning_content`) or whole per reply. Redacted thinking is skipped. Turns get the `note` step first. The text the model writes before a tool call also arrives as `ThinkingDelta` | yes | yes |
+
+kwnt doesn't switch on Anthropic extended thinking for API accounts itself (it costs tokens and
+changes replies), so Anthropic API turns show thinking only for models that think by default.
## 2. Human step
@@ -101,13 +105,22 @@ browser):
{ "reason": "Log in to GitHub so I can open the PR", "kind": "sign_in", "url": "https://github.com/login" }
```
-`kind` is one of `sign_in`, `captcha` or `other`. `reason` is required and at most 300
+`kind` is one of `sign_in`, `captcha`, `two_factor` (a one-time code, an authenticator or a
+security key) or `other`. `reason` is required and at most 300
characters. `url` is optional, must be http(s), and is stored without user info, query or
fragment.
-The turn waits until the person answers, the turn is stopped, or the wait runs out (a few
-minutes). If the wait runs out, the step stays open and the agent is told to end its turn. When
-the person answers later, a **new turn** starts in the same chat with the outcome.
+### Timeouts
+
+- The turn waits **290 seconds** (the 300-second tool-call limit less 10 seconds) for the person to
+ answer, unless the turn is stopped first (then the step is `cancelled`).
+- If the wait runs out, the step **stays open** and the card stays live; the agent is told to end
+ its turn and say what it is waiting for. The bot's browser stays held for the person.
+- Open steps **never expire** on their own. When the person answers later, Done or Skip starts a
+ **new turn** in the same chat with the outcome (`resumed: "new_turn"`), so the bot carries on
+ from where it stopped.
+- "Skip" in the UI is `POST /api/human-steps/:id/decline`: the bot is told the person skipped the
+ step and continues without it.
**Auto-raise:** when a `browser_open`, `browser_page` or `browser_act` tool lands on a CAPTCHA or
anti-bot wall (`detect_bot_wall`), kwnt raises a `captcha` step itself (`source: "auto"`), waits
@@ -121,6 +134,12 @@ While a step is open in a bot browser:
The person can use the live view freely.
+**Bots never see typed passwords.** The agent's browser tools are `browser_open`, `browser_page`
+and `browser_act` (click by text, type, key, scroll); there is no script tool. Page reads use
+`innerText` and element labels, which never include the value of an input (only submit and button
+labels), and all three tools are refused while the step is open. This covers kwnt's own browser
+tools; a CLI engine's own built-in browser or shell is outside it.
+
A turn that asks again while its step is open gets the same step back, so no second card is
created. Each agent can have at most 5 open steps.
@@ -160,7 +179,8 @@ Sent when a step opens and when it closes.
### The card message
-Opening a step also adds a chat message (`message_added`) from the bot. Its text is something like:
+Opening a step also adds a chat message (`message_added`) from the bot. The first line names the kind: "Sign in needed", "Human check needed",
+"Sign-in code needed" (two_factor) or "Your help is needed". Its text is something like:
> Sign in needed: Log in to GitHub so I can open the PR
> https://github.com/login
@@ -182,7 +202,7 @@ The card's `meta.status` is updated in place when the step closes. Render it as
### Notification
The standard `Notify` event and webhook use `kind: "human_step"`. The title is "<Bot> needs you in
-the browser". The body is "<Sign in needed | Human check needed | Your help is needed>. Open the
+the browser". The body is "<Sign in needed | Human check needed | Sign-in code needed | Your help is needed>. Open the
chat, do it in the browser panel, then press Done." The body never includes the reason or URL.
`human_step` was added to `NOTIFY_KINDS`. People who saved a custom notification list must turn it
diff --git a/src/server/auth.rs b/src/server/auth.rs
index 63435933..aabbf362 100644
--- a/src/server/auth.rs
+++ b/src/server/auth.rs
@@ -248,7 +248,7 @@ fn exempt(path: &str) -> bool {
|| path == "/api/mcp/self"
}
-/// Routes only the person may call: saved passwords and the password vault (Bitwarden), answering an approval card, Loose ends and Parallel Universe, the
+/// Routes only the person may call: saved passwords and the password vault (Bitwarden), answering an approval card, Loose ends, Connections and Parallel Universe, the
/// approvals switch, and deleting a bot or team or undoing a bot action or import (those delete saved passwords too). A bot's turn token (or any
/// bearer that isn't the API token) is refused with 403 everywhere. From another machine they need the API token (401);
/// from this machine they don't, unless `KWNT_REQUIRE_TOKEN=always` (`person_token_needed`).
@@ -259,6 +259,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {
["", "api", "passwords", ..] => true,
// Loose ends read the person's mail: bots never see or change them
["", "api", "zombie", ..] => true,
+ // Connections list saved logins and add Composio, which holds the person's app sign-ins
+ ["", "api", "connections", ..] => true,
// Parallel Universe starts containers on this machine from a directory the person names
["", "api", "parallel", ..] => true,
// Camera-to-Completed: the person's letters
@@ -581,6 +583,8 @@ mod tests {
assert!(person_only(&post, "/api/passwords/migrate"));
assert!(person_only(&get, "/api/zombie/cases"));
assert!(person_only(&post, "/api/zombie/sources/s1/test"));
+ assert!(person_only(&get, "/api/connections"));
+ assert!(person_only(&post, "/api/connections/composio"));
assert!(person_only(&get, "/api/parallel/prices"));
assert!(person_only(&post, "/api/parallel/scenarios"));
assert!(person_only(&post, "/api/documents"));
diff --git a/src/server/connections.rs b/src/server/connections.rs
new file mode 100644
index 00000000..46702ce0
--- /dev/null
+++ b/src/server/connections.rs
@@ -0,0 +1,494 @@
+//! Connections: one list of everything kwnt's bots can reach outside the app, with its status,
+//! last check and the bots that use it. MCP servers, engine accounts, website logins in the
+//! vault, and the mail (IMAP) and GitHub sources of Loose ends.
+//!
+//! Composio is offered as an optional MCP connector, off until the person adds it. It keeps the
+//! person's app sign-ins on Composio's servers, so every entry says so; logins otherwise stay in
+//! kwnt's own vault. Person-only (`auth::person_only`): the list names saved logins.
+
+use super::loose_ends_owner::{self, OwnerSettings};
+use super::mcp_suggest::refuse_agent_tokens;
+use super::spaces::Scope;
+use super::AppState;
+use crate::db::models::{Kwant, McpServer};
+use crate::db::spaces::SpaceId;
+use crate::mcp::{self, McpServerInput};
+use crate::profiles::Engine;
+use crate::sandbox::credentials::{CredentialStore, StoreError};
+use axum::{
+ extract::State,
+ http::{HeaderMap, StatusCode},
+ response::{IntoResponse, Response},
+ Json,
+};
+use chrono::{DateTime, Utc};
+use serde::{Deserialize, Serialize};
+use serde_json::{json, Value};
+use std::collections::{BTreeMap, HashMap};
+use std::sync::{Mutex, OnceLock};
+
+const REFUSAL: &str = "only the person manages connections";
+
+/// The name the Composio connector gets as an MCP server.
+pub const COMPOSIO_NAME: &str = "composio";
+/// Said wherever Composio is offered or connected.
+pub const COMPOSIO_WARNING: &str = "Composio keeps your app sign-ins on Composio's servers, not in kwnt's vault, \
+ and your bots' tool calls through it pass through Composio.";
+
+/// A bot that uses a connection.
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct UsedBy {
+ pub id: String,
+ pub name: String,
+}
+
+/// One connection, as `GET /api/connections` lists it. Never holds a secret.
+#[derive(Debug, Clone, Serialize)]
+pub struct Connection {
+ /// `<kind>:<id>`, stable across calls.
+ pub id: String,
+ /// `mcp`, `account`, `browser_login`, `email` or `github`.
+ pub kind: &'static str,
+ pub name: String,
+ /// What it points at: a host, an engine, `username @ origin`. Never a secret.
+ pub detail: Option<String>,
+ /// `connected`, `needs_sign_in`, `limited`, `error`, `off`, `locked` or `unknown`.
+ pub status: &'static str,
+ pub status_detail: Option<String>,
+ pub last_check: Option<DateTime<Utc>>,
+ pub used_by: Vec<UsedBy>,
+ /// Where its sign-in lives: `vault` (kwnt's password vault or Bitwarden), `kwnt` (kwnt's
+ /// database or the engine CLI's own login folder) or `composio` (Composio's servers).
+ pub logins_stored: &'static str,
+ /// The API that manages it.
+ pub manage: String,
+}
+
+// Last MCP test results (POST /api/mcp/servers/:id/test), kept in memory
+
+#[derive(Debug, Clone)]
+struct McpCheck {
+ ok: bool,
+ auth_required: bool,
+ error: Option<String>,
+ at: DateTime<Utc>,
+}
+
+fn mcp_checks() -> &'static Mutex<HashMap<String, McpCheck>> {
+ static CHECKS: OnceLock<Mutex<HashMap<String, McpCheck>>> = OnceLock::new();
+ CHECKS.get_or_init(Default::default)
+}
+
+/// Remembers the outcome of an MCP server test (already redacted) as its last check.
+pub fn record_mcp_check(server_id: &str, outcome: &Value) {
+ let check = McpCheck {
+ ok: outcome["ok"] == json!(true),
+ auth_required: outcome["auth_required"] == json!(true),
+ error: outcome["error"].as_str().map(|e| cut(e, 300)),
+ at: Utc::now(),
+ };
+ mcp_checks().lock().unwrap_or_else(|e| e.into_inner()).insert(server_id.to_string(), check);
+}
+
+fn cut(text: &str, max: usize) -> String {
+ match text.char_indices().nth(max) {
+ Some((i, _)) => format!("{}…", &text[..i]),
+ None => text.to_string(),
+ }
+}
+
+fn host_of(url: &str) -> Option<String> {
+ url::Url::parse(url).ok().and_then(|u| u.host_str().map(str::to_string))
+}
+
+/// Whether `url` is one of Composio's MCP endpoints.
+pub fn is_composio_url(url: &str) -> bool {
+ url::Url::parse(url).ok().is_some_and(|u| {
+ u.scheme() == "https" && u.host_str().is_some_and(|h| h == "composio.dev" || h.ends_with(".composio.dev"))
+ })
+}
+
+fn is_composio(server: &McpServer) -> bool {
+ server.url.as_deref().is_some_and(is_composio_url)
+}
+
+fn used(kwants: &[&Kwant]) -> Vec<UsedBy> {
+ let mut out: Vec<UsedBy> = kwants.iter().map(|k| UsedBy { id: k.id.clone(), name: k.name.clone() }).collect();
+ out.sort_by_key(|u| (u.name.to_lowercase(), u.id.clone()));
+ out.dedup_by(|a, b| a.id == b.id);
+ out
+}
+
+/// The status of an MCP server from its switch, sign-in and last test.
+fn mcp_status(server: &McpServer, oauth_connected: bool, check: Option<&McpCheck>) -> (&'static str, Option<String>) {
+ if !server.enabled {
+ return ("off", None);
+ }
+ match check {
+ Some(c) if c.ok => ("connected", None),
+ Some(c) if c.auth_required => ("needs_sign_in", Some("Sign-in required".into())),
+ Some(c) => ("error", c.error.clone()),
+ None if oauth_connected => ("connected", Some("Signed in; not tested since kwnt started".into())),
+ None => ("unknown", Some("Not tested since kwnt started".into())),
+ }
+}
+
+async fn mcp_connections(state: &AppState, space: &SpaceId, kwants: &[Kwant]) -> Vec<Connection> {
+ let servers = state.db.list_mcp_servers(space).await.unwrap_or_default();
+ let oauth = super::mcp_oauth::statuses(state).await;
+ let opt_outs = state.db.list_mcp_kwant_opt_outs(space).await.unwrap_or_default();
+ let checks = mcp_checks().lock().unwrap_or_else(|e| e.into_inner()).clone();
+ servers
+ .iter()
+ .map(|s| {
+ let (status, status_detail) =
+ mcp_status(s, oauth.get(&s.id).is_some_and(|o| o.connected), checks.get(&s.id));
+ let off_for = opt_outs.get(&s.id).cloned().unwrap_or_default();
+ let users: Vec<&Kwant> = if s.enabled { kwants.iter().filter(|k| !off_for.contains(&k.id)).collect() } else { Vec::new() };
+ let detail = match s.transport.as_str() {
+ "http" => s.url.as_deref().and_then(host_of),
+ // the command only: arguments can carry tokens
+ _ => s.command.clone(),
+ };
+ Connection {
+ id: format!("mcp:{}", s.id),
+ kind: "mcp",
+ name: s.name.clone(),
+ detail,
+ status,
+ status_detail,
+ last_check: checks.get(&s.id).map(|c| c.at),
+ used_by: used(&users),
+ logins_stored: if is_composio(s) { "composio" } else { "kwnt" },
+ manage: format!("/api/mcp/servers/{}", s.id),
+ }
+ })
+ .collect()
+}
+
+/// Bots that run on an account: bound to it, or unbound on its engine while it is the default.
+fn account_users<'a>(
+ profile: &crate::db::models::LlmProfile,
+ kwants: &'a [Kwant],
+ bindings: &HashMap<String, (Option<String>, bool)>,
+) -> Vec<&'a Kwant> {
+ let engine = Engine::parse(&profile.engine);
+ kwants
+ .iter()
+ .filter(|k| match bindings.get(&k.id).and_then(|(p, _)| p.as_deref()) {
+ Some(bound) => bound == profile.id,
+ None => profile.is_default && engine.is_some() && Engine::from_model(&k.preferred_model) == engine,
+ })
+ .collect()
+}
+
+async fn account_connections(state: &AppState, space: &SpaceId, kwants: &[Kwant]) -> Vec<Connection> {
+ let profiles = state.db.list_profiles(space).await.unwrap_or_default();
+ let bindings = state.db.list_kwant_bindings(space).await.unwrap_or_default();
+ let users: HashMap<String, Vec<UsedBy>> =
+ profiles.iter().map(|p| (p.id.clone(), used(&account_users(p, kwants, &bindings)))).collect();
+ super::profile_routes::views(state, profiles)
+ .await
+ .into_iter()
+ .map(|p| {
+ let custom_status = p.custom.as_ref().and_then(|c| c.status);
+ let (status, status_detail): (&'static str, Option<String>) = if !p.enabled {
+ ("off", None)
+ } else if let Some(until) = p.limited_until {
+ ("limited", Some(format!("Out of quota until {}", until.to_rfc3339())))
+ } else if let Some(s) = custom_status {
+ use crate::drivers::custom::CheckStatus as C;
+ match s {
+ C::Ready => ("connected", None),
+ C::KeyRejected => ("needs_sign_in", Some("The key is missing or refused".into())),
+ C::Unreachable => ("error", Some("The server can't be reached".into())),
+ C::Error => ("error", p.custom.as_ref().and_then(|c| c.detail.clone())),
+ }
+ } else if p.last_error.as_deref() == Some("auth") || p.signed_in == Some(false) {
+ ("needs_sign_in", None)
+ } else if p.signed_in == Some(true) {
+ ("connected", None)
+ } else if let Some(e) = p.last_error.clone() {
+ ("error", Some(e))
+ } else {
+ ("unknown", None)
+ };
+ let detail = match (&p.custom, &p.account_label) {
+ (Some(c), _) => host_of(&c.base_url).or_else(|| Some(c.base_url.clone())),
+ (None, Some(label)) => Some(format!("{} · {label}", p.engine)),
+ (None, None) => Some(p.engine.clone()),
+ };
+ Connection {
+ id: format!("account:{}", p.id),
+ kind: "account",
+ name: p.name.clone(),
+ detail,
+ status,
+ status_detail,
+ last_check: p.custom.as_ref().and_then(|c| c.checked_at),
+ used_by: users.get(&p.id).cloned().unwrap_or_default(),
+ logins_stored: "kwnt",
+ manage: format!("/api/profiles/{}", p.id),
+ }
+ })
+ .collect()
+}
+
+fn members(lead: &str, members_json: &str) -> Vec<String> {
+ let mut ids: Vec<String> = serde_json::from_str(members_json).unwrap_or_default();
+ ids.push(lead.to_string());
+ ids
+}
+
+/// Saved website logins of every team, channel and bot in the space. Metadata only. `Err` when
+/// the vault is locked (Bitwarden) or unavailable.
+async fn login_connections(state: &AppState, space: &SpaceId, kwants: &[Kwant]) -> Result<Vec<Connection>, StoreError> {
+ let by_id: HashMap<&str, &Kwant> = kwants.iter().map(|k| (k.id.as_str(), k)).collect();
+ let pick = |ids: Vec<String>| -> Vec<&Kwant> { ids.iter().filter_map(|id| by_id.get(id.as_str()).copied()).collect() };
+ // (owner id, owner label, bots that use the owner's browser)
+ let mut owners: Vec<(String, String, Vec<&Kwant>)> = Vec::new();
+ for t in state.db.list_teams(space).await.unwrap_or_default() {
+ owners.push((t.id.clone(), format!("team {}", t.name), pick(members(&t.lead_kwant_id, &t.member_kwants))));
+ }
+ for c in state.db.list_channels(space).await.unwrap_or_default() {
+ owners.push((c.id.clone(), format!("channel {}", c.name), pick(members(&c.lead_kwant_id, &c.member_kwants))));
+ }
+ for k in kwants {
+ owners.push((k.id.clone(), k.name.clone(), vec![k]));
+ }
+ let mut out = Vec::new();
+ for (owner, label, users) in owners {
+ for m in state.credentials.list(&owner).await? {
+ out.push(Connection {
+ id: format!("login:{owner}:{}", m.id),
+ kind: "browser_login",
+ name: host_of(&m.origin).unwrap_or_else(|| m.origin.clone()),
+ detail: Some(format!("{} @ {} · saved for {label}", m.username, m.origin)),
+ status: "connected",
+ status_detail: None,
+ last_check: DateTime::parse_from_rfc3339(&m.last_used).ok().map(|t| t.with_timezone(&Utc)),
+ used_by: used(&users),
+ logins_stored: "vault",
+ manage: format!("/api/sandbox/{owner}/passwords"),
+ });
+ }
+ }
+ Ok(out)
+}
+
+/// The mail (IMAP) and GitHub sources of Loose ends, used by the space's Loose ends bot.
+async fn source_connections(state: &AppState, space: &SpaceId) -> Vec<Connection> {
+ let settings = OwnerSettings::load(&state.db, space).await.unwrap_or_default();
+ let owner = if settings.enabled { loose_ends_owner::owner(&state.db, space, &settings).await } else { None };
+ let users: Vec<UsedBy> = owner.map(|k| vec![UsedBy { id: k.id, name: k.name }]).unwrap_or_default();
+ state
+ .db
+ .zombie_sources()
+ .await
+ .unwrap_or_default()
+ .into_iter()
+ .filter_map(|s| {
+ let config: Value = serde_json::from_str(&s.config).unwrap_or(Value::Null);
+ let (kind, detail) = match s.kind.as_str() {
+ "imap" => {
+ let host = config["host"].as_str().unwrap_or_default();
+ let user = config["username"].as_str().unwrap_or_default();
+ ("email", Some(format!("{user} @ {host}")))
+ }
+ "github" => ("github", config["api_base"].as_str().and_then(host_of).or_else(|| Some("api.github.com".into()))),
+ _ => return None,
+ };
+ let (status, status_detail) = match (s.enabled, s.last_status.as_deref()) {
+ (false, _) => ("off", None),
+ (true, Some("ok")) => ("connected", None),
+ (true, Some(_)) => ("error", s.last_error.clone()),
+ (true, None) => ("unknown", Some("Not checked yet".into())),
+ };
+ Some(Connection {
+ id: format!("source:{}", s.id),
+ kind,
+ name: s.label,
+ detail,
+ status,
+ status_detail,
+ last_check: s.last_scan_at,
+ used_by: users.clone(),
+ logins_stored: "vault",
+ manage: format!("/api/zombie/sources/{}", s.id),
+ })
+ })
+ .collect()
+}
+
+/// The optional connectors kwnt offers, with whether each is added.
+fn catalog(servers: &[McpServer]) -> Value {
+ let added = servers.iter().find(|s| is_composio(s));
+ json!([{
+ "id": "composio",
+ "kind": "mcp",
+ "name": "Composio",
+ "description": "Hundreds of apps (Gmail, Slack, Notion, Linear…) through one MCP server you set up at composio.dev.",
+ "optional": true,
+ "added": added.is_some(),
+ "connection_id": added.map(|s| format!("mcp:{}", s.id)),
+ "enabled": added.is_some_and(|s| s.enabled),
+ "logins_stored": "composio",
+ "warning": COMPOSIO_WARNING,
+ "add": "/api/connections/composio",
+ }])
+}
+
+/// `GET /api/connections?space=`: every connection of the space, a vault summary and the
+/// optional connectors.
+pub async fn list(State(state): State<AppState>, headers: HeaderMap, Scope(space): Scope) -> Response {
+ if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {
+ return r;
+ }
+ let kwants = state.db.list_kwants(&space).await.unwrap_or_default();
+ let mut connections = mcp_connections(&state, &space, &kwants).await;
+ connections.extend(account_connections(&state, &space, &kwants).await);
+ let vault = match login_connections(&state, &space, &kwants).await {
+ Ok(logins) => {
+ let n = logins.len();
+ connections.extend(logins);
+ json!({"status": "ok", "logins": n})
+ }
+ Err(StoreError::Locked) => json!({"status": "locked", "detail": "Unlock Bitwarden to list saved logins"}),
+ Err(e) => {
+ tracing::warn!(error = %e, "connections: could not list saved logins");
+ json!({"status": "unavailable", "detail": "Saved logins can't be read right now"})
+ }
+ };
+ connections.extend(source_connections(&state, &space).await);
+ let servers = state.db.list_mcp_servers(&space).await.unwrap_or_default();
+ let mut counts: BTreeMap<&str, usize> = BTreeMap::new();
+ for c in &connections {
+ *counts.entry(c.status).or_default() += 1;
+ }
+ Json(json!({
+ "connections": connections,
+ "counts": counts,
+ "vault": vault,
+ "catalog": catalog(&servers),
+ }))
+ .into_response()
+}
+
+#[derive(Debug, Deserialize)]
+pub struct ComposioBody {
+ /// The MCP URL Composio gives for the person's server, `https://….composio.dev/…`.
+ pub url: String,
+ /// Composio API key, sent as `x-api-key` (stored like any MCP header, masked in every view).
+ #[serde(default)]
+ pub api_key: Option<String>,
+ /// Off unless the person says so: an added connector reaches no bot until it is switched on.
+ #[serde(default)]
+ pub enabled: bool,
+}
+
+fn error(status: StatusCode, message: &str) -> Response {
+ (status, Json(json!({"error": message}))).into_response()
+}
+
+/// `POST /api/connections/composio?space=`: adds Composio as an MCP server (off by default).
+pub async fn add_composio(
+ State(state): State<AppState>,
+ headers: HeaderMap,
+ Scope(space): Scope,
+ Json(body): Json<ComposioBody>,
+) -> Response {
+ if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {
+ return r;
+ }
+ let url = body.url.trim();
+ if !is_composio_url(url) {
+ return error(StatusCode::BAD_REQUEST, "url must be an https address on composio.dev");
+ }
+ let servers = state.db.list_mcp_servers(&space).await.unwrap_or_default();
+ if servers.iter().any(|s| is_composio(s) || s.name.eq_ignore_ascii_case(COMPOSIO_NAME)) {
+ return error(StatusCode::CONFLICT, "Composio is already added; change it under its MCP server");
+ }
+ let headers: BTreeMap<String, String> = body
+ .api_key
+ .map(|k| k.trim().to_string())
+ .filter(|k| !k.is_empty())
+ .map(|k| BTreeMap::from([("x-api-key".to_string(), k)]))
+ .unwrap_or_default();
+ let input = McpServerInput {
+ name: COMPOSIO_NAME.into(),
+ transport: "http".into(),
+ command: None,
+ args: None,
+ url: Some(url.to_string()),
+ env: None,
+ headers: Some(headers),
+ enabled: Some(body.enabled),
+ timeout_secs: None,
+ };
+ let server = match mcp::build_server(input, None) {
+ Ok(s) => s,
+ Err(m) => return error(StatusCode::BAD_REQUEST, &m),
+ };
+ match state.db.create_mcp_server(&space, &server).await {
+ Ok(created) => Json(json!({
+ "connection_id": format!("mcp:{}", created.id),
+ "server": mcp::McpServerView::from(&created),
+ "warning": COMPOSIO_WARNING,
+ }))
+ .into_response(),
+ Err(e) => {
+ tracing::warn!(error = %e, "connections: could not add Composio");
+ error(StatusCode::INTERNAL_SERVER_ERROR, "could not add Composio")
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn server(enabled: bool, url: Option<&str>) -> McpServer {
+ McpServer {
+ id: "s1".into(),
+ name: "x".into(),
+ transport: "http".into(),
+ command: None,
+ args: vec![],
+ url: url.map(str::to_string),
+ env: Default::default(),
+ headers: Default::default(),
+ enabled,
+ timeout_secs: 30,
+ created_at: None,
+ }
+ }
+
+ #[test]
+ fn composio_urls_are_https_on_composio_dev_only() {
+ assert!(is_composio_url("https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u"));
+ assert!(is_composio_url("https://mcp.composio.dev/partner/x"));
+ assert!(!is_composio_url("http://backend.composio.dev/v3/mcp/abc"), "no plain http");
+ assert!(!is_composio_url("https://composio.dev.evil.example/mcp"));
+ assert!(!is_composio_url("https://evilcomposio.dev/mcp"));
+ assert!(!is_composio_url("not a url"));
+ }
+
+ #[test]
+ fn mcp_status_follows_switch_then_last_test() {
+ let check = |ok, auth_required, error: Option<&str>| McpCheck { ok, auth_required, error: error.map(str::to_string), at: Utc::now() };
+ assert_eq!(mcp_status(&server(false, None), true, Some(&check(true, false, None))).0, "off");
+ assert_eq!(mcp_status(&server(true, None), false, Some(&check(true, false, None))).0, "connected");
+ assert_eq!(mcp_status(&server(true, None), false, Some(&check(false, true, None))).0, "needs_sign_in");
+ assert_eq!(mcp_status(&server(true, None), false, Some(&check(false, false, Some("boom")))), ("error", Some("boom".into())));
+ assert_eq!(mcp_status(&server(true, None), true, None).0, "connected");
+ assert_eq!(mcp_status(&server(true, None), false, None).0, "unknown");
+ }
+
+ #[test]
+ fn a_test_outcome_becomes_the_last_check() {
+ record_mcp_check("conn-unit", &json!({"ok": false, "error": "x".repeat(400)}));
+ let c = mcp_checks().lock().unwrap().get("conn-unit").cloned().unwrap();
+ assert!(!c.ok && !c.auth_required);
+ assert_eq!(c.error.unwrap().chars().count(), 301, "cut to 300 plus the ellipsis");
+ }
+}
diff --git a/src/server/mcp_routes.rs b/src/server/mcp_routes.rs
index c72eb6b7..137f36a0 100644
--- a/src/server/mcp_routes.rs
+++ b/src/server/mcp_routes.rs
@@ -174,6 +174,7 @@ pub(super) async fn run_test(state: &AppState, stored: &McpServer) -> Value {
"stderr_tail": mcp::redact(&stderr_tail, &secrets) }),
};
outcome["duration_ms"] = json!(start.elapsed().as_millis() as u64);
+ super::connections::record_mcp_check(&stored.id, &outcome);
outcome
}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 5b51fa62..58a48ddc 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -34,6 +34,7 @@ pub mod loose_ends_owner;
pub mod zombie_routes;
pub mod parallel_routes;
pub mod document_routes;
+pub mod connections;
use crate::broker::PermissionBroker;
use crate::config::Config;
@@ -253,6 +254,8 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/parallel/scenarios/:id/runs", get(parallel_routes::scenario_runs))
.route("/api/parallel/runs", get(parallel_routes::list_runs))
.route("/api/parallel/runs/:id", get(parallel_routes::get_run))
+ .route("/api/connections", get(connections::list))
+ .route("/api/connections/composio", post(connections::add_composio))
.route("/api/mcp/servers", get(mcp_routes::list_servers).post(mcp_routes::create_server))
.route(
"/api/mcp/servers/:id",
diff --git a/src/server/profile_routes.rs b/src/server/profile_routes.rs
index 92d841b6..5a875770 100644
--- a/src/server/profile_routes.rs
+++ b/src/server/profile_routes.rs
@@ -107,7 +107,7 @@ pub(super) async fn keyed_ids(state: &AppState, profiles: &[LlmProfile]) -> Hash
ids
}
-async fn views(state: &AppState, profiles: Vec<LlmProfile>) -> Vec<ProfileOut> {
+pub(super) async fn views(state: &AppState, profiles: Vec<LlmProfile>) -> Vec<ProfileOut> {
let endpoints = state.db.list_profile_endpoints().await.unwrap_or_default();
// Stale checks of Custom API accounts run together, each bounded by its own timeout
futures::future::join_all(
diff --git a/tests/connections_test.rs b/tests/connections_test.rs
new file mode 100644
index 00000000..5b1c7d9a
--- /dev/null
+++ b/tests/connections_test.rs
@@ -0,0 +1,159 @@
+//! Connections: `GET /api/connections` lists MCP servers, engine accounts, saved website logins
+//! and Loose ends sources with status, last check and the bots that use them; Composio is an
+//! optional connector, off when added, and never shows its key. Person-only.
+
+mod common;
+
+use axum::http::StatusCode;
+use chrono::Utc;
+use common::*;
+use kwnt::db::{spaces::SpaceId, zombie::SourceRow};
+use kwnt::sandbox::credentials::CredentialStore;
+use kwnt::server::{continuity::SelfScope, mcp_runtime};
+use serde_json::{json, Value};
+
+fn find<'a>(list: &'a Value, id: &str) -> &'a Value {
+ list["connections"].as_array().unwrap().iter().find(|c| c["id"] == id).unwrap_or_else(|| panic!("{id} not in {list}"))
+}
+
+fn user_ids(c: &Value) -> Vec<String> {
+ c["used_by"].as_array().unwrap().iter().map(|u| u["id"].as_str().unwrap().to_string()).collect()
+}
+
+#[tokio::test]
+async fn connections_list_everything_with_status_and_users() {
+ let env = setup().await;
+
+ // An MCP server whose test fails: status error with a last check.
+ let (s, server) = call(
+ &env.app,
+ "POST",
+ "/api/mcp/servers",
+ Some(json!({"name": "broken", "transport": "stdio", "command": "false", "args": ["--token", "sk-hidden-123"]})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{server}");
+ let mcp_id = server["id"].as_str().unwrap().to_string();
+ let (_, before) = call(&env.app, "GET", "/api/connections", None).await;
+ let c = find(&before, &format!("mcp:{mcp_id}"));
+ assert_eq!(c["status"], "unknown");
+ assert!(c["last_check"].is_null());
+ assert!(user_ids(c).contains(&env.a) && user_ids(c).contains(&env.b), "every bot in the space: {c}");
+ let (_, tested) = call(&env.app, "POST", &format!("/api/mcp/servers/{mcp_id}/test"), None).await;
+ assert_eq!(tested["ok"], false, "{tested}");
+
+ // A saved login for bot a, and a mail source of Loose ends.
+ env.state.credentials.save(&env.a, "https://github.com", "octo", "pw-never-listed").await.unwrap();
+ env.state
+ .db
+ .zombie_put_source(&SourceRow {
+ id: "src1".into(),
+ kind: "imap".into(),
+ label: "Work mail".into(),
+ config: json!({"host": "imap.example.com", "port": 993, "username": "[email protected]", "folders": ["INBOX"]}).to_string(),
+ enabled: true,
+ last_scan_at: None,
+ last_status: None,
+ last_error: None,
+ created_at: Utc::now(),
+ })
+ .await
+ .unwrap();
+
+ let (s, list) = call(&env.app, "GET", "/api/connections", None).await;
+ assert_eq!(s, StatusCode::OK, "{list}");
+ let text = list.to_string();
+ assert!(!text.contains("pw-never-listed") && !text.contains("sk-hidden-123"), "no secret in the list: {text}");
+
+ let c = find(&list, &format!("mcp:{mcp_id}"));
+ assert_eq!(c["kind"], "mcp");
+ assert_eq!(c["status"], "error", "{c}");
+ assert!(c["last_check"].is_string(), "the test is the last check: {c}");
+ assert_eq!(c["detail"], "false", "the command only, never its arguments");
+ assert_eq!(c["logins_stored"], "kwnt");
+
+ let login = list["connections"].as_array().unwrap().iter().find(|c| c["kind"] == "browser_login").expect("the saved login");
+ assert_eq!(login["name"], "github.com");
+ assert_eq!(login["logins_stored"], "vault");
+ assert_eq!(user_ids(login), vec![env.a.clone()], "only the bot it was saved for");
+ assert_eq!(list["vault"]["status"], "ok");
+ assert_eq!(list["vault"]["logins"], 1);
+
+ let mail = find(&list, "source:src1");
+ assert_eq!(mail["kind"], "email");
+ assert_eq!(mail["status"], "unknown");
+ assert_eq!(mail["detail"], "[email protected] @ imap.example.com");
+
+ assert!(list["connections"].as_array().unwrap().iter().any(|c| c["kind"] == "account"), "engine accounts are listed");
+ assert!(list["counts"]["error"].as_u64().unwrap() >= 1);
+
+ // Composio is in the catalog, optional and not added.
+ let composio = &list["catalog"][0];
+ assert_eq!(composio["id"], "composio");
+ assert_eq!(composio["optional"], true);
+ assert_eq!(composio["added"], false);
+ assert_eq!(composio["logins_stored"], "composio");
+ assert!(composio["warning"].as_str().unwrap().contains("Composio's servers"));
+}
+
+#[tokio::test]
+async fn composio_is_added_off_and_keeps_its_key_hidden() {
+ let env = setup().await;
+ for bad in ["http://backend.composio.dev/v3/mcp/x", "https://composio.dev.evil.example/mcp", "https://example.com/mcp"] {
+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"url": bad}))).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{bad}: {v}");
+ }
+ let (s, added) = call(
+ &env.app,
+ "POST",
+ "/api/connections/composio",
+ Some(json!({"url": "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u1", "api_key": "ck-secret-999"})),
+ )
+ .await;
+ assert_eq!(s, StatusCode::OK, "{added}");
+ assert_eq!(added["server"]["enabled"], false, "off until the person switches it on");
+ assert!(!added.to_string().contains("ck-secret-999"), "{added}");
+ let id = added["connection_id"].as_str().unwrap().to_string();
+
+ let (s, again) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"url": "https://backend.composio.dev/v3/mcp/abc/mcp"}))).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{again}");
+
+ let (_, list) = call(&env.app, "GET", "/api/connections", None).await;
+ assert!(!list.to_string().contains("ck-secret-999"));
+ let c = find(&list, &id);
+ assert_eq!(c["status"], "off");
+ assert_eq!(c["logins_stored"], "composio");
+ assert!(c["used_by"].as_array().unwrap().is_empty(), "no bot uses it while it is off");
+ assert_eq!(list["catalog"][0]["added"], true);
+ assert_eq!(list["catalog"][0]["connection_id"], id);
+ assert_eq!(list["catalog"][0]["enabled"], false);
+
+ // the stored server really is off: no bot gets its tools
+ let server = env.state.db.list_mcp_servers(&SpaceId::default_space()).await.unwrap();
+ assert!(server.iter().any(|s| s.name == "composio" && !s.enabled));
+}
+
+#[tokio::test]
+async fn connections_are_person_only() {
+ let env = setup().await;
+ assert_eq!(call_remote(&env.app, "GET", "/api/connections").await, StatusCode::UNAUTHORIZED);
+ assert_eq!(call_remote(&env.app, "POST", "/api/connections/composio").await, StatusCode::UNAUTHORIZED);
+
+ let bot = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();
+ let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };
+ let folder = tempfile::tempdir().unwrap();
+ let (_, token) =
+ mcp_runtime::prepare_turn_with_self(&env.state, &bot, None, Some(folder.path().to_path_buf()), Some(scope)).await.unwrap();
+ let bearer = format!("Bearer {token}");
+ let (s, _) = call_with(&env.app, "GET", "/api/connections", None, &[("authorization", &bearer)]).await;
+ assert_eq!(s, StatusCode::FORBIDDEN);
+ let (s, _) = call_with(
+ &env.app,
+ "POST",
+ "/api/connections/composio",
+ Some(json!({"url": "https://backend.composio.dev/v3/mcp/abc/mcp"})),
+ &[("authorization", &bearer)],
+ )
+ .await;
+ assert_eq!(s, StatusCode::FORBIDDEN);
+}