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.

Composio: person-only app status route for the connection card

Lin (kwant bot)6c60aff8a4fa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 342bc381..1cbb4711 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
## Unreleased
### Added
+- **kwant can tell when an app finished connecting through Composio.** A new person-only
+ `GET /api/connections/composio/apps/:slug/status` answers whether you've signed in to the app, so the
+ connection card can show "Connected" once you have.
- **Bots try the way round before saying "not possible".** Bots can now read a public page's HTML with a
new `page_source` tool: meta description, canonical, robots, Open Graph tags, headings, image alt text
and structured data, which reading a page normally leaves out. When a bot lacks access to an app such
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index c7cca016..03599f8c 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -217,6 +217,12 @@ most 3 in all. The card is a message from the bot with `meta.kind = "connection_
(the person-only `POST /api/connections/composio/apps/:slug/connect` that starts the sign-in). Its text
names the steps, so it reads on its own where the app has no card for it.
+After Connect, the card polls the person-only `GET /api/connections/composio/apps/:slug/status?space=`,
+which answers `{"connected": bool}`: true once the connector's `user_id` has an `ACTIVE`, not disabled
+account for that app on Composio (`GET /api/v3.1/connected_accounts`, with the person's key). 400 for a
+bad app name; 409 when Composio isn't added, has no key, the key is refused, or the URL has no
+`user_id`; 502 when Composio fails or can't be reached. A bot's token gets 403.
+
## Agent runtime
- **Tool names** are `mcp__<server>__<tool>`.
diff --git a/src/mcp/composio.rs b/src/mcp/composio.rs
index 4f7bef61..fd46ee0d 100644
--- a/src/mcp/composio.rs
+++ b/src/mcp/composio.rs
@@ -4,7 +4,8 @@
//!
//! Sources: <https://docs.composio.dev/reference/api-reference/toolkits/getToolkits>,
//! <https://docs.composio.dev/reference/api-reference/tool-router/postToolRouterSession> and
-//! <https://docs.composio.dev/reference/api-reference/tool-router/postToolRouterSessionBySessionIdLink>.
+//! <https://docs.composio.dev/reference/api-reference/tool-router/postToolRouterSessionBySessionIdLink> and
+//! <https://docs.composio.dev/reference/api-reference/connected-accounts/getConnectedAccounts>.
use serde::Serialize;
use serde_json::{json, Value};
@@ -121,6 +122,21 @@ pub fn parse_apps(body: &Value) -> Vec<ComposioApp> {
.unwrap_or_default()
}
+/// Whether a `GET /api/v3.1/connected_accounts` answer holds a working account of `user_id` for the
+/// app `slug`. Composio filters by user, app and status already; this checks again, so a wider
+/// answer never reads as connected. Composio is dropping `user_id` from the answer, so a missing
+/// one is fine but a different one isn't.
+pub fn has_active_account(body: &Value, user_id: &str, slug: &str) -> bool {
+ body["items"].as_array().is_some_and(|items| {
+ items.iter().any(|a| {
+ a["status"] == "ACTIVE"
+ && a["toolkit"]["slug"] == slug
+ && a["is_disabled"] != json!(true)
+ && a["user_id"].as_str().is_none_or(|u| u == user_id)
+ })
+ })
+}
+
impl ComposioApi {
pub fn new(base_url: &str) -> Self {
Self {
@@ -245,6 +261,23 @@ impl ComposioApi {
ComposioError::Upstream(201, "no https redirect_url in the answer".into())
})
}
+
+ /// Whether `user_id` has a working (ACTIVE) connection to the app `slug` on Composio.
+ pub async fn is_connected(
+ &self,
+ api_key: &str,
+ user_id: &str,
+ slug: &str,
+ ) -> Result<bool, ComposioError> {
+ let mut url = self.url(&["api", "v3.1", "connected_accounts"])?;
+ url.query_pairs_mut()
+ .append_pair("user_ids", user_id)
+ .append_pair("toolkit_slugs", slug)
+ .append_pair("statuses", "ACTIVE")
+ .append_pair("limit", &PAGE.to_string());
+ let body = self.send(self.client.get(url), api_key).await?;
+ Ok(has_active_account(&body, user_id, slug))
+ }
}
#[cfg(test)]
@@ -299,4 +332,32 @@ mod tests {
assert_eq!(apps[1].logo, None, "only https logos");
assert!(parse_apps(&Value::Null).is_empty());
}
+
+ #[test]
+ fn only_an_active_enabled_account_of_this_user_and_app_counts() {
+ let account = |status: &str, slug: &str, extra: Value| {
+ let mut a = json!({"id": "ca_1", "status": status, "toolkit": {"slug": slug}});
+ for (k, v) in extra.as_object().unwrap() {
+ a[k] = v.clone();
+ }
+ json!({"items": [a], "next_cursor": null})
+ };
+ assert!(has_active_account(&account("ACTIVE", "gmail", json!({})), "u-1", "gmail"));
+ assert!(has_active_account(
+ &account("ACTIVE", "gmail", json!({"user_id": "u-1", "is_disabled": false})),
+ "u-1",
+ "gmail"
+ ));
+ for (body, why) in [
+ (account("INITIATED", "gmail", json!({})), "not finished"),
+ (account("EXPIRED", "gmail", json!({})), "expired"),
+ (account("ACTIVE", "slack", json!({})), "another app"),
+ (account("ACTIVE", "gmail", json!({"user_id": "u-2"})), "another user"),
+ (account("ACTIVE", "gmail", json!({"is_disabled": true})), "disabled"),
+ (json!({"items": []}), "none"),
+ (Value::Null, "no answer"),
+ ] {
+ assert!(!has_active_account(&body, "u-1", "gmail"), "{why}");
+ }
+ }
}
diff --git a/src/server/connections.rs b/src/server/connections.rs
index 04f6a393..a58e5bf0 100644
--- a/src/server/connections.rs
+++ b/src/server/connections.rs
@@ -555,6 +555,37 @@ pub async fn connect_composio_app(
}
}
+/// `GET /api/connections/composio/apps/:slug/status?space=`: whether the user in the connector's
+/// URL (`user_id`) has finished signing in to the app on Composio: `{"connected": bool}`. The
+/// connection card polls it after Connect. 409 when Composio can't be used for this.
+pub async fn composio_app_status(
+ State(state): State<AppState>,
+ headers: HeaderMap,
+ Scope(space): Scope,
+ axum::extract::Path(slug): axum::extract::Path<String>,
+) -> Response {
+ if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {
+ return r;
+ }
+ if !composio::valid_slug(&slug) {
+ return error(StatusCode::BAD_REQUEST, "not a Composio app name");
+ }
+ let (server, key) = match composio_with_key(&state, &space).await {
+ Ok(found) => found,
+ Err(r) => return r,
+ };
+ let Some(user_id) = server.url.as_deref().and_then(composio::user_id_of) else {
+ return error(
+ StatusCode::CONFLICT,
+ "Your Composio URL has no user_id, so kwant can't tell which Composio user to check. Check the app on composio.dev instead",
+ );
+ };
+ match state.composio_api.is_connected(&key, &user_id, &slug).await {
+ Ok(connected) => Json(json!({"connected": connected})).into_response(),
+ Err(e) => composio_failed(e),
+ }
+}
+
#[cfg(test)]
mod tests {
use super::*;
diff --git a/src/server/mod.rs b/src/server/mod.rs
index 7ee7112b..5e5a39c9 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -299,6 +299,7 @@ pub fn create_router(state: AppState) -> Router {
.route("/api/connections/composio", post(connections::add_composio))
.route("/api/connections/composio/apps", get(connections::search_composio_apps))
.route("/api/connections/composio/apps/:slug/connect", post(connections::connect_composio_app))
+ .route("/api/connections/composio/apps/:slug/status", get(connections::composio_app_status))
.route("/api/mcp/servers", get(mcp_routes::list_servers).post(mcp_routes::create_server))
.route(
"/api/mcp/servers/:id",
diff --git a/tests/composio_search_test.rs b/tests/composio_search_test.rs
index 6cea084a..79f8abd1 100644
--- a/tests/composio_search_test.rs
+++ b/tests/composio_search_test.rs
@@ -63,6 +63,27 @@ async fn fake_composio() -> (String, Seen) {
(StatusCode::CREATED, Json(json!({"redirect_url": "https://connect.composio.dev/link/ln_1", "link_token": "ln_1"})))
}),
)
+ .route(
+ "/api/v3.1/connected_accounts",
+ get(|State(seen): State<Seen>, h: HeaderMap, Query(q): Query<HashMap<String, String>>| async move {
+ let mut pairs: Vec<_> = q.iter().map(|(k, v)| format!("{k}={v}")).collect();
+ pairs.sort();
+ seen.lock().unwrap().push(("GET".into(), format!("/api/v3.1/connected_accounts?{}", pairs.join("&")), key_of(&h), Value::Null));
+ let app = q.get("toolkit_slugs").cloned().unwrap_or_default();
+ match app.as_str() {
+ "gmail" => (StatusCode::OK, Json(json!({"items": [
+ {"id": "ca_1", "status": "ACTIVE", "toolkit": {"slug": "gmail"}, "is_disabled": false}
+ ], "next_cursor": null}))),
+ // Composio ignoring a filter must not read as connected.
+ "slack" => (StatusCode::OK, Json(json!({"items": [
+ {"id": "ca_2", "status": "INITIATED", "toolkit": {"slug": "slack"}},
+ {"id": "ca_3", "status": "ACTIVE", "toolkit": {"slug": "gmail"}}
+ ], "next_cursor": null}))),
+ "broken" => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": {"message": "boom"}}))),
+ _ => (StatusCode::OK, Json(json!({"items": [], "next_cursor": null}))),
+ }
+ }),
+ )
.with_state(seen.clone());
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
@@ -379,3 +400,89 @@ async fn finding_apps_is_person_only() {
"a bot's token never reaches Composio"
);
}
+
+#[tokio::test]
+async fn app_status_tells_whether_the_sign_in_finished() {
+ let (env, seen) = env_with_fake().await;
+
+ // Not added, then added without a key: 409 and nothing sent.
+ let status = |slug: &str| format!("/api/connections/composio/apps/{slug}/status");
+ let (s, v) = call(&env.app, "GET", &status("gmail"), None).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{v}");
+ assert!(v["error"].as_str().unwrap().contains("Add the Composio connector first"), "{v}");
+ add_composio(&env, "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-1", None).await;
+ let (s, v) = call(&env.app, "GET", &status("gmail"), None).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{v}");
+ assert!(v["error"].as_str().unwrap().contains("x-api-key"), "{v}");
+ assert!(seen.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn app_status_asks_composio_for_this_user_and_app_only() {
+ let (env, seen) = env_with_fake().await;
+ add_composio(&env, "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-1", Some("ck-secret-1")).await;
+ let status = |slug: &str| format!("/api/connections/composio/apps/{slug}/status");
+
+ for slug in ["Gmail", "a.b"] {
+ let (s, _) = call(&env.app, "GET", &status(slug), None).await;
+ assert_eq!(s, StatusCode::BAD_REQUEST, "{slug}");
+ }
+ assert!(seen.lock().unwrap().is_empty(), "a bad name never reaches Composio");
+
+ let (s, v) = call(&env.app, "GET", &status("gmail"), None).await;
+ assert_eq!((s, v.clone()), (StatusCode::OK, json!({"connected": true})), "{v}");
+ let (s, v) = call(&env.app, "GET", &status("notion"), None).await;
+ assert_eq!((s, v.clone()), (StatusCode::OK, json!({"connected": false})), "{v}");
+ let (s, v) = call(&env.app, "GET", &status("slack"), None).await;
+ assert_eq!(v, json!({"connected": false}), "an unfinished sign-in or another app's account isn't this one: {s} {v}");
+ let (s, v) = call(&env.app, "GET", &status("broken"), None).await;
+ assert_eq!(s, StatusCode::BAD_GATEWAY, "{v}");
+ assert!(v["error"].as_str().unwrap().contains("boom"), "{v}");
+
+ let seen = seen.lock().unwrap().clone();
+ assert_eq!(seen.len(), 4, "{seen:?}");
+ assert!(seen.iter().all(|(_, _, key, _)| key == "ck-secret-1"));
+ assert_eq!(
+ seen[0].1,
+ "/api/v3.1/connected_accounts?limit=20&statuses=ACTIVE&toolkit_slugs=gmail&user_ids=u-1"
+ );
+}
+
+#[tokio::test]
+async fn app_status_explains_a_refused_key_or_missing_user() {
+ let (env, seen) = env_with_fake().await;
+ add_composio(&env, "https://backend.composio.dev/v3/mcp/abc/mcp", Some("ck-1")).await;
+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps/gmail/status", None).await;
+ assert_eq!(s, StatusCode::CONFLICT, "{v}");
+ assert!(v["error"].as_str().unwrap().contains("no user_id"), "{v}");
+ assert!(seen.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn app_status_is_person_only() {
+ let (env, seen) = env_with_fake().await;
+ add_composio(&env, "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-1", Some("ck-secret-1")).await;
+ let path = "/api/connections/composio/apps/gmail/status";
+ assert_eq!(call_remote(&env.app, "GET", path).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, v) = call_with(&env.app, "GET", path, None, &[("authorization", &bearer)]).await;
+ assert_eq!(s, StatusCode::FORBIDDEN, "{v}");
+ assert!(seen.lock().unwrap().is_empty(), "a bot's token never reaches Composio");
+}