Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Composio with one key, and the whole app list for autocomplete (#548)
Oleksandr Ivanchenko7db29074f347
diff --git a/docs/connections.md b/docs/connections.mdindex 72514f78..45988e0e 100644--- a/docs/connections.md+++ b/docs/connections.md@@ -141,82 +141,207 @@ empty again after a restart. Call the test route to refresh it ("Check now")."id": "composio","kind": "mcp","name": "Composio",- "description": "Hundreds of apps (Gmail, Slack, Notion, Linear…) through one MCP server you set up at composio.dev.",+ "description": "Gmail, Slack, Notion, Linear and hundreds more apps, with your free Composio key. Your bots find the tools they need themselves.","optional": true,- "added": false,- "connection_id": null,+ "added": true,+ "connection_id": "mcp:…","enabled": false,"logins_stored": "composio","warning": "Composio keeps your app sign-ins on Composio's servers, not in kwant's vault, and your bots' tool calls through it pass through Composio.","add": "/api/connections/composio",- "can_search": false,- "can_connect": false,- "search": "/api/connections/composio/apps"+ "key_url": "https://dashboard.composio.dev",+ "mode": "session",+ "user_id": "kwant-spc_default",+ "apps_connected": [{ "slug": "gmail", "name": "Gmail" }],+ "problem": null,+ "can_search": true,+ "can_connect": true,+ "can_switch": false,+ "search": "/api/connections/composio/apps",+ "switch": "/api/connections/composio/switch",+ "replace_key": "/api/connections/composio/key"}```Show `warning` next to the add button and on the connection once it is added. Once added,-`connection_id` points at the MCP connection. `can_search` is true once Composio is added with an-API key (`x-api-key` header); `can_connect` also needs a `user_id` in its URL.+`connection_id` points at the MCP connection.++| field | meaning |+|---|---|+| `mode` | `null` before Composio is added. `session`: the one-key setup with a project key (`ak_…`), where kwant made the Composio session. `connect`: a Composio Connect key (`ck_…`), used on Composio Connect's own MCP server. `url`: an MCP URL pasted from composio.dev (older setups) |+| `user_id` | the Composio user whose apps the bots use: the session's, else the `user_id` in the URL. In the one-key setup it is `kwant-<space id>`. `null` for `connect`: the key is the person's own Composio account |+| `apps_connected` | apps signed in on Composio for that user. One Composio call, cached for a minute per space (an app search or status check refreshes it). For `connect` that call is one `COMPOSIO_MANAGE_CONNECTIONS` `list` over the 120 popular apps (below), timed and logged ("Composio Connect status of the popular apps", with `ms`); when it takes over 3 seconds, the next 10 minutes list only the apps connected through kwant, with no call. Names come from catalogue searches, else the popular list, else the slug in words. Empty without a key or user, or if Composio couldn't be asked |+| `problem` | `null`, or `{message, action}` when something needs the person: a missing or refused key (`replace_key`), Composio down (`try_again`), a URL setup without a `user_id` (`switch`) |+| `can_search` | Composio is added with a key |+| `can_connect` | also knows the user (always for `session` and `connect`) |+| `can_switch` | a `url` setup: offer Switch to the one-key setup |+| `key_url` | the Composio dashboard, where the person copies their key. Composio has no stable deep link to the key: a Composio Connect key is under the AI Clients setup, a project key under Project settings › API keys |## `POST /api/connections/composio?space=`+The one-key setup, which the app uses:++```json+{ "api_key": "ck_…" | "ak_…", "enabled": false }+```++One field takes either kind of Composio key; the prefix says which:++- `ck_…`, a **Composio Connect** key: kwant checks it with the MCP `initialize` and `tools/list`+ on `https://connect.composio.dev/mcp` (header `x-consumer-api-key`; `KWNT_COMPOSIO_CONNECT_URL`+ points it elsewhere for tests), and requires `COMPOSIO_MANAGE_CONNECTIONS` among the tools. It+ saves the MCP server `composio` with that URL and the key in the `x-consumer-api-key` header,+ `mode: "connect"`, `user_id: null`. Nothing is kept in settings.+- `ak_…`, a **project** key: the session setup below.+- any other prefix: tried as a project key (one account call), then on Composio Connect. If both+ refuse it, the reply is the first refusal (`uak_…` keys get their own words).++For a project key, kwant checks the key by creating a Composio Tool Router session for the space's own Composio user+(`POST /api/v3.1/tool_router/session` with `{"user_id": "kwant-<space id>", "manage_connections": {"enable": true}}`+and no toolkit list, so every app is available and the bots find tools themselves). It saves the+session's MCP address as the MCP server `composio` with the key as its `x-api-key` header, and+keeps `{session_id, user_id, mcp_url}` in settings under `composio_session:<space id>`. The setup+counts as `session` only while the server's URL is still that `mcp_url`: a server edited or+re-added by hand is a `url` setup again. If Composio refuses the key, **nothing is saved**.++The older body still works and makes a `url` setup without calling Composio:+```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 |+| `api_key` | required without `url`. Trimmed. Sent to Composio as the `x-api-key` header (`x-consumer-api-key` for a Composio Connect key), and stored and masked like any MCP header. Never logged |+| `url` | optional. Must be `https` on `composio.dev` or one of its subdomains || `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.+Result: `{ "connection_id": "mcp:…", "server": McpServerView, "mode": "session" | "connect" | "url", "user_id": "kwant-…" | null, "tools": ["COMPOSIO_SEARCH_TOOLS", …], "warning": "…" }`.+`McpServerView` masks header values. `tools` are the session's or Composio Connect's meta tools+(empty for `url`).-Errors:+## Errors from the Composio routes-| 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) |+Every error is `{ "error": "<words for the person>", "action": "…", "key_url"?: "…" }`. `action`+is the one button that fixes it:++| `action` | button | when |+|---|---|---|+| `add_composio` | Add Composio | Composio isn't added yet, or the add body has no key |+| `replace_key` | Replace key | no key saved, Composio refused the key (`409`), or Composio is already added (`409` on add) |+| `try_again` | Try again | Composio couldn't be reached or failed (`502`) |+| `switch` | Switch to one key | a `url` setup without `user_id` can't connect apps (`409`) |++`add_composio` and `replace_key` errors carry `key_url`. The texts:++- refused key (401; for Composio Connect also 403): "Composio didn't accept this key. Copy your key again from your Composio dashboard."+- a user key (`uak_…`) refused: "That's a Composio user key (it starts with uak_). kwant needs your Composio key: copy it from your Composio dashboard. It starts with ck_ or ak_."+- a scoped key without the permission (403): "This Composio key isn't allowed to do this. Copy a full-access API key from your Composio dashboard, under Project settings › API keys."+- down, timed out or 5xx: "Composio couldn't be reached; try again in a minute."++`400` is a bad body, query or app name; `403` / `401` is not the person.++## `POST /api/connections/composio/switch?space=`++Body optional: `{ "api_key": "ak_…" }` (else the saved key). Turns a `url` setup into the one-key+setup: a session for the URL's `user_id` (so apps connected before stay connected), else for+`kwant-<space id>`. The same MCP server is updated in place, so its id, its on/off switch and the+per-bot opt-outs don't change. A refused key changes nothing. Idempotent: a `session` or+`connect` setup answers `switched: false` without calling Composio.++Result: `{ "connection_id", "server", "mode": "session", "user_id", "tools"?, "switched": bool }`.++## `PUT /api/connections/composio/key?space=`++Body `{ "api_key": "ck_…" | "ak_…" }`, either kind, checked as on add before anything is saved; a+refused key changes nothing. The same MCP server is updated in place either way, so its id, its+switch and the per-bot opt-outs stay. A `ck_` key makes the setup `connect` (URL and header+replaced). An `ak_` key in place of a `ck_` one gets a session for `kwant-<space id>`+(`mode: "session"`, `session_renewed: true`). Otherwise, in the one-key setup+kwant reads the saved session with the new key: a key of the same Composio project keeps the+session; a key of another project (or a deleted session) gets a new session for the **same user**,+on the same MCP server. In a `url` setup the key is checked with one account call and only the+header changes.++Result: `{ "connection_id", "server", "mode", "user_id", "session_renewed": bool }`.Composio appears as an ordinary MCP server in `/api/mcp/servers`, so switching it on or off, theper-bot opt-outs, testing and removing all use those routes.## Find an app on Composio-Both routes are person-only, refuse bot tokens, and use the person's own Composio key from the-connector's `x-api-key` header. Until Composio is added with a key they answer `409` **without-contacting Composio**; nothing else in kwant calls Composio's API. The key is never echoed.-`KWNT_COMPOSIO_API_URL` points them at another API address (tests).+These routes are person-only, refuse bot tokens, and use the person's own Composio key from the+connector's header. Before Composio is added the app list answers from kwant's bundled popular+apps and the other routes answer `409`, both **without contacting Composio**; added without a key,+they answer `409`. The key is never echoed or logged. `KWNT_COMPOSIO_API_URL` points them at+another API address and `KWNT_COMPOSIO_CONNECT_URL` at another Composio Connect (tests).++`source` in the list and search replies says where the apps come from: `"all"` is Composio's+catalogue (a project key); `"popular"` is Composio's 120 most popular apps, bundled with kwant in+`src/mcp/composio_popular.json` (`slug`, `name`, `rank` from 0, https `logo`). Composio Connect+has no catalogue call, so a `ck_` setup lists those too. Regenerate the file at release with+`python3 scripts/composio_popular_apps.py` (it reads composio.dev/toolkits and refuses to write+fewer than 50 apps).++| setup | no `q` | `q` |+|---|---|---|+| not added | popular, `connected: false`, `mode: null`, `can_connect: false`, no call | popular matches (name or slug starting with `q` first), up to 20, no call |+| `connect` | popular, `connected` from the one-minute `apps_connected` cache | popular matches, up to 20; `connected` from that cache if fresh, else one `list` call for just those apps, kept a minute |+| `session`, `url` | the whole catalogue, `source: "all"` (below) | Composio's search, `source: "all"` (below) |++### `GET /api/connections/composio/apps?space=` (no `q`): the whole catalogue++For autocomplete: the UI loads this once and matches each keystroke in the browser, with no call+per key. kwant pages Composio's `GET /api/v3.1/toolkits?sort_by=usage&limit=500[&cursor=…]`+(at most 20 pages, duplicates dropped) and keeps the list **24 hours per key** in memory. A list+older than that is still served at once while one background fetch replaces it. The `connected`+flags come from the one-minute connected-apps cache, so a listing costs at most one+`connected_accounts` call.++```json+{ "apps": [{ "slug": "gmail", "name": "Gmail", "logo": "https://…", "tools_count": 23, "connected": true }],+ "count": 1, "fetched_at": "2026-11-12T22:30:00Z", "connected_checked": true,+ "mode": "session", "can_connect": true, "warning": "…" }+```++Rows are compact: no description; `logo` (https only) and `tools_count` are left out when+Composio has none. The order is Composio's usage order. The reply carries `ETag` and+`Cache-Control: private, no-cache`; send it back as `If-None-Match` (weak `W/` tags and lists are+accepted) and an unchanged list answers `304` with no body. The tag changes when the list is+refetched, the connected apps change, or the setup's mode or user changes. Composio needs a key+even to list apps (`401` without one), so before setup kwant answers with its popular list. The+server does not gzip; a reverse proxy can.### `GET /api/connections/composio/apps?q=&space=`-`q` is 1–60 characters. kwant calls Composio's `GET /api/v3.1/toolkits?search=…&sort_by=usage&limit=20`.+`q` is 1–60 characters. kwant calls Composio's `GET /api/v3.1/toolkits?search=…&sort_by=usage&limit=20`,+then **one** `GET /api/v3.1/connected_accounts?user_ids=<user>&statuses=ACTIVE&limit=200` for the+whole page.```json-{ "apps": [{ "slug": "gmail", "name": "Gmail", "description": "…", "logo": "https://…", "tools_count": 23, "no_auth": false }],- "can_connect": true, "warning": "…" }+{ "apps": [{ "slug": "gmail", "name": "Gmail", "description": "…", "logo": "https://…", "tools_count": 23, "no_auth": false, "connected": true }],+ "connected_checked": true, "mode": "session", "can_connect": true, "warning": "…" }```-Apps without a plain slug are left out; `logo` is kept only when it is `https`.+Apps without a plain slug are left out; `logo` is kept only when it is `https`. If the account call+fails, the search still answers with every `connected: false` and `connected_checked: false`.### `POST /api/connections/composio/apps/:slug/connect?space=`-Creates a Composio session for the `user_id` in the connector's URL-(`POST /api/v3.1/tool_router/session`), then a sign-in link for the app-(`POST /api/v3.1/tool_router/session/:id/link`). Result: `{ "redirect_url": "https://…", "warning": "…" }`.-The person finishes signing in on Composio's site. A Composio MCP server set up with a fixed list-of apps may need the new app added to it on composio.dev before its tools reach bots.+With a Composio Connect key: one `COMPOSIO_MANAGE_CONNECTIONS` call with+`{"toolkits": [{"name": "<slug>", "action": "add"}]}`, and its `results.<slug>.redirect_url`+(only `https` on `composio.dev` or a subdomain). In the one-key setup: a sign-in link from the+saved session (`POST /api/v3.1/tool_router/session/:id/link`). In a `url` setup: a new session for the URL's+`user_id`, then the link. Result: `{ "redirect_url": "https://…", "warning": "…" }`. The person+finishes signing in on Composio's site. A Composio MCP server set up with a fixed list of apps may+need the new app added to it on composio.dev before its tools reach bots; the one-key session has+every app.-| status | when |-|---|---|-| `400` | `q` is empty or too long, or `slug` isn't `[a-z0-9_-]` |-| `409` | Composio isn't added, has no API key, Composio refused the key, or (connect) the URL has no `user_id` |-| `502` | Composio couldn't be reached or answered with an error |-| `403` / `401` | not the person |+### `GET /api/connections/composio/apps/:slug/status?space=`++`{ "connected": bool }` for the setup's user, and it updates `apps_connected`. With a Composio+Connect key it is one `COMPOSIO_MANAGE_CONNECTIONS` `list` call for that app (`status: "active"`,+or an active account), never `COMPOSIO_SEARCH_TOOLS`.## Known limitsdiff --git a/scripts/composio_popular_apps.py b/scripts/composio_popular_apps.pynew file mode 100644index 00000000..681b0be2--- /dev/null+++ b/scripts/composio_popular_apps.py@@ -0,0 +1,70 @@+#!/usr/bin/env python3+"""Regenerates src/mcp/composio_popular.json: Composio's most popular apps (slug, name, logo,+rank), read from the public https://composio.dev/toolkits page. No key is needed.++kwant shows this list in Find a tool before Composio is added, and with a Composio Connect+(`ck_`) key, which can't list Composio's catalogue. Run it at release:++ python3 scripts/composio_popular_apps.py # fetch and write+ python3 scripts/composio_popular_apps.py page.html # from a saved copy of the page+"""++import json+import re+import sys+import urllib.request+from pathlib import Path++URL = "https://composio.dev/toolkits"+OUT = Path(__file__).resolve().parent.parent / "src" / "mcp" / "composio_popular.json"+SLUG = re.compile(r"^[a-z0-9_-]{1,64}$")+MAX_APPS = 120+++def page_text(argv):+ if len(argv) > 1:+ return Path(argv[1]).read_text(encoding="utf-8", errors="replace")+ req = urllib.request.Request(URL, headers={"User-Agent": "Mozilla/5.0 (kwant release script)"})+ with urllib.request.urlopen(req, timeout=60) as resp:+ return resp.read().decode("utf-8", errors="replace")+++def flight_data(html):+ """The page's Next.js data: every `self.__next_f.push([1,"…"])` string, decoded and joined."""+ parts = []+ for m in re.finditer(r'self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)', html):+ parts.append(json.loads(m.group(1)))+ return "".join(parts)+++def toolkits(data):+ start = data.find('"toolkits":[')+ if start < 0:+ raise SystemExit("no toolkits list on the page: has composio.dev/toolkits changed?")+ items, _ = json.JSONDecoder().raw_decode(data, start + len('"toolkits":'))+ apps, seen = [], set()+ for t in sorted(items, key=lambda t: t.get("rank", 1 << 30)):+ slug, name, logo = t.get("slug"), t.get("name"), t.get("logo")+ if not isinstance(slug, str) or not SLUG.match(slug) or slug in seen or not isinstance(name, str):+ continue+ seen.add(slug)+ app = {"slug": slug, "name": name.strip()[:80], "rank": len(apps)}+ if isinstance(logo, str) and logo.startswith("https://") and len(logo) <= 300:+ app["logo"] = logo+ apps.append(app)+ if len(apps) == MAX_APPS:+ break+ if len(apps) < 50:+ raise SystemExit(f"only {len(apps)} apps found; not writing")+ return apps+++def main(argv):+ apps = toolkits(flight_data(page_text(argv)))+ lines = ",\n".join(json.dumps(a, ensure_ascii=False, separators=(",", ":")) for a in apps)+ OUT.write_text("[\n" + lines + "\n]\n", encoding="utf-8")+ print(f"wrote {len(apps)} apps to {OUT}")+++if __name__ == "__main__":+ main(sys.argv)diff --git a/src/mcp/composio.rs b/src/mcp/composio.rsindex fd46ee0d..0456ddc2 100644--- a/src/mcp/composio.rs+++ b/src/mcp/composio.rs@@ -6,9 +6,18 @@//! <https://docs.composio.dev/reference/api-reference/tool-router/postToolRouterSession> and//! <https://docs.composio.dev/reference/api-reference/tool-router/postToolRouterSessionBySessionIdLink> and//! <https://docs.composio.dev/reference/api-reference/connected-accounts/getConnectedAccounts>.+//!+//! A Composio Connect key (`ck_…`, a consumer key) works on none of those: it works only on+//! Composio Connect, an MCP server (<https://docs.composio.dev/docs/composio-connect>). kwnt+//! checks such a key, starts sign-ins and reads which apps are connected through that server's+//! own `COMPOSIO_MANAGE_CONNECTIONS` tool, with kwnt's MCP client.-use serde::Serialize;+use super::client::{McpClient, McpError};+use crate::db::models::McpServer;+use serde::{Deserialize, Serialize};use serde_json::{json, Value};+use std::collections::BTreeSet;+use std::sync::OnceLock;use std::time::Duration;pub const DEFAULT_API_URL: &str = "https://backend.composio.dev";@@ -20,6 +29,138 @@ const MAX_BODY: usize = 2 * 1024 * 1024;pub const MAX_QUERY_CHARS: usize = 60;/// How many apps one search returns.const PAGE: usize = 20;+/// The whole-catalogue listing: pages of this many apps, at most this many pages.+const LIST_PAGE: usize = 500;+const MAX_LIST_PAGES: usize = 20;++/// Composio Connect: the MCP server a consumer key (`ck_…`) works on, sent as+/// [`CONNECT_KEY_HEADER`]. Stateless streamable HTTP that answers as an event stream.+pub const CONNECT_MCP_URL: &str = "https://connect.composio.dev/mcp";+/// Points kwnt's own Composio Connect calls at another address (tests).+pub const CONNECT_URL_ENV: &str = "KWNT_COMPOSIO_CONNECT_URL";+/// The header a project key (`ak_…`) goes in.+pub const PROJECT_KEY_HEADER: &str = "x-api-key";+/// The header a Composio Connect key (`ck_…`) goes in.+pub const CONNECT_KEY_HEADER: &str = "x-consumer-api-key";+/// The Composio Connect tool kwnt uses for sign-ins and status: `add` and `list`, never anything+/// that runs an app's tools.+pub const MANAGE_TOOL: &str = "COMPOSIO_MANAGE_CONNECTIONS";+/// Composio Connect calls get this long (the MCP handshake and one call).+const CONNECT_TIMEOUT_SECS: i64 = 15;+/// Most apps one `list` call asks about.+pub const MAX_STATUS_SLUGS: usize = 120;++/// Which kind of Composio key, from its prefix.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum KeyKind {+ /// `ak_…`: a project API key, for Composio's REST API (`x-api-key`).+ Project,+ /// `ck_…`: a Composio Connect key, for its MCP server only (`x-consumer-api-key`).+ Connect,+}++/// The kind a key's prefix says it is; `None` for any other prefix (kwnt tries both).+pub fn key_kind(key: &str) -> Option<KeyKind> {+ if key.starts_with("ak_") {+ Some(KeyKind::Project)+ } else if key.starts_with("ck_") {+ Some(KeyKind::Connect)+ } else {+ None+ }+}++/// One of Composio's most popular apps, bundled with kwnt (`composio_popular.json`, made by+/// `scripts/composio_popular_apps.py` from the public composio.dev/toolkits page at release).+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+pub struct PopularApp {+ pub slug: String,+ pub name: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub logo: Option<String>,+ pub rank: u32,+}++/// Composio's popular apps, most popular first: shown before Composio is added and with a+/// Composio Connect key, which can't list the catalogue.+pub fn popular_apps() -> &'static [PopularApp] {+ static APPS: OnceLock<Vec<PopularApp>> = OnceLock::new();+ APPS.get_or_init(|| {+ let mut apps: Vec<PopularApp> = serde_json::from_str(include_str!("composio_popular.json"))+ .expect("src/mcp/composio_popular.json is valid");+ apps.retain(|a| valid_slug(&a.slug) && a.logo.as_deref().is_none_or(|l| l.starts_with("https://")));+ apps.sort_by_key(|a| a.rank);+ apps+ })+}++/// Popular apps matching `query` (name or slug, any case): those starting with it first, then+/// those containing it, each in popularity order; at most `limit`.+pub fn search_popular(query: &str, limit: usize) -> Vec<&'static PopularApp> {+ let q = query.trim().to_lowercase();+ let words = |a: &PopularApp| (a.name.to_lowercase(), a.slug.clone());+ let (mut first, mut then) = (Vec::new(), Vec::new());+ for a in popular_apps() {+ let (name, slug) = words(a);+ if name.starts_with(&q) || slug.starts_with(&q) || name.split(' ').any(|w| w.starts_with(&q)) {+ first.push(a);+ } else if name.contains(&q) || slug.contains(&q) {+ then.push(a);+ }+ }+ first.extend(then);+ first.truncate(limit);+ first+}++/// The `results` of a `COMPOSIO_MANAGE_CONNECTIONS` answer (`{"successful", "data": {"results":+/// {<slug>: …}}}`), or why there are none.+pub fn manage_results(text: &str) -> Result<Value, ComposioError> {+ let body: Value = serde_json::from_str(text.trim())+ .map_err(|_| ComposioError::Upstream(200, "Composio Connect answered something kwant can't read".into()))?;+ if body["successful"] == json!(false) {+ let why = body["error"].as_str().or_else(|| body["data"]["message"].as_str()).unwrap_or_default();+ return Err(ComposioError::Upstream(200, clip(why, 200)));+ }+ let results = body["data"]["results"].clone();+ let results = if results.is_object() { results } else { body["results"].clone() };+ if results.is_object() {+ Ok(results)+ } else {+ Err(ComposioError::Upstream(200, "Composio Connect's answer has no results".into()))+ }+}++/// Whether one app's `list` result has a working account: its `status` is `active`, or one of+/// its accounts' is.+pub fn result_active(entry: &Value) -> bool {+ let active = |v: &Value| v.as_str().is_some_and(|s| s.eq_ignore_ascii_case("active"));+ active(&entry["status"])+ || entry["accounts"].as_array().is_some_and(|a| a.iter().any(|acc| active(&acc["status"])))+}++/// The HTTP status in an MCP client error ("HTTP 401 Unauthorized"), if it carries one.+fn http_status(message: &str) -> Option<u16> {+ let at = message.find("HTTP ")?;+ message[at + 5..].get(..3)?.parse().ok()+}++/// A failed Composio Connect call, in [`ComposioError`] terms: 401 or 403 is the key.+fn connect_error(e: McpError) -> ComposioError {+ let message = match e {+ McpError::Unauthorized { .. } => return ComposioError::KeyRefused,+ McpError::Rpc { message, .. } | McpError::Protocol(message) => {+ return ComposioError::Upstream(200, clip(&message, 200));+ }+ McpError::Startup { message, .. } | McpError::Transport(message) | McpError::Spawn(message) => message,+ McpError::Timeout(..) | McpError::Closed => return ComposioError::Unreachable,+ };+ match http_status(&message) {+ Some(401 | 403) => ComposioError::KeyRefused,+ Some(status) => ComposioError::Upstream(status, String::new()),+ None => ComposioError::Unreachable,+ }+}/// One app (Composio calls it a toolkit), as kwnt shows it.#[derive(Debug, Clone, Serialize, PartialEq)]@@ -34,11 +175,18 @@ pub struct ComposioApp {pub no_auth: bool,}+/// Where a person gets a Composio key. Composio documents no deep link for a Composio Connect key+/// ("Copy your consumer API key from the AI Clients setup in the Composio dashboard"; checked+/// 2026-11-12, signed out the dashboard sends a visitor to Composio's sign-in), so the dashboard.+pub const KEY_PAGE: &str = "https://dashboard.composio.dev";+/// Why a Composio call failed, in words for the person.#[derive(Debug, Clone, PartialEq)]pub enum ComposioError {- /// Composio refused the API key (401/403).+ /// Composio refused the API key (401).KeyRefused,+ /// The key is valid but not allowed to do this (403: a scoped project key).+ KeyNoAccess,/// Composio answered with an error; carries a short message.Upstream(u16, String),Unreachable,@@ -47,16 +195,100 @@ pub enum ComposioError {impl ComposioError {pub fn message(&self) -> String {match self {- Self::KeyRefused => "Composio refused the API key saved with the Composio connector. Check it under its MCP server.".into(),+ Self::KeyRefused => "Composio didn't accept this key. Copy your key again from your Composio dashboard.".into(),+ Self::KeyNoAccess => "This Composio key isn't allowed to do this. Copy a full-access API key from your \+ Composio dashboard, under Project settings › API keys."+ .into(),+ Self::Upstream(status, _) if *status >= 500 => "Composio couldn't be reached; try again in a minute.".into(),Self::Upstream(status, m) if m.is_empty() => format!("Composio answered HTTP {status}; try again later."),Self::Upstream(status, m) => format!("Composio answered HTTP {status}: {m}"),- Self::Unreachable => "Composio couldn't be reached; try again later.".into(),+ Self::Unreachable => "Composio couldn't be reached; try again in a minute.".into(),+ }+ }++ /// The one thing the person can do about it: `replace_key` or `try_again`.+ pub fn action(&self) -> &'static str {+ match self {+ Self::KeyRefused | Self::KeyNoAccess => "replace_key",+ _ => "try_again",}}++ /// The key is the problem (refused or not allowed).+ pub fn is_key(&self) -> bool {+ matches!(self, Self::KeyRefused | Self::KeyNoAccess)+ }+}++/// A Tool Router session: one Composio user's MCP server with Composio's search, connect and+/// execute tools, over every app in the catalogue.+#[derive(Debug, Clone, PartialEq)]+pub struct Session {+ pub session_id: String,+ /// The session's MCP address, always https on composio.dev.+ pub mcp_url: String,+ pub user_id: String,+ /// The tools a bot gets (`COMPOSIO_SEARCH_TOOLS`, `COMPOSIO_MANAGE_CONNECTIONS`…).+ pub tools: Vec<String>,+}++/// The Composio user kwant picks for a space when nothing older names one.+pub fn space_user_id(space: &str) -> String {+ format!("kwant-{space}")+}++/// Whether `url` is an https address on composio.dev, the only place a Composio key may go.+pub fn is_composio_https(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 valid_session_id(id: &str) -> bool {+ !id.is_empty() && id.len() <= 128 && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')+}++/// A session from a `POST /api/v3.1/tool_router/session` answer. The MCP address must be https on+/// composio.dev: kwant sends the key there with every bot call.+pub fn parse_session(body: &Value, user_id: &str) -> Result<Session, ComposioError> {+ let session_id = body["session_id"]+ .as_str()+ .filter(|s| valid_session_id(s))+ .ok_or_else(|| ComposioError::Upstream(201, "no session_id in the answer".into()))?;+ let mcp_url = body["mcp"]["url"]+ .as_str()+ .filter(|u| u.len() <= 2048 && is_composio_https(u))+ .ok_or_else(|| ComposioError::Upstream(201, "no https composio.dev MCP address in the answer".into()))?;+ let tools = body["tool_router_tools"]+ .as_array()+ .map(|t| t.iter().filter_map(|n| n.as_str()).filter(|n| n.len() <= 128).take(64).map(str::to_string).collect())+ .unwrap_or_default();+ Ok(Session { session_id: session_id.into(), mcp_url: mcp_url.into(), user_id: user_id.into(), tools })+}++/// The apps (toolkit slugs) with a working account of `user_id` in a `GET connected_accounts`+/// answer, checked the same way as [`has_active_account`].+pub fn active_apps(body: &Value, user_id: &str) -> std::collections::BTreeSet<String> {+ body["items"]+ .as_array()+ .map(|items| {+ items+ .iter()+ .filter(|a| {+ a["status"] == "ACTIVE"+ && a["is_disabled"] != json!(true)+ && a["user_id"].as_str().is_none_or(|u| u == user_id)+ })+ .filter_map(|a| a["toolkit"]["slug"].as_str().filter(|s| valid_slug(s)).map(str::to_string))+ .collect()+ })+ .unwrap_or_default()}pub struct ComposioApi {base_url: String,+ /// Composio Connect's MCP address, for `ck_` keys.+ connect_url: String,client: reqwest::Client,}@@ -138,9 +370,14 @@ pub fn has_active_account(body: &Value, user_id: &str, slug: &str) -> bool {}impl ComposioApi {+ /// The Composio API at `base_url`. Composio Connect is Composio's own for Composio's API,+ /// else `<base_url>/connect/mcp`, so a fake Composio serves both.pub fn new(base_url: &str) -> Self {+ let base_url = base_url.trim_end_matches('/').to_string();+ let connect_url = if base_url == DEFAULT_API_URL { CONNECT_MCP_URL.to_string() } else { format!("{base_url}/connect/mcp") };Self {- base_url: base_url.trim_end_matches('/').to_string(),+ connect_url,+ base_url,client: reqwest::Client::builder().timeout(TIMEOUT)// the key goes in a header: never follow a redirect to another host with it@@ -151,12 +388,87 @@ impl ComposioApi {}}- /// [`API_URL_ENV`], else Composio's own API.+ /// [`API_URL_ENV`], else Composio's own API; [`CONNECT_URL_ENV`] for Composio Connect.pub fn from_env() -> Self {let url = std::env::var(API_URL_ENV).ok().filter(|u| u.starts_with("http"));- Self::new(url.as_deref().unwrap_or(DEFAULT_API_URL))+ let api = Self::new(url.as_deref().unwrap_or(DEFAULT_API_URL));+ match std::env::var(CONNECT_URL_ENV).ok().filter(|u| u.starts_with("http")) {+ Some(c) => api.with_connect_url(&c),+ None => api,+ }+ }++ /// The same API with Composio Connect at `url`.+ pub fn with_connect_url(mut self, url: &str) -> Self {+ self.connect_url = url.to_string();+ self+ }++ /// Composio Connect as an MCP server with `key`, for kwnt's own calls (never saved).+ fn connect_server(&self, key: &str) -> McpServer {+ McpServer {+ id: "composio-connect".into(),+ name: "composio".into(),+ transport: "http".into(),+ command: None,+ args: vec![],+ url: Some(self.connect_url.clone()),+ env: Default::default(),+ headers: std::collections::BTreeMap::from([(CONNECT_KEY_HEADER.to_string(), key.to_string())]),+ enabled: true,+ timeout_secs: CONNECT_TIMEOUT_SECS,+ created_at: None,+ }+ }++ /// Checks a Composio Connect key: the MCP handshake and `tools/list`. Returns the tools a bot+ /// gets; Composio Connect without [`MANAGE_TOOL`] isn't one kwnt can use.+ pub async fn check_connect_key(&self, key: &str) -> Result<Vec<String>, ComposioError> {+ let mut client = McpClient::connect(&self.connect_server(key), None).await.map_err(connect_error)?;+ let tools = client.list_tools().await.map_err(connect_error);+ client.shutdown().await;+ let tools: Vec<String> = tools?.into_iter().map(|t| t.name).filter(|n| n.len() <= 128).take(64).collect();+ if !tools.iter().any(|t| t == MANAGE_TOOL) {+ return Err(ComposioError::Upstream(200, format!("Composio Connect has no {MANAGE_TOOL} tool")));+ }+ Ok(tools)+ }++ /// One `COMPOSIO_MANAGE_CONNECTIONS` call on Composio Connect; its `results`.+ async fn manage(&self, key: &str, toolkits: Value) -> Result<Value, ComposioError> {+ let mut client = McpClient::connect(&self.connect_server(key), None).await.map_err(connect_error)?;+ let result = client.call_tool(MANAGE_TOOL, json!({"toolkits": toolkits})).await.map_err(connect_error);+ client.shutdown().await;+ let result = result?;+ if result.is_error {+ return Err(ComposioError::Upstream(200, clip(&result.text, 200)));+ }+ manage_results(&result.text)+ }++ /// Starts signing in to the app `slug` through Composio Connect (`add`): the address the+ /// person opens, only ever https on composio.dev.+ pub async fn connect_add_link(&self, key: &str, slug: &str) -> Result<String, ComposioError> {+ let results = self.manage(key, json!([{"name": slug, "action": "add"}])).await?;+ results[slug]["redirect_url"]+ .as_str()+ .filter(|u| u.len() <= 2048 && is_composio_https(u))+ .map(str::to_string)+ .ok_or_else(|| ComposioError::Upstream(200, "no https composio.dev sign-in link in the answer".into()))+ }++ /// Which of `slugs` have a working account on Composio Connect, in one `list` call (no side+ /// effects). At most [`MAX_STATUS_SLUGS`]; slugs that aren't slugs are left out.+ pub async fn connect_active(&self, key: &str, slugs: &[&str]) -> Result<BTreeSet<String>, ComposioError> {+ let asked: Vec<&str> = slugs.iter().copied().filter(|s| valid_slug(s)).take(MAX_STATUS_SLUGS).collect();+ if asked.is_empty() {+ return Ok(BTreeSet::new());+ }+ let toolkits: Vec<Value> = asked.iter().map(|s| json!({"name": s, "action": "list"})).collect();+ let results = self.manage(key, Value::Array(toolkits)).await?;+ Ok(asked.into_iter().filter(|s| result_active(&results[*s])).map(str::to_string).collect())}fn url(&self, segments: &[&str]) -> Result<reqwest::Url, ComposioError> {@@ -194,9 +506,12 @@ impl ComposioApi {));}let value: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);- if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {+ if status == reqwest::StatusCode::UNAUTHORIZED {return Err(ComposioError::KeyRefused);}+ if status == reqwest::StatusCode::FORBIDDEN {+ return Err(ComposioError::KeyNoAccess);+ }if !status.is_success() {let message = value["error"]["message"].as_str()@@ -208,6 +523,35 @@ impl ComposioApi {}/// Apps whose name, slug or description match `query`.+ /// Composio's whole app catalogue, most used first, paged through with `cursor` (at most+ /// `MAX_LIST_PAGES` pages of `LIST_PAGE`). Duplicate or unusable slugs are left out.+ pub async fn all_apps(&self, api_key: &str) -> Result<Vec<ComposioApp>, ComposioError> {+ let mut apps: Vec<ComposioApp> = Vec::new();+ let mut seen = std::collections::HashSet::new();+ let mut cursor: Option<String> = None;+ for _ in 0..MAX_LIST_PAGES {+ let mut url = self.url(&["api", "v3.1", "toolkits"])?;+ {+ let mut q = url.query_pairs_mut();+ q.append_pair("sort_by", "usage").append_pair("limit", &LIST_PAGE.to_string());+ if let Some(c) = &cursor {+ q.append_pair("cursor", c);+ }+ }+ let body = self.send(self.client.get(url), api_key).await?;+ for app in parse_apps(&body) {+ if seen.insert(app.slug.clone()) {+ apps.push(app);+ }+ }+ cursor = body["next_cursor"].as_str().filter(|c| !c.is_empty() && c.len() <= 512).map(str::to_string);+ if cursor.is_none() {+ break;+ }+ }+ Ok(apps)+ }+pub async fn search(&self,api_key: &str,@@ -222,8 +566,60 @@ impl ComposioApi {Ok(parse_apps(&body))}+ /// Creates a Tool Router session for `user_id` over every app (no toolkit list), with+ /// connection management on, so a bot can find any app's tools and ask to connect one.+ /// This is also the key check: a refused key fails here and nothing is kept.+ pub async fn create_session(&self, api_key: &str, user_id: &str) -> Result<Session, ComposioError> {+ let body = self+ .send(+ self.client+ .post(self.url(&["api", "v3.1", "tool_router", "session"])?)+ .json(&json!({"user_id": user_id, "manage_connections": {"enable": true}})),+ api_key,+ )+ .await?;+ parse_session(&body, user_id)+ }++ /// The user of session `session_id` as this key's project sees it; `None` when the project+ /// has no such session (another project's key, or a deleted session).+ pub async fn session_user(&self, api_key: &str, session_id: &str) -> Result<Option<String>, ComposioError> {+ if !valid_session_id(session_id) {+ return Ok(None);+ }+ match self.send(self.client.get(self.url(&["api", "v3.1", "tool_router", "session", session_id])?), api_key).await {+ Ok(body) => Ok(body["config"]["user_id"].as_str().or_else(|| body["user_id"].as_str()).map(str::to_string)),+ Err(ComposioError::Upstream(400 | 404, _)) => Ok(None),+ Err(e) => Err(e),+ }+ }++ /// One cheap authenticated call: `Ok` when Composio takes the key.+ pub async fn check_key(&self, api_key: &str) -> Result<(), ComposioError> {+ let mut url = self.url(&["api", "v3.1", "connected_accounts"])?;+ url.query_pairs_mut().append_pair("limit", "1");+ self.send(self.client.get(url), api_key).await.map(|_| ())+ }++ /// A sign-in link for the app `slug` in an existing session.+ pub async fn session_link(&self, api_key: &str, session_id: &str, slug: &str) -> Result<String, ComposioError> {+ if !valid_session_id(session_id) {+ return Err(ComposioError::Upstream(0, "the saved session id isn't valid".into()));+ }+ let link = self+ .send(+ self.client+ .post(self.url(&["api", "v3.1", "tool_router", "session", session_id, "link"])?)+ .json(&json!({"toolkit": slug})),+ api_key,+ )+ .await?;+ https_or_none(&link["redirect_url"])+ .ok_or_else(|| ComposioError::Upstream(201, "no https redirect_url in the answer".into()))+ }+/// Starts signing `user_id` in to the app `slug`: a session for the user, then a sign-in link- /// for the app. Returns the https address the person opens.+ /// for the app. Returns the https address the person opens. (Setups made from an MCP URL.)pub async fn connect_link(&self,api_key: &str,@@ -242,24 +638,22 @@ impl ComposioApi {.as_str().filter(|s| !s.is_empty() && s.len() <= 256).ok_or_else(|| ComposioError::Upstream(200, "no session_id in the answer".into()))?;- let link = self- .send(- self.client- .post(self.url(&[- "api",- "v3.1",- "tool_router",- "session",- session_id,- "link",- ])?)- .json(&json!({"toolkit": slug})),- api_key,- )- .await?;- https_or_none(&link["redirect_url"]).ok_or_else(|| {- ComposioError::Upstream(201, "no https redirect_url in the answer".into())- })+ self.session_link(api_key, session_id, slug).await+ }++ /// Every app `user_id` has a working account for, in one call.+ pub async fn connected_apps(+ &self,+ api_key: &str,+ user_id: &str,+ ) -> Result<std::collections::BTreeSet<String>, ComposioError> {+ let mut url = self.url(&["api", "v3.1", "connected_accounts"])?;+ url.query_pairs_mut()+ .append_pair("user_ids", user_id)+ .append_pair("statuses", "ACTIVE")+ .append_pair("limit", "200");+ let body = self.send(self.client.get(url), api_key).await?;+ Ok(active_apps(&body, user_id))}/// Whether `user_id` has a working (ACTIVE) connection to the app `slug` on Composio.@@ -333,6 +727,111 @@ mod tests {assert!(parse_apps(&Value::Null).is_empty());}+ #[test]+ fn a_session_must_point_its_mcp_server_at_composio_over_https() {+ let ok = json!({"session_id": "trs_1", "mcp": {"type": "http", "url": "https://backend.composio.dev/tool_router/trs_1/mcp"},+ "tool_router_tools": ["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_MANAGE_CONNECTIONS"]});+ let s = parse_session(&ok, "kwant-spc_default").unwrap();+ assert_eq!(s.mcp_url, "https://backend.composio.dev/tool_router/trs_1/mcp");+ assert_eq!(s.tools, ["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_MANAGE_CONNECTIONS"]);+ for url in ["http://backend.composio.dev/x", "https://evil.example/mcp", "https://composio.dev.evil.example/mcp"] {+ let mut bad = ok.clone();+ bad["mcp"]["url"] = json!(url);+ assert!(parse_session(&bad, "u").is_err(), "{url}");+ }+ let mut bad = ok.clone();+ bad["session_id"] = json!("../x");+ assert!(parse_session(&bad, "u").is_err());+ }++ #[test]+ fn active_apps_are_the_working_accounts_of_this_user() {+ let body = json!({"items": [+ {"status": "ACTIVE", "toolkit": {"slug": "gmail"}},+ {"status": "ACTIVE", "toolkit": {"slug": "slack"}, "user_id": "someone-else"},+ {"status": "INITIATED", "toolkit": {"slug": "notion"}},+ {"status": "ACTIVE", "toolkit": {"slug": "github"}, "is_disabled": true},+ {"status": "ACTIVE", "toolkit": {"slug": "../x"}}+ ]});+ assert_eq!(active_apps(&body, "u-1").into_iter().collect::<Vec<_>>(), ["gmail"]);+ assert_eq!(space_user_id("spc_default"), "kwant-spc_default");+ }++ #[test]+ fn errors_say_what_to_do() {+ assert_eq!(ComposioError::KeyRefused.message(), "Composio didn't accept this key. Copy your key again from your Composio dashboard.");+ assert!(!ComposioError::KeyRefused.message().contains("ak_"), "either kind of key works");+ assert_eq!(ComposioError::KeyRefused.action(), "replace_key");+ assert_eq!(ComposioError::KeyNoAccess.action(), "replace_key");+ assert_eq!(ComposioError::Unreachable.message(), "Composio couldn't be reached; try again in a minute.");+ assert_eq!(ComposioError::Upstream(500, "boom".into()).action(), "try_again");+ assert!(!ComposioError::KeyRefused.message().contains("MCP server"));+ }++ #[test]+ fn the_key_prefix_says_its_kind() {+ assert_eq!(key_kind("ak_x"), Some(KeyKind::Project));+ assert_eq!(key_kind("ck_x"), Some(KeyKind::Connect));+ assert_eq!(key_kind("uak_x"), None);+ assert_eq!(key_kind("x"), None);+ }++ #[test]+ fn the_bundled_popular_apps_are_composios_top_120() {+ let apps = popular_apps();+ assert_eq!(apps.len(), 120);+ assert_eq!((apps[0].slug.as_str(), apps[0].name.as_str()), ("gmail", "Gmail"));+ assert!(apps.windows(2).all(|w| w[0].rank < w[1].rank), "most popular first");+ assert!(apps.iter().all(|a| valid_slug(&a.slug) && a.logo.as_deref().is_some_and(|l| l.starts_with("https://"))));+ let slugs: BTreeSet<_> = apps.iter().map(|a| &a.slug).collect();+ assert_eq!(slugs.len(), 120, "no duplicates");+ }++ #[test]+ fn popular_search_puts_names_that_start_with_the_query_first() {+ let slugs = |q: &str, n| search_popular(q, n).into_iter().map(|a| a.slug.as_str()).collect::<Vec<_>>();+ assert_eq!(slugs("gma", 20), ["gmail", "figma"], "starts with, then contains");+ let google = slugs("google", 20);+ assert_eq!(google[0], "googlecalendar", "popularity order among prefix matches: {google:?}");+ assert!(google.len() > 3 && google.iter().all(|s| s.starts_with("google")), "{google:?}");+ assert_eq!(slugs("CAL", 3).first(), Some(&"googlecalendar"), "a later word counts, any case");+ assert_eq!(slugs("google", 2).len(), 2);+ assert!(slugs("zzzz-not-an-app", 20).is_empty());+ }++ #[test]+ fn manage_connections_answers_are_read_as_composio_sends_them() {+ // As Composio answered a `list` on 2026-11-12.+ let listed = r#"{"successful":true,"data":{"message":"…","results":{+ "gmail":{"toolkit":"gmail","status":"active","accounts":[{"id":"ca_1","status":"ACTIVE"}]},+ "slack":{"toolkit":"slack","status":"initiated","accounts":[]},+ "notion":{"toolkit":"notion","status":"initiated","accounts":[{"id":"ca_2","status":"active"}]}},+ "summary":{"total_toolkits":3}},"error":null,"log_id":"log_x"}"#;+ let r = manage_results(listed).unwrap();+ assert!(result_active(&r["gmail"]) && result_active(&r["notion"]) && !result_active(&r["slack"]));+ assert!(!result_active(&r["github"]), "an app not in the answer");+ assert!(manage_results(r#"{"results":{"gmail":{"status":"active"}}}"#).is_ok(), "results at the top");+ assert_eq!(+ manage_results(r#"{"successful":false,"error":"max accounts","data":{}}"#),+ Err(ComposioError::Upstream(200, "max accounts".into()))+ );+ assert!(manage_results("not json").is_err());+ assert!(manage_results(r#"{"successful":true,"data":{}}"#).is_err());+ }++ #[test]+ fn connect_failures_name_the_key_only_for_401_and_403() {+ let unauthorized = McpError::Unauthorized { www_authenticate: None };+ assert_eq!(connect_error(unauthorized), ComposioError::KeyRefused);+ let startup = |m: &str| McpError::Startup { message: m.into(), stderr_tail: String::new() };+ assert_eq!(connect_error(startup("transport error: HTTP 403 Forbidden")), ComposioError::KeyRefused);+ assert_eq!(connect_error(startup("transport error: HTTP 502 Bad Gateway")), ComposioError::Upstream(502, String::new()));+ assert_eq!(connect_error(startup("transport error: error sending request")), ComposioError::Unreachable);+ assert_eq!(connect_error(McpError::Timeout(15, "tools/call".into())), ComposioError::Unreachable);+ assert_eq!(connect_error(McpError::Rpc { code: -32000, message: "nope".into() }), ComposioError::Upstream(200, "nope".into()));+ assert_eq!(ComposioError::Upstream(502, String::new()).message(), "Composio couldn't be reached; try again in a minute.");+ }+#[test]fn only_an_active_enabled_account_of_this_user_and_app_counts() {let account = |status: &str, slug: &str, extra: Value| {diff --git a/src/mcp/composio_popular.json b/src/mcp/composio_popular.jsonnew file mode 100644index 00000000..2d39d147--- /dev/null+++ b/src/mcp/composio_popular.json@@ -0,0 +1,122 @@+[+{"slug":"gmail","name":"Gmail","rank":0,"logo":"https://logos.composio.dev/api/gmail"},+{"slug":"googlecalendar","name":"Google Calendar","rank":1,"logo":"https://logos.composio.dev/api/googlecalendar"},+{"slug":"googledrive","name":"Google Drive","rank":2,"logo":"https://logos.composio.dev/api/googledrive"},+{"slug":"outlook","name":"Outlook","rank":3,"logo":"https://logos.composio.dev/api/outlook"},+{"slug":"twitter","name":"Twitter","rank":4,"logo":"https://logos.composio.dev/api/twitter"},+{"slug":"googlesheets","name":"Google Sheets","rank":5,"logo":"https://logos.composio.dev/api/googlesheets"},+{"slug":"supabase","name":"Supabase","rank":6,"logo":"https://logos.composio.dev/api/supabase"},+{"slug":"composio","name":"Composio","rank":7,"logo":"https://logos.composio.dev/api/composio"},+{"slug":"notion","name":"Notion","rank":8,"logo":"https://logos.composio.dev/api/notion"},+{"slug":"slack","name":"Slack","rank":9,"logo":"https://logos.composio.dev/api/slack"},+{"slug":"airtable","name":"Airtable","rank":10,"logo":"https://logos.composio.dev/api/airtable"},+{"slug":"googledocs","name":"Google Docs","rank":11,"logo":"https://logos.composio.dev/api/googledocs"},+{"slug":"googlesuper","name":"Google Super","rank":12,"logo":"https://logos.composio.dev/api/googlesuper"},+{"slug":"hubspot","name":"HubSpot","rank":13,"logo":"https://logos.composio.dev/api/hubspot"},+{"slug":"codeinterpreter","name":"Codeinterpreter","rank":14,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/code-interpreter.webp"},+{"slug":"gong","name":"Gong","rank":15,"logo":"https://logos.composio.dev/api/gong"},+{"slug":"asana","name":"Asana","rank":16,"logo":"https://logos.composio.dev/api/asana"},+{"slug":"ashby","name":"Ashby","rank":17,"logo":"https://logos.composio.dev/api/ashby"},+{"slug":"pipedrive","name":"Pipedrive","rank":18,"logo":"https://logos.composio.dev/api/pipedrive"},+{"slug":"googletasks","name":"Google Tasks","rank":19,"logo":"https://logos.composio.dev/api/googletasks"},+{"slug":"linear","name":"Linear","rank":20,"logo":"https://logos.composio.dev/api/linear"},+{"slug":"github","name":"GitHub","rank":21,"logo":"https://logos.composio.dev/api/github"},+{"slug":"microsoft_teams","name":"Microsoft teams","rank":22,"logo":"https://logos.composio.dev/api/microsoft_teams"},+{"slug":"firecrawl","name":"Firecrawl","rank":23,"logo":"https://logos.composio.dev/api/firecrawl"},+{"slug":"canvas","name":"Canvas","rank":24,"logo":"https://logos.composio.dev/api/canvas"},+{"slug":"composio_search","name":"Composio search","rank":25,"logo":"https://logos.composio.dev/api/composio_search"},+{"slug":"salesforce","name":"Salesforce","rank":26,"logo":"https://logos.composio.dev/api/salesforce"},+{"slug":"tavily","name":"Tavily","rank":27,"logo":"https://logos.composio.dev/api/tavily"},+{"slug":"jira","name":"Jira","rank":28,"logo":"https://logos.composio.dev/api/jira"},+{"slug":"exa","name":"Exa","rank":29,"logo":"https://logos.composio.dev/api/exa"},+{"slug":"instagram","name":"Instagram","rank":30,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/instagram.svg"},+{"slug":"serpapi","name":"Serpapi","rank":31,"logo":"https://logos.composio.dev/api/serpapi"},+{"slug":"youtube","name":"Youtube","rank":32,"logo":"https://logos.composio.dev/api/youtube"},+{"slug":"clickup","name":"Clickup","rank":33,"logo":"https://logos.composio.dev/api/clickup"},+{"slug":"slackbot","name":"Slackbot","rank":34,"logo":"https://logos.composio.dev/api/slackbot"},+{"slug":"excel","name":"Excel","rank":35,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/Excel.png"},+{"slug":"monday","name":"Monday","rank":36,"logo":"https://logos.composio.dev/api/monday"},+{"slug":"reddit","name":"Reddit","rank":37,"logo":"https://logos.composio.dev/api/reddit"},+{"slug":"perplexityai","name":"Perplexityai","rank":38,"logo":"https://logos.composio.dev/api/perplexityai"},+{"slug":"apollo","name":"Apollo","rank":39,"logo":"https://logos.composio.dev/api/apollo"},+{"slug":"figma","name":"Figma","rank":40,"logo":"https://logos.composio.dev/api/figma"},+{"slug":"peopledatalabs","name":"Peopledatalabs","rank":41,"logo":"https://logos.composio.dev/api/peopledatalabs"},+{"slug":"attio","name":"Attio","rank":42,"logo":"https://logos.composio.dev/api/attio"},+{"slug":"stripe","name":"Stripe","rank":43,"logo":"https://logos.composio.dev/api/stripe"},+{"slug":"snowflake","name":"Snowflake","rank":44,"logo":"https://logos.composio.dev/api/snowflake"},+{"slug":"facebook","name":"Facebook","rank":45,"logo":"https://logos.composio.dev/api/facebook"},+{"slug":"browser_tool","name":"Browser tool","rank":46,"logo":"https://logos.composio.dev/api/composio"},+{"slug":"posthog","name":"Posthog","rank":47,"logo":"https://logos.composio.dev/api/posthog"},+{"slug":"metaads","name":"Metaads","rank":48,"logo":"https://logos.composio.dev/api/metaads"},+{"slug":"linkedin","name":"Linkedin","rank":49,"logo":"https://logos.composio.dev/api/linkedin"},+{"slug":"_21risk","name":"21risk","rank":50,"logo":"https://logos.composio.dev/api/_21risk"},+{"slug":"_2chat","name":"2chat","rank":51,"logo":"https://logos.composio.dev/api/_2chat"},+{"slug":"0codekit","name":"0CodeKit","rank":52,"logo":"https://logos.composio.dev/api/0codekit"},+{"slug":"_1password","name":"1password","rank":53,"logo":"https://logos.composio.dev/api/1password"},+{"slug":"44api","name":"44API","rank":54,"logo":"https://logos.composio.dev/api/44api"},+{"slug":"7shifts","name":"7shifts","rank":55,"logo":"https://logos.composio.dev/api/7shifts"},+{"slug":"ably","name":"Ably","rank":56,"logo":"https://logos.composio.dev/api/ably"},+{"slug":"abstract","name":"Abstract","rank":57,"logo":"https://logos.composio.dev/api/abstract"},+{"slug":"abuselpdb","name":"Abuselpdb","rank":58,"logo":"https://logos.composio.dev/api/abuseipdb"},+{"slug":"abyssale","name":"Abyssale","rank":59,"logo":"https://logos.composio.dev/api/abyssale"},+{"slug":"accredible_certificates","name":"Accredible certificates","rank":60,"logo":"https://logos.composio.dev/api/accredible_certificates"},+{"slug":"acculynx","name":"Acculynx","rank":61,"logo":"https://logos.composio.dev/api/acculynx"},+{"slug":"accu_weather","name":"AccuWeather","rank":62,"logo":"https://logos.composio.dev/api/accuweather"},+{"slug":"active_campaign","name":"Active campaign","rank":63,"logo":"https://logos.composio.dev/api/active_campaign"},+{"slug":"active_merge","name":"ActiveMerge","rank":64,"logo":"https://logos.composio.dev/api/active_merge"},+{"slug":"active_trail","name":"ActiveTrail","rank":65,"logo":"https://logos.composio.dev/api/active_trail"},+{"slug":"adafruit_io","name":"Adafruit IO","rank":66,"logo":"https://logos.composio.dev/api/adafruit_io"},+{"slug":"addressfinder","name":"Addressfinder","rank":67,"logo":"https://logos.composio.dev/api/addressfinder"},+{"slug":"addresszen","name":"Addresszen","rank":68,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/addresszen-logo.png"},+{"slug":"adobe_marketing_agent_mcp","name":"Adobe Marketing Agent MCP","rank":69,"logo":"https://logos.composio.dev/api/adobe_marketing_agent_mcp"},+{"slug":"adrapid","name":"Adrapid","rank":70,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/adrapid-logo.png"},+{"slug":"adroll","name":"AdRoll","rank":71,"logo":"https://logos.composio.dev/api/adroll"},+{"slug":"adtraction","name":"Adtraction","rank":72,"logo":"https://logos.composio.dev/api/adtraction"},+{"slug":"adyntel","name":"Adyntel","rank":73,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/icons/adyntel_round5_20250722.png"},+{"slug":"aeroleads","name":"Aeroleads","rank":74,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/aeroleads-logo.png"},+{"slug":"affinda","name":"Affinda","rank":75,"logo":"https://logos.composio.dev/api/affinda"},+{"slug":"affinity","name":"Affinity","rank":76,"logo":"https://logos.composio.dev/api/affinity"},+{"slug":"agencyzoom","name":"Agencyzoom","rank":77,"logo":"https://logos.composio.dev/api/agencyzoom"},+{"slug":"agent_mail","name":"Agent mail","rank":78,"logo":"https://logos.composio.dev/api/agent_mail"},+{"slug":"agentql","name":"Agentql","rank":79,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/agentql-logo.png"},+{"slug":"agenty","name":"Agenty","rank":80,"logo":"https://logos.composio.dev/api/agenty"},+{"slug":"agile_crm","name":"Agile CRM","rank":81,"logo":"https://logos.composio.dev/api/agilecrm"},+{"slug":"agiled","name":"Agiled","rank":82,"logo":"https://logos.composio.dev/api/agiled"},+{"slug":"agility_cms","name":"Agility cms","rank":83,"logo":"https://logos.composio.dev/api/agility_cms"},+{"slug":"aha","name":"Aha!","rank":84,"logo":"https://logos.composio.dev/api/aha"},+{"slug":"ahrefs","name":"Ahrefs","rank":85,"logo":"https://logos.composio.dev/api/ahrefs"},+{"slug":"ahrefs_mcp","name":"Ahrefs MCP","rank":86,"logo":"https://logos.composio.dev/api/ahrefs_mcp"},+{"slug":"ai_ark","name":"AI Ark","rank":87,"logo":"https://logos.composio.dev/api/ai_ark"},+{"slug":"ai_ml_api","name":"Ai ml api","rank":88,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/icons/ai_ml_api_fixed_20250722.png"},+{"slug":"aimtell","name":"AimTell","rank":89,"logo":"https://logos.composio.dev/api/aimtell"},+{"slug":"aircall","name":"Aircall","rank":90,"logo":"https://logos.composio.dev/api/aircall"},+{"slug":"airops_mcp","name":"AirOps MCP","rank":91,"logo":"https://logos.composio.dev/api/airops_mcp"},+{"slug":"airparser","name":"Airparser","rank":92,"logo":"https://logos.composio.dev/api/airparser"},+{"slug":"airtop","name":"Airtop","rank":93,"logo":"https://logos.composio.dev/api/airtop"},+{"slug":"airwallex","name":"Airwallex","rank":94,"logo":"https://logos.composio.dev/api/airwallex"},+{"slug":"aivoov","name":"Aivoov","rank":95,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/icons/aivoov_round2_20250722.png"},+{"slug":"aiwyn_tax_mcp","name":"Aiwyn Tax MCP","rank":96,"logo":"https://logos.composio.dev/api/aiwyn_tax_mcp"},+{"slug":"akta","name":"Akta","rank":97,"logo":"https://logos.composio.dev/api/akta"},+{"slug":"alchemy","name":"Alchemy","rank":98,"logo":"https://logos.composio.dev/api/alchemy"},+{"slug":"algodocs","name":"Algodocs","rank":99,"logo":"https://logos.composio.dev/api/algodocs"},+{"slug":"algolia","name":"Algolia","rank":100,"logo":"https://logos.composio.dev/api/algolia"},+{"slug":"all_images_ai","name":"All images ai","rank":101,"logo":"https://logos.composio.dev/api/all_images_ai"},+{"slug":"alltrails_mcp","name":"AllTrails MCP","rank":102,"logo":"https://logos.composio.dev/api/alltrails_mcp"},+{"slug":"alpaca","name":"Alpaca","rank":103,"logo":"https://logos.composio.dev/api/alpaca"},+{"slug":"alpha_vantage","name":"Alpha vantage","rank":104,"logo":"https://logos.composio.dev/api/alpha_vantage"},+{"slug":"altoviz","name":"Altoviz","rank":105,"logo":"https://logos.composio.dev/api/altoviz"},+{"slug":"alttext_ai","name":"Alttext ai","rank":106,"logo":"https://logos.composio.dev/api/alttext_ai"},+{"slug":"alt_text_lab","name":"AltTextLab","rank":107,"logo":"https://logos.composio.dev/api/alttextlab"},+{"slug":"amara","name":"Amara","rank":108,"logo":"https://logos.composio.dev/api/amara"},+{"slug":"amazing_marvin","name":"Amazing Marvin","rank":109,"logo":"https://logos.composio.dev/api/amazingmarvin"},+{"slug":"amazon","name":"Amazon","rank":110,"logo":"https://logos.composio.dev/api/amazon"},+{"slug":"ambee","name":"Ambee","rank":111,"logo":"https://logos.composio.dev/api/ambee"},+{"slug":"ambient_weather","name":"Ambient weather","rank":112,"logo":"https://cdn.jsdelivr.net/gh/ComposioHQ/open-logos@master/icons/ambient_weather_round3_20250722.png"},+{"slug":"ambiguous_mcp","name":"Ambiguous MCP","rank":113,"logo":"https://www.ambiguous.ai/favicon.ico"},+{"slug":"amcards","name":"Amcards","rank":114,"logo":"https://logos.composio.dev/api/amcards"},+{"slug":"amplitude","name":"Amplitude","rank":115,"logo":"https://logos.composio.dev/api/amplitude"},+{"slug":"amplitude_mcp","name":"Amplitude MCP","rank":116,"logo":"https://logos.composio.dev/api/amplitude_mcp"},+{"slug":"anakin_io","name":"Anakin","rank":117,"logo":"https://logos.composio.dev/api/anakin"},+{"slug":"anaplan","name":"Anaplan","rank":118,"logo":"https://logos.composio.dev/api/anaplan"},+{"slug":"anchor_browser","name":"Anchor browser","rank":119,"logo":"https://logos.composio.dev/api/anchor_browser"}+]diff --git a/src/server/connection_suggest.rs b/src/server/connection_suggest.rsindex a73621e2..ad37b7df 100644--- a/src/server/connection_suggest.rs+++ b/src/server/connection_suggest.rs@@ -30,7 +30,8 @@ pub fn tools() -> Vec<Value> {(google_search_console, google_analytics, googleads, hubspot). This connects nothing: the user signs in \themselves, so post it rather than offering to or asking whether to. Use it instead of reporting that something is \impossible for lack of access, then carry on \- with everything you can do without it. At most 3 per turn.",+ with everything you can do without it. When a Composio tool (such as COMPOSIO_MANAGE_CONNECTIONS) gives you \+ a sign-in link, don't paste the link: call this instead, so the user connects from the card. At most 3 per turn.","inputSchema": {"type": "object","properties": {@@ -66,9 +67,9 @@ impl ComposioReady {fn first_step(self) -> Option<&'static str> {match self {Self::Ready => None,- Self::Off => Some("switch the Composio connector on in Connections"),- Self::NeedsKey => Some("add your Composio API key to the Composio connector in Connections"),- Self::NotAdded => Some("add Composio in Connections (free account at composio.dev)"),+ Self::Off => Some("switch Composio on in Apps & accounts"),+ Self::NeedsKey => Some("paste your Composio API key on the Composio tile in Apps & accounts (Replace key)"),+ Self::NotAdded => Some("add Composio with your free key in Apps & accounts (press Add Composio and paste the API key)"),}}}@@ -94,8 +95,8 @@ fn one_line(text: &str) -> String {/// The card's text, readable without a card: what, why, and the steps.pub fn card_text(name: &str, reason: &str, ready: ComposioReady) -> String {let steps = match ready.first_step() {- Some(first) => format!("To connect it, {first}, then open Connections → Composio apps, find {name} and press Connect."),- None => format!("To connect it, open Connections → Composio apps, find {name} and press Connect."),+ Some(first) => format!("To connect it, {first}, then find {name} under Composio in Apps & accounts and press Connect."),+ None => format!("To connect it, find {name} under Composio in Apps & accounts and press Connect."),};format!("Suggested connection: {name}. {reason} {steps} You sign in on the app's own page; nothing is connected until you do.")}@@ -139,7 +140,7 @@ pub async fn tool_call(state: &AppState, scope: &SelfScope, args: &Value) -> (St}let Some(origin) = scope.origin.as_ref() else {return (- "There is no chat to show a card in. Say in your reply which connection you need and that the user adds it in Connections.".into(),+ "There is no chat to show a card in. Say in your reply which connection you need and that the user adds it in Apps & accounts.".into(),true,);};@@ -205,12 +206,15 @@ mod tests {fn the_card_text_names_the_app_the_reason_and_the_steps() {let t = card_text("Google Search Console", "It shows which pages Google indexed.", ComposioReady::Ready);assert!(t.starts_with("Suggested connection: Google Search Console. It shows which pages Google indexed."));- assert!(t.contains("Connections → Composio apps, find Google Search Console and press Connect"));+ assert!(t.contains("find Google Search Console under Composio in Apps & accounts and press Connect"), "{t}");assert!(!t.contains("API key"));let t = card_text("Google Search Console", "x", ComposioReady::NotAdded);- assert!(t.contains("add Composio in Connections"), "{t}");+ assert!(t.contains("add Composio with your free key in Apps & accounts"), "{t}");+ assert!(!t.contains("Connections"), "the old page name is gone: {t}");assert!(card_text("A", "x", ComposioReady::NeedsKey).contains("Composio API key"));- assert!(card_text("A", "x", ComposioReady::Off).contains("switch the Composio connector on"));+ assert!(card_text("A", "x", ComposioReady::Off).contains("switch Composio on in Apps & accounts"));+ let d = tools()[0]["description"].as_str().unwrap().to_string();+ assert!(d.contains("don't paste the link: call this instead"), "{d}");}#[test]diff --git a/src/server/connections.rs b/src/server/connections.rsindex c7368c72..cd09ff21 100644--- a/src/server/connections.rs+++ b/src/server/connections.rs@@ -25,7 +25,7 @@ use chrono::{DateTime, Utc};use serde::{Deserialize, Serialize};use serde_json::{json, Value};use std::collections::{BTreeMap, HashMap};-use std::sync::{Mutex, OnceLock};+use std::sync::{Arc, Mutex, OnceLock};const REFUSAL: &str = "only the person manages connections";@@ -364,24 +364,306 @@ async fn source_connections(state: &AppState, space: &SpaceId) -> Vec<Connection.collect()}-/// The Composio API key saved with the connector (its `x-api-key` header), if any.+fn is_key_header(name: &str) -> bool {+ name.eq_ignore_ascii_case(composio::PROJECT_KEY_HEADER) || name.eq_ignore_ascii_case(composio::CONNECT_KEY_HEADER)+}++/// Whether the connector is a Composio Connect setup: its key is a `ck_` key, sent as+/// `x-consumer-api-key`.+fn is_connect(server: &McpServer) -> bool {+ server.headers.keys().any(|k| k.eq_ignore_ascii_case(composio::CONNECT_KEY_HEADER))+}++/// The Composio key saved with the connector (its `x-api-key` header, or `x-consumer-api-key`+/// for a Composio Connect key), if any.pub(super) fn composio_key(server: &McpServer) -> Option<&str> {server.headers.iter()- .find(|(k, _)| k.eq_ignore_ascii_case("x-api-key"))+ .find(|(k, _)| is_key_header(k)).map(|(_, v)| v.trim()).filter(|v| !v.is_empty())}+/// The session kwant made for a space's Composio (the one-key setup), kept in `settings` under+/// `composio_session:<space>`. It describes the space's server only while that server's URL is+/// still `mcp_url`: a server re-added or edited by hand is a URL setup again.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+struct StoredSession {+ session_id: String,+ user_id: String,+ mcp_url: String,+}++fn session_setting(space: &SpaceId) -> String {+ format!("composio_session:{}", space.as_str())+}++async fn stored_session(state: &AppState, space: &SpaceId, server: &McpServer) -> Option<StoredSession> {+ let raw = state.db.get_setting(&session_setting(space)).await.ok().flatten()?;+ let s: StoredSession = serde_json::from_str(&raw).ok()?;+ (server.url.as_deref() == Some(s.mcp_url.as_str())).then_some(s)+}++async fn save_session(state: &AppState, space: &SpaceId, s: &composio::Session) -> Result<(), crate::db::DbError> {+ let stored = StoredSession { session_id: s.session_id.clone(), user_id: s.user_id.clone(), mcp_url: s.mcp_url.clone() };+ state.db.set_setting(&session_setting(space), &serde_json::to_string(&stored).unwrap_or_default()).await+}++/// How a space's Composio is set up: `session` (one `ak_` key; kwant made the session),+/// `connect` (one `ck_` key on Composio Connect, whose apps belong to the key's own Composio+/// account) or `url` (an MCP URL pasted from composio.dev).+#[derive(Debug, Clone)]+struct ComposioSetup {+ server: McpServer,+ key: Option<String>,+ session: Option<StoredSession>,+ connect: bool,+}++impl ComposioSetup {+ fn mode(&self) -> &'static str {+ if self.connect {+ "connect"+ } else if self.session.is_some() {+ "session"+ } else {+ "url"+ }+ }++ /// The Composio user apps are connected for: the session's, else the URL's `user_id`.+ /// Composio Connect has none: the key is the person's own account.+ fn user_id(&self) -> Option<String> {+ if self.connect {+ return None;+ }+ match &self.session {+ Some(s) => Some(s.user_id.clone()),+ None => self.server.url.as_deref().and_then(composio::user_id_of),+ }+ }++ /// Apps can be connected from kwant: a key, and someone to connect them for.+ fn can_connect(&self) -> bool {+ self.key.is_some() && (self.connect || self.user_id().is_some())+ }+}++async fn composio_setup(state: &AppState, space: &SpaceId) -> Option<ComposioSetup> {+ let servers = state.db.list_mcp_servers(space).await.unwrap_or_default();+ let server = servers.into_iter().find(is_composio)?;+ let connect = is_connect(&server);+ let session = if connect { None } else { stored_session(state, space, &server).await };+ let key = composio_key(&server).map(str::to_string);+ Some(ComposioSetup { server, key, session, connect })+}++// Apps connected on Composio, per space, kept a minute so the Connections list costs at most+// one Composio call a minute. Keyed by space and Composio client (one per server; tests make+// their own), and fingerprinted by key and user, so a new key or user starts over.++fn cache_key(state: &AppState, space: &SpaceId) -> String {+ format!("{:p}:{}", Arc::as_ptr(&state.composio_api), space.as_str())+}++const APPS_TTL: std::time::Duration = std::time::Duration::from_secs(60);++#[derive(Debug, Clone)]+struct AppsSeen {+ at: std::time::Instant,+ fingerprint: u64,+ apps: std::collections::BTreeSet<String>,+ /// The last call's failure, with the one action that fixes it.+ problem: Option<(String, &'static str)>,+}++fn apps_seen() -> &'static Mutex<HashMap<String, AppsSeen>> {+ static SEEN: OnceLock<Mutex<HashMap<String, AppsSeen>>> = OnceLock::new();+ SEEN.get_or_init(Default::default)+}++/// App names learned from catalogue searches (Composio's account list only has slugs).+fn app_names() -> &'static Mutex<HashMap<String, String>> {+ static NAMES: OnceLock<Mutex<HashMap<String, String>>> = OnceLock::new();+ NAMES.get_or_init(Default::default)+}++fn learn_names(apps: &[composio::ComposioApp]) {+ let mut names = app_names().lock().unwrap_or_else(|e| e.into_inner());+ if names.len() > 5000 {+ names.clear();+ }+ for a in apps {+ names.insert(a.slug.clone(), a.name.clone());+ }+}++/// An app's name: the catalogue's when kwant has seen it, else the popular list's, else its+/// slug in words (`google_drive` → `Google Drive`).+fn app_name(slug: &str) -> String {+ if let Some(n) = app_names().lock().unwrap_or_else(|e| e.into_inner()).get(slug) {+ return n.clone();+ }+ if let Some(a) = composio::popular_apps().iter().find(|a| a.slug == slug) {+ return a.name.clone();+ }+ slug.split(['_', '-'])+ .filter(|w| !w.is_empty())+ .map(|w| {+ let mut c = w.chars();+ c.next().map(|f| f.to_uppercase().chain(c).collect::<String>()).unwrap_or_default()+ })+ .collect::<Vec<_>>()+ .join(" ")+}++fn fingerprint(key: &str, user: &str) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ (key, user).hash(&mut h);+ h.finish()+}++fn remember_apps(space: &str, fp: u64, result: &Result<std::collections::BTreeSet<String>, composio::ComposioError>) {+ let mut seen = apps_seen().lock().unwrap_or_else(|e| e.into_inner());+ let entry = match result {+ Ok(apps) => AppsSeen { at: std::time::Instant::now(), fingerprint: fp, apps: apps.clone(), problem: None },+ Err(e) => {+ let apps = seen.get(space).filter(|s| s.fingerprint == fp).map(|s| s.apps.clone()).unwrap_or_default();+ AppsSeen { at: std::time::Instant::now(), fingerprint: fp, apps, problem: Some((e.message(), e.action())) }+ }+ };+ seen.insert(space.to_string(), entry);+}++/// Apps a status check found connected, per space and key fingerprint: with Composio Connect,+/// what the tile lists when the full check is too slow.+type ThroughKwant = HashMap<String, (u64, std::collections::BTreeSet<String>)>;++fn through_kwant() -> &'static Mutex<ThroughKwant> {+ static SEEN: OnceLock<Mutex<ThroughKwant>> = OnceLock::new();+ SEEN.get_or_init(Default::default)+}++fn apps_through_kwant(space: &str, fp: u64) -> std::collections::BTreeSet<String> {+ through_kwant().lock().unwrap_or_else(|e| e.into_inner()).get(space).filter(|(f, _)| *f == fp).map(|(_, a)| a.clone()).unwrap_or_default()+}++/// One app's status, learned from a status check: updates the cache without a call.+fn note_app(space: &str, fp: u64, slug: &str, connected: bool) {+ {+ let mut kept = through_kwant().lock().unwrap_or_else(|e| e.into_inner());+ if kept.len() > 1000 {+ kept.clear();+ }+ let entry = kept.entry(space.to_string()).or_default();+ if entry.0 != fp {+ *entry = (fp, Default::default());+ }+ if connected {+ entry.1.insert(slug.to_string());+ } else {+ entry.1.remove(slug);+ }+ }+ let mut seen = apps_seen().lock().unwrap_or_else(|e| e.into_inner());+ if let Some(s) = seen.get_mut(space).filter(|s| s.fingerprint == fp) {+ if connected {+ s.apps.insert(slug.to_string());+ } else {+ s.apps.remove(slug);+ }+ }+}++fn forget_apps(state: &AppState, space: &SpaceId) {+ apps_seen().lock().unwrap_or_else(|e| e.into_inner()).remove(&cache_key(state, space));+}++/// With Composio Connect, a check of all the popular apps that took longer than this is too slow+/// to repeat every minute: the tile then lists the apps connected through kwant for a while.+const CONNECT_SLOW: std::time::Duration = std::time::Duration::from_secs(3);+const CONNECT_SLOW_PAUSE: std::time::Duration = std::time::Duration::from_secs(10 * 60);++/// Spaces whose last full Composio Connect check was slow, until when.+fn connect_slow() -> &'static Mutex<HashMap<String, std::time::Instant>> {+ static SLOW: OnceLock<Mutex<HashMap<String, std::time::Instant>>> = OnceLock::new();+ SLOW.get_or_init(Default::default)+}++/// The apps connected with Composio Connect: one `list` call over the popular apps, timed. Under+/// [`CONNECT_SLOW`] it is the answer (with the apps connected through kwant); slower, the next+/// ten minutes list only the apps connected through kwant, with no call.+async fn connect_apps(api: &composio::ComposioApi, ck: &str, fp: u64, key: &str) -> Result<std::collections::BTreeSet<String>, composio::ComposioError> {+ let mine = apps_through_kwant(ck, fp);+ let paused = connect_slow().lock().unwrap_or_else(|e| e.into_inner()).get(ck).is_some_and(|until| std::time::Instant::now() < *until);+ if paused {+ return Ok(mine);+ }+ let slugs: Vec<&str> = composio::popular_apps().iter().map(|a| a.slug.as_str()).collect();+ let started = std::time::Instant::now();+ let result = api.connect_active(key, &slugs).await;+ let took = started.elapsed();+ tracing::info!(apps = slugs.len(), ms = took.as_millis() as u64, ok = result.is_ok(), "connections: Composio Connect status of the popular apps");+ if result.is_ok() && took > CONNECT_SLOW {+ connect_slow().lock().unwrap_or_else(|e| e.into_inner()).insert(ck.to_string(), std::time::Instant::now() + CONNECT_SLOW_PAUSE);+ }+ result.map(|mut apps| {+ apps.extend(mine);+ apps+ })+}++/// The apps connected for the setup's user: cached for a minute, else one Composio call that+/// may take up to 2 seconds here (it goes on in the background and fills the cache after).+async fn connected_apps_cached(state: &AppState, space: &SpaceId, setup: &ComposioSetup) -> Option<AppsSeen> {+ let key = setup.key.clone()?;+ let user = if setup.connect { String::new() } else { setup.user_id()? };+ let fp = fingerprint(&key, &user);+ let ck = cache_key(state, space);+ if let Some(s) = apps_seen().lock().unwrap_or_else(|e| e.into_inner()).get(&ck) {+ if s.fingerprint == fp && s.at.elapsed() < APPS_TTL {+ return Some(s.clone());+ }+ }+ let api = state.composio_api.clone();+ let ck_job = ck.clone();+ let connect = setup.connect;+ let job = tokio::spawn(async move {+ let result = if connect { connect_apps(&api, &ck_job, fp, &key).await } else { api.connected_apps(&key, &user).await };+ remember_apps(&ck_job, fp, &result);+ });+ let _ = tokio::time::timeout(std::time::Duration::from_secs(2), job).await;+ apps_seen().lock().unwrap_or_else(|e| e.into_inner()).get(&ck).filter(|s| s.fingerprint == fp).cloned()+}+/// The optional connectors kwnt offers, with whether each is added.-fn catalog(servers: &[McpServer]) -> Value {- let added = servers.iter().find(|s| is_composio(s));+async fn catalog(state: &AppState, space: &SpaceId) -> Value {+ let setup = composio_setup(state, space).await;+ let seen = match &setup {+ Some(s) => connected_apps_cached(state, space, s).await,+ None => None,+ };+ let added = setup.as_ref().map(|s| &s.server);+ let has_key = setup.as_ref().is_some_and(|s| s.key.is_some());+ let can_connect = setup.as_ref().is_some_and(|s| s.can_connect());+ // Old setups get one way into the new one; a missing key or a refused one gets Replace key.+ let problem = match (&setup, &seen) {+ (None, _) => None,+ (Some(s), _) if s.key.is_none() => Some(json!({"message": "Add your Composio API key to finish setting up Composio.", "action": "replace_key"})),+ (Some(_), Some(AppsSeen { problem: Some((m, a)), .. })) => Some(json!({"message": m, "action": a})),+ (Some(s), _) if s.mode() == "url" && s.user_id().is_none() => Some(json!({+ "message": "This Composio setup doesn't say which Composio user your apps belong to. Switch to the one-key setup and kwant picks one.",+ "action": "switch",+ })),+ _ => None,+ };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.",+ "description": "Gmail, Slack, Notion, Linear and hundreds more apps, with your free Composio key. Your bots find the tools they need themselves.","optional": true,"added": added.is_some(),"connection_id": added.map(|s| format!("mcp:{}", s.id)),@@ -389,10 +671,19 @@ fn catalog(servers: &[McpServer]) -> Value {"logins_stored": "composio","warning": COMPOSIO_WARNING,"add": "/api/connections/composio",- // Finding apps needs the connector's API key; connecting one also needs the URL's user_id.- "can_search": added.is_some_and(|s| composio_key(s).is_some()),- "can_connect": added.is_some_and(|s| composio_key(s).is_some() && s.url.as_deref().and_then(composio::user_id_of).is_some()),+ "key_url": composio::KEY_PAGE,+ // `session`: one `ak_` key, kwant made the session; `connect`: one `ck_` key on Composio+ // Connect; `url`: an MCP URL pasted from composio.dev+ "mode": setup.as_ref().map(|s| s.mode()),+ "user_id": setup.as_ref().and_then(|s| s.user_id()),+ "apps_connected": seen.as_ref().map(|s| s.apps.iter().map(|slug| json!({"slug": slug, "name": app_name(slug)})).collect::<Vec<_>>()).unwrap_or_default(),+ "problem": problem,+ "can_search": has_key,+ "can_connect": can_connect,+ "can_switch": setup.as_ref().is_some_and(|s| s.mode() == "url"),"search": "/api/connections/composio/apps",+ "switch": "/api/connections/composio/switch",+ "replace_key": "/api/connections/composio/key",}])}@@ -427,7 +718,6 @@ pub async fn list(State(state): State<AppState>, headers: HeaderMap, Scope(spacec.notes = Some(NoteCounts { open, broke });}}- 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;@@ -436,7 +726,7 @@ pub async fn list(State(state): State<AppState>, headers: HeaderMap, Scope(space"connections": connections,"counts": counts,"vault": vault,- "catalog": catalog(&servers),+ "catalog": catalog(&state, &space).await,// Composio apps marked production by toolkit slug (D10), as `composio:<slug>`"production": marked.iter().filter(|m| m.starts_with("composio:")).collect::<Vec<_>>(),}))@@ -489,9 +779,11 @@ pub async fn put_production(#[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).+ /// The MCP URL Composio gives for the person's server, `https://….composio.dev/…`. Optional:+ /// without it kwant makes the server itself from the API key (the one-key setup).+ #[serde(default)]+ pub url: Option<String>,+ /// Composio project 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.@@ -503,7 +795,112 @@ 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).+/// An error with the one action that fixes it: `add_composio`, `replace_key`, `try_again`,+/// `switch` or `turn_on`. A key problem also carries where to copy a key.+fn error_with(status: StatusCode, message: &str, action: &str) -> Response {+ let mut body = json!({"error": message, "action": action});+ if action == "replace_key" || action == "add_composio" {+ body["key_url"] = json!(composio::KEY_PAGE);+ }+ (status, Json(body)).into_response()+}++fn trimmed_key(key: Option<&str>) -> Option<String> {+ key.map(str::trim).filter(|k| !k.is_empty()).map(str::to_string)+}++/// Composio refused `key`: 409 with what to copy, and a word when it is the wrong kind of key.+fn key_failed(e: composio::ComposioError, key: &str) -> Response {+ if e == composio::ComposioError::KeyRefused && key.starts_with("uak_") {+ return error_with(+ StatusCode::CONFLICT,+ "That's a Composio user key (it starts with uak_). kwant needs your Composio key: copy it from your \+ Composio dashboard. It starts with ck_ or ak_.",+ "replace_key",+ );+ }+ composio_failed(e)+}++/// What a key turned out to be. A project key (`ak_`) is checked by the caller's own first call;+/// a Composio Connect key has been checked already and comes with its tools.+enum Checked {+ Project,+ Connect(Vec<String>),+}++/// Which kind `key` is. `ck_` is checked on Composio Connect (MCP `initialize` and `tools/list`);+/// `ak_` is left to the caller; any other prefix is tried as a project key, then on Composio+/// Connect. A key both refuse gets 409 `replace_key`; Composio out of reach gets 502.+#[allow(clippy::result_large_err)]+async fn check_kind(state: &AppState, key: &str) -> Result<Checked, Response> {+ let api = &state.composio_api;+ match composio::key_kind(key) {+ Some(composio::KeyKind::Project) => Ok(Checked::Project),+ Some(composio::KeyKind::Connect) => api.check_connect_key(key).await.map(Checked::Connect).map_err(|e| key_failed(e, key)),+ None => match api.check_key(key).await {+ Ok(()) => Ok(Checked::Project),+ Err(refused) if refused.is_key() => match api.check_connect_key(key).await {+ Ok(tools) => Ok(Checked::Connect(tools)),+ Err(e) if e.is_key() => Err(key_failed(refused, key)),+ Err(e) => Err(composio_failed(e)),+ },+ Err(e) => Err(composio_failed(e)),+ },+ }+}++/// `next` with `key` as its only Composio key, in the header its kind goes in.+fn with_key(mut next: McpServer, header: &str, key: &str) -> McpServer {+ next.headers.retain(|k, _| !is_key_header(k));+ next.headers.insert(header.to_string(), key.to_string());+ next+}++/// Adds Composio Connect with a checked `ck_` key: server `composio` at Composio Connect, the key+/// in `x-consumer-api-key`, no Composio user (the key is the person's own account).+async fn add_connect(state: &AppState, space: &SpaceId, key: &str, tools: Vec<String>, enabled: bool) -> Response {+ let input = McpServerInput {+ name: COMPOSIO_NAME.into(),+ transport: "http".into(),+ command: None,+ args: None,+ url: Some(composio::CONNECT_MCP_URL.into()),+ env: None,+ headers: Some(BTreeMap::from([(composio::CONNECT_KEY_HEADER.to_string(), key.to_string())])),+ enabled: Some(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) => {+ forget_apps(state, space);+ tracing::info!(space = %space.as_str(), mode = "connect", "connections: Composio added");+ Json(json!({+ "connection_id": format!("mcp:{}", created.id),+ "server": mcp::McpServerView::from(&created),+ "mode": "connect",+ "user_id": Value::Null,+ "tools": tools,+ "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")+ }+ }+}++/// `POST /api/connections/composio?space=`: adds Composio (off for bots by default). A `ck_`+/// key alone is checked on Composio Connect and saved as `mode: "connect"`. With only+/// `api_key`, kwant checks the key by making a Tool Router session for the space's own Composio+/// user and saves the session's MCP server: `mode: "session"`. With `url` it saves that MCP URL as+/// before: `mode: "url"`. A refused key saves nothing.pub async fn add_composio(State(state): State<AppState>,headers: HeaderMap,@@ -513,26 +910,41 @@ pub async fn add_composio(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 url = body.url.as_deref().map(str::trim).filter(|u| !u.is_empty()).map(str::to_string);+ let key = trimmed_key(body.api_key.as_deref());+ if let Some(u) = &url {+ if !is_composio_url(u) {+ return error(StatusCode::BAD_REQUEST, "url must be an https address on composio.dev");+ }+ } else if key.is_none() {+ return error_with(StatusCode::BAD_REQUEST, "Paste your Composio API key.", "add_composio");}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();+ return error_with(StatusCode::CONFLICT, "Composio is already added. Replace its key on the Composio tile instead.", "replace_key");+ }+ if let (None, Some(k)) = (&url, &key) {+ match check_kind(&state, k).await {+ Ok(Checked::Connect(tools)) => return add_connect(&state, &space, k, tools, body.enabled).await,+ Ok(Checked::Project) => {}+ Err(r) => return r,+ }+ }+ let session = match (&url, &key) {+ (None, Some(k)) => match state.composio_api.create_session(k, &composio::space_user_id(space.as_str())).await {+ Ok(s) => Some(s),+ Err(e) => return key_failed(e, k),+ },+ _ => None,+ };+ let headers: BTreeMap<String, String> =+ key.clone().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()),+ url: Some(session.as_ref().map(|s| s.mcp_url.clone()).or(url).unwrap_or_default()),env: None,headers: Some(headers),enabled: Some(body.enabled),@@ -542,13 +954,26 @@ pub async fn add_composio(Ok(s) => s,Err(m) => return error(StatusCode::BAD_REQUEST, &m),};+ if let Some(s) = &session {+ if let Err(e) = save_session(&state, &space, s).await {+ tracing::warn!(error = %e, "connections: could not save the Composio session");+ return error(StatusCode::INTERNAL_SERVER_ERROR, "could not add Composio");+ }+ }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(),+ Ok(created) => {+ forget_apps(&state, &space);+ tracing::info!(space = %space.as_str(), mode = if session.is_some() { "session" } else { "url" }, "connections: Composio added");+ Json(json!({+ "connection_id": format!("mcp:{}", created.id),+ "server": mcp::McpServerView::from(&created),+ "mode": if session.is_some() { "session" } else { "url" },+ "user_id": session.as_ref().map(|s| s.user_id.clone()),+ "tools": session.as_ref().map(|s| s.tools.clone()).unwrap_or_default(),+ "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")@@ -556,36 +981,483 @@ pub async fn add_composio(}}-/// The space's Composio connector and its API key, or the reply that explains what's missing.-/// Nothing here calls Composio.+#[derive(Debug, Default, Deserialize)]+pub struct KeyBody {+ #[serde(default)]+ pub api_key: Option<String>,+}++/// Points the space's Composio server at `session` with `key`, keeping its id, its switch and+/// which bots have it, so nothing the person picked changes.#[allow(clippy::result_large_err)]-async fn composio_with_key(state: &AppState, space: &SpaceId) -> Result<(McpServer, String), Response> {- let servers = state.db.list_mcp_servers(space).await.unwrap_or_default();- let Some(server) = servers.into_iter().find(is_composio) else {- return Err(error(StatusCode::CONFLICT, "Add the Composio connector first; kwant never contacts Composio before that"));+async fn move_to_session(+ state: &AppState,+ space: &SpaceId,+ server: &McpServer,+ key: &str,+ session: &composio::Session,+) -> Result<McpServer, Response> {+ let mut next = with_key(server.clone(), composio::PROJECT_KEY_HEADER, key);+ next.url = Some(session.mcp_url.clone());+ let fail = |what: &str| {+ tracing::warn!(what, "connections: could not save the Composio session");+ error(StatusCode::INTERNAL_SERVER_ERROR, "could not save the new Composio setup")+ };+ save_session(state, space, session).await.map_err(|_| fail("setting"))?;+ let saved = state.db.update_mcp_server(&next).await.map_err(|_| fail("server"))?.ok_or_else(|| fail("server gone"))?;+ forget_apps(state, space);+ Ok(saved)+}++/// `POST /api/connections/composio/switch?space=` `{api_key?}`: turns a setup made from an MCP+/// URL into the one-key setup. It uses the saved key (or `api_key`) and the URL's `user_id`, so+/// apps already connected stay connected; without one, the space's own user. Idempotent: a+/// session setup answers `switched: false` and calls nobody.+pub async fn switch_composio(+ State(state): State<AppState>,+ headers: HeaderMap,+ Scope(space): Scope,+ body: Option<Json<KeyBody>>,+) -> Response {+ if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {+ return r;+ }+ let Some(setup) = composio_setup(&state, &space).await else {+ return error_with(StatusCode::CONFLICT, "Composio isn't added yet. Add it with your free Composio API key.", "add_composio");+ };+ if setup.session.is_some() || setup.connect {+ return Json(json!({+ "connection_id": format!("mcp:{}", setup.server.id),+ "server": mcp::McpServerView::from(&setup.server),+ "mode": setup.mode(),+ "user_id": setup.user_id(),+ "switched": false,+ }))+ .into_response();+ }+ let given = body.and_then(|Json(b)| trimmed_key(b.api_key.as_deref()));+ let Some(key) = given.or(setup.key.clone()) else {+ return error_with(StatusCode::CONFLICT, "Paste your Composio API key to switch.", "replace_key");+ };+ let user_id = setup.user_id().unwrap_or_else(|| composio::space_user_id(space.as_str()));+ let session = match state.composio_api.create_session(&key, &user_id).await {+ Ok(s) => s,+ Err(e) => return key_failed(e, &key),+ };+ match move_to_session(&state, &space, &setup.server, &key, &session).await {+ Ok(saved) => {+ tracing::info!(space = %space.as_str(), "connections: Composio switched to the one-key setup");+ Json(json!({+ "connection_id": format!("mcp:{}", saved.id),+ "server": mcp::McpServerView::from(&saved),+ "mode": "session",+ "user_id": session.user_id,+ "tools": session.tools,+ "switched": true,+ }))+ .into_response()+ }+ Err(r) => r,+ }+}++/// `PUT /api/connections/composio/key?space=` `{api_key}`: replaces the Composio key with either+/// kind. The new key is checked first, and a refused one changes nothing. A `ck_` key makes the+/// setup Composio Connect; an `ak_` key in place of a `ck_` one gets a session for the space's+/// own Composio user. In the one-key setup a key of the same Composio project keeps the session;+/// a key of another project gets a new session for the same user. Replies `{connection_id, mode,+/// user_id, session_renewed}`.+pub async fn replace_composio_key(+ State(state): State<AppState>,+ headers: HeaderMap,+ Scope(space): Scope,+ Json(body): Json<KeyBody>,+) -> Response {+ if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {+ return r;+ }+ let Some(key) = trimmed_key(body.api_key.as_deref()) else {+ return error_with(StatusCode::BAD_REQUEST, "Paste your Composio API key.", "replace_key");+ };+ let Some(setup) = composio_setup(&state, &space).await else {+ return error_with(StatusCode::CONFLICT, "Composio isn't added yet. Add it with your free Composio API key.", "add_composio");+ };+ let reply = |server: &McpServer, mode: &str, user_id: Option<String>, renewed: bool| {+ Json(json!({+ "connection_id": format!("mcp:{}", server.id),+ "server": mcp::McpServerView::from(server),+ "mode": mode,+ "user_id": user_id,+ "session_renewed": renewed,+ }))+ .into_response()+ };+ match check_kind(&state, &key).await {+ Err(r) => return r,+ Ok(Checked::Connect(_)) => {+ let mut next = with_key(setup.server.clone(), composio::CONNECT_KEY_HEADER, &key);+ next.url = Some(composio::CONNECT_MCP_URL.into());+ return match state.db.update_mcp_server(&next).await {+ Ok(Some(saved)) => {+ forget_apps(&state, &space);+ tracing::info!(space = %space.as_str(), from = setup.mode(), "connections: Composio key replaced with a Composio Connect key");+ reply(&saved, "connect", None, false)+ }+ _ => error(StatusCode::INTERNAL_SERVER_ERROR, "could not save the key"),+ };+ }+ Ok(Checked::Project) if setup.connect => {+ let session = match state.composio_api.create_session(&key, &composio::space_user_id(space.as_str())).await {+ Ok(s) => s,+ Err(e) => return key_failed(e, &key),+ };+ return match move_to_session(&state, &space, &setup.server, &key, &session).await {+ Ok(saved) => reply(&saved, "session", Some(session.user_id), true),+ Err(r) => r,+ };+ }+ Ok(Checked::Project) => {}+ }+ match &setup.session {+ Some(stored) => {+ let same_project = match state.composio_api.session_user(&key, &stored.session_id).await {+ Ok(user) => user.is_some(),+ Err(e) => return key_failed(e, &key),+ };+ if same_project {+ let next = with_key(setup.server.clone(), composio::PROJECT_KEY_HEADER, &key);+ return match state.db.update_mcp_server(&next).await {+ Ok(Some(saved)) => {+ forget_apps(&state, &space);+ reply(&saved, "session", Some(stored.user_id.clone()), false)+ }+ _ => error(StatusCode::INTERNAL_SERVER_ERROR, "could not save the key"),+ };+ }+ let session = match state.composio_api.create_session(&key, &stored.user_id).await {+ Ok(s) => s,+ Err(e) => return key_failed(e, &key),+ };+ match move_to_session(&state, &space, &setup.server, &key, &session).await {+ Ok(saved) => reply(&saved, "session", Some(session.user_id), true),+ Err(r) => r,+ }+ }+ None => {+ if let Err(e) = state.composio_api.check_key(&key).await {+ return key_failed(e, &key);+ }+ let next = with_key(setup.server.clone(), composio::PROJECT_KEY_HEADER, &key);+ match state.db.update_mcp_server(&next).await {+ Ok(Some(saved)) => {+ forget_apps(&state, &space);+ reply(&saved, "url", setup.user_id(), false)+ }+ _ => error(StatusCode::INTERNAL_SERVER_ERROR, "could not save the key"),+ }+ }+ }+}++/// The space's Composio with its key, or the reply that explains what's missing and how to fix+/// it. Nothing here calls Composio.+#[allow(clippy::result_large_err)]+async fn composio_with_key(state: &AppState, space: &SpaceId) -> Result<(ComposioSetup, String), Response> {+ let Some(setup) = composio_setup(state, space).await else {+ return Err(error_with(+ StatusCode::CONFLICT,+ "Add Composio first: paste your free Composio API key in Apps & accounts. kwant never contacts Composio before that.",+ "add_composio",+ ));};- let Some(key) = composio_key(&server).map(str::to_string) else {- return Err(error(StatusCode::CONFLICT, "Finding apps needs your Composio API key: add it as the x-api-key header of the Composio MCP server"));+ let Some(key) = setup.key.clone() else {+ return Err(error_with(StatusCode::CONFLICT, "Add your Composio API key to finish setting up Composio.", "replace_key"));};- Ok((server, key))+ Ok((setup, key))+}++/// The Composio user to connect apps for, or the reply that offers the switch.+#[allow(clippy::result_large_err)]+fn user_or_switch(setup: &ComposioSetup) -> Result<String, Response> {+ setup.user_id().ok_or_else(|| {+ error_with(+ StatusCode::CONFLICT,+ "This Composio setup doesn't say which Composio user your apps belong to. Switch to the one-key setup and kwant picks one.",+ "switch",+ )+ })}fn composio_failed(e: composio::ComposioError) -> Response {- let status = match e {- composio::ComposioError::KeyRefused => StatusCode::CONFLICT,- _ => StatusCode::BAD_GATEWAY,+ let status = if e.is_key() { StatusCode::CONFLICT } else { StatusCode::BAD_GATEWAY };+ error_with(status, &e.message(), e.action())+}++/// Composio's popular apps as rows, each with `connected` from `connected` (false when unknown).+fn popular_rows<'a>(apps: impl Iterator<Item = &'a composio::PopularApp>, connected: Option<&std::collections::BTreeSet<String>>) -> Vec<Value> {+ apps.map(|a| {+ let mut row = serde_json::to_value(a).unwrap_or(Value::Null);+ row["connected"] = json!(connected.is_some_and(|c| c.contains(&a.slug)));+ row+ })+ .collect()+}++/// Before Composio is added: Composio's popular apps from kwant itself, no Composio call.+fn popular_before_setup(q: Option<&str>) -> Response {+ let apps: Vec<&composio::PopularApp> = match q {+ Some(q) => composio::search_popular(q, SEARCH_POPULAR_LIMIT),+ None => composio::popular_apps().iter().collect(),};- error(status, &e.message())+ let count = apps.len();+ Json(json!({+ "apps": popular_rows(apps.into_iter(), None),+ "count": count,+ "connected_checked": false,+ "mode": Value::Null,+ "can_connect": false,+ "source": "popular",+ "warning": COMPOSIO_WARNING,+ }))+ .into_response()+}++/// At most this many popular apps answer a search; their status is one Composio call.+const SEARCH_POPULAR_LIMIT: usize = 20;++type SearchSeen = HashMap<(String, u64, String), (std::time::Instant, std::collections::BTreeSet<String>)>;++fn connect_searches() -> &'static Mutex<SearchSeen> {+ static SEEN: OnceLock<Mutex<SearchSeen>> = OnceLock::new();+ SEEN.get_or_init(Default::default)+}++/// Which of `slugs` are connected with Composio Connect: the one-minute tile cache when fresh,+/// else one `list` call for just these apps, itself kept a minute. `None` when it can't be told.+async fn connect_search_status(state: &AppState, space: &SpaceId, key: &str, slugs: &[&str]) -> Option<std::collections::BTreeSet<String>> {+ let ck = cache_key(state, space);+ let fp = fingerprint(key, "");+ if let Some(s) = apps_seen().lock().unwrap_or_else(|e| e.into_inner()).get(&ck) {+ if s.fingerprint == fp && s.at.elapsed() < APPS_TTL && s.problem.is_none() {+ return Some(s.apps.clone());+ }+ }+ if slugs.is_empty() {+ return Some(Default::default());+ }+ let lk = (ck.clone(), fp, slugs.join(","));+ {+ let mut seen = connect_searches().lock().unwrap_or_else(|e| e.into_inner());+ seen.retain(|_, (at, _)| at.elapsed() < APPS_TTL);+ if seen.len() > 1000 {+ seen.clear();+ }+ if let Some((_, apps)) = seen.get(&lk) {+ return Some(apps.clone());+ }+ }+ match state.composio_api.connect_active(key, slugs).await {+ Ok(mut apps) => {+ apps.extend(apps_through_kwant(&ck, fp).into_iter().filter(|a| slugs.contains(&a.as_str())));+ connect_searches().lock().unwrap_or_else(|e| e.into_inner()).insert(lk, (std::time::Instant::now(), apps.clone()));+ Some(apps)+ }+ Err(e) => {+ tracing::warn!(error = %e.message(), "connections: could not check Composio Connect apps");+ None+ }+ }+}++/// With a Composio Connect key: Composio's popular apps (Composio Connect has no catalogue+/// call), each with `connected`.+async fn connect_popular(state: &AppState, space: &SpaceId, setup: &ComposioSetup, key: &str, q: Option<&str>) -> Response {+ let (apps, connected) = match q {+ None => {+ let seen = connected_apps_cached(state, space, setup).await;+ (composio::popular_apps().iter().collect::<Vec<_>>(), seen.filter(|s| s.problem.is_none()).map(|s| s.apps))+ }+ Some(q) => {+ let apps = composio::search_popular(q, SEARCH_POPULAR_LIMIT);+ let slugs: Vec<&str> = apps.iter().map(|a| a.slug.as_str()).collect();+ let connected = connect_search_status(state, space, key, &slugs).await;+ (apps, connected)+ }+ };+ let count = apps.len();+ Json(json!({+ "apps": popular_rows(apps.into_iter(), connected.as_ref()),+ "count": count,+ "connected_checked": connected.is_some(),+ "mode": "connect",+ "can_connect": true,+ "source": "popular",+ "warning": COMPOSIO_WARNING,+ }))+ .into_response()}#[derive(Debug, Deserialize)]pub struct AppSearch {+ /// Without `q` the whole catalogue comes back, for matching in the browser.#[serde(default)]- pub q: String,+ pub q: Option<String>,+}++// The whole Composio catalogue, per Composio client and key, kept a day: the app list barely+// changes, and Find a tool matches every keystroke against it in the browser. A day-old list is+// still served at once while a fresh one loads in the background.++const LIST_TTL: std::time::Duration = std::time::Duration::from_secs(24 * 60 * 60);++#[derive(Debug, Clone, Serialize)]+struct ListedApp {+ slug: String,+ name: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ logo: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ tools_count: Option<u64>,+}++#[derive(Debug, Clone)]+struct AppList {+ at: std::time::Instant,+ fetched_at: DateTime<Utc>,+ apps: Arc<Vec<ListedApp>>,+ refreshing: bool,+}++fn app_lists() -> &'static Mutex<HashMap<String, AppList>> {+ static LISTS: OnceLock<Mutex<HashMap<String, AppList>>> = OnceLock::new();+ LISTS.get_or_init(Default::default)+}++fn list_key(state: &AppState, key: &str) -> String {+ format!("{:p}:{:x}", Arc::as_ptr(&state.composio_api), fingerprint(key, ""))+}++fn store_list(lk: &str, apps: Vec<composio::ComposioApp>) -> AppList {+ learn_names(&apps);+ let listed = apps+ .into_iter()+ .map(|a| ListedApp { slug: a.slug, name: a.name, logo: a.logo, tools_count: a.tools_count })+ .collect();+ let list = AppList { at: std::time::Instant::now(), fetched_at: Utc::now(), apps: Arc::new(listed), refreshing: false };+ let mut lists = app_lists().lock().unwrap_or_else(|e| e.into_inner());+ if lists.len() > 64 {+ lists.retain(|_, l| l.at.elapsed() < LIST_TTL);+ }+ lists.insert(lk.to_string(), list.clone());+ list+}++/// The catalogue for `key`: cached, else one paged fetch. A list older than a day is served as it+/// is while one background fetch replaces it.+async fn whole_list(state: &AppState, key: &str) -> Result<AppList, composio::ComposioError> {+ let lk = list_key(state, key);+ let cached = {+ let mut lists = app_lists().lock().unwrap_or_else(|e| e.into_inner());+ match lists.get_mut(&lk) {+ Some(l) => {+ let stale = l.at.elapsed() >= LIST_TTL && !l.refreshing;+ if stale {+ l.refreshing = true;+ }+ Some((l.clone(), stale))+ }+ None => None,+ }+ };+ match cached {+ Some((list, stale)) => {+ if stale {+ let (api, key, lk) = (state.composio_api.clone(), key.to_string(), lk.clone());+ tokio::spawn(async move {+ match api.all_apps(&key).await {+ Ok(apps) => {+ store_list(&lk, apps);+ }+ Err(e) => {+ tracing::warn!(error = %e.message(), "connections: could not refresh the Composio app list");+ if let Some(l) = app_lists().lock().unwrap_or_else(|e| e.into_inner()).get_mut(&lk) {+ l.refreshing = false;+ }+ }+ }+ });+ }+ Ok(list)+ }+ None => Ok(store_list(&lk, state.composio_api.all_apps(key).await?)),+ }}-/// `GET /api/connections/composio/apps?space=&q=`: apps in Composio's catalogue matching `q`,-/// searched with the person's own Composio key. 409 when Composio isn't added or has no key.+fn if_none_match(headers: &HeaderMap, etag: &str) -> bool {+ headers+ .get(axum::http::header::IF_NONE_MATCH)+ .and_then(|v| v.to_str().ok())+ .is_some_and(|v| v.split(',').any(|t| t.trim().trim_start_matches("W/") == etag))+}++/// `GET /api/connections/composio/apps?space=` without `q`: every app in Composio's catalogue,+/// compact, with `connected` for the space's user (that from the one-minute apps cache, so at+/// most one account call). Sends an `ETag`; a matching `If-None-Match` gets `304`.+async fn list_composio_apps(state: &AppState, headers: &HeaderMap, space: &SpaceId, setup: &ComposioSetup, key: &str) -> Response {+ let started = std::time::Instant::now();+ let list = match whole_list(state, key).await {+ Ok(l) => l,+ Err(e) => return composio_failed(e),+ };+ let user = setup.user_id();+ let seen = connected_apps_cached(state, space, setup).await;+ let connected = seen.as_ref().filter(|s| s.problem.is_none()).map(|s| s.apps.clone());+ let etag = {+ use std::hash::{Hash, Hasher};+ let mut h = std::collections::hash_map::DefaultHasher::new();+ (fingerprint(key, ""), list.fetched_at.timestamp_millis(), list.apps.len(), &connected, setup.mode(), &user).hash(&mut h);+ format!("\"{:016x}\"", h.finish())+ };+ let cache_headers = [+ (axum::http::header::ETAG, etag.clone()),+ (axum::http::header::CACHE_CONTROL, "private, no-cache".to_string()),+ ];+ if if_none_match(headers, &etag) {+ return (StatusCode::NOT_MODIFIED, cache_headers).into_response();+ }+ let apps: Vec<Value> = list+ .apps+ .iter()+ .map(|a| {+ let mut row = serde_json::to_value(a).unwrap_or(Value::Null);+ row["connected"] = json!(connected.as_ref().is_some_and(|c| c.contains(&a.slug)));+ row+ })+ .collect();+ tracing::debug!(apps = apps.len(), ms = started.elapsed().as_millis() as u64, "connections: Composio app list");+ (+ cache_headers,+ Json(json!({+ "apps": apps,+ "count": list.apps.len(),+ "fetched_at": list.fetched_at,+ "connected_checked": connected.is_some(),+ "mode": setup.mode(),+ "can_connect": user.is_some(),+ "source": "all",+ "warning": COMPOSIO_WARNING,+ })),+ )+ .into_response()+}++/// `GET /api/connections/composio/apps?space=&q=`: apps in Composio's catalogue matching `q`+/// (without `q`, the whole catalogue: see `list_composio_apps`),+/// searched with the person's own Composio key, each with `connected` for the space's Composio+/// user (one account call per search). `source` says where the apps come from: `"all"` is+/// Composio's catalogue (a project key); `"popular"` is Composio's top apps bundled with kwant,+/// served before Composio is added (no Composio call, `mode: null`) and with a Composio Connect+/// key. 409 when Composio is added without a key.pub async fn search_composio_apps(State(state): State<AppState>,headers: HeaderMap,@@ -595,28 +1467,60 @@ pub async fn search_composio_apps(if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {return r;}- let q = query.q.trim();- if q.is_empty() || q.chars().count() > composio::MAX_QUERY_CHARS {+ let q = query.q.as_deref().map(str::trim);+ if q.is_some_and(|q| q.is_empty() || q.chars().count() > composio::MAX_QUERY_CHARS) {return error(StatusCode::BAD_REQUEST, "type an app name, up to 60 characters");}- let (server, key) = match composio_with_key(&state, &space).await {+ if composio_setup(&state, &space).await.is_none() {+ return popular_before_setup(q);+ }+ let (setup, key) = match composio_with_key(&state, &space).await {Ok(found) => found,Err(r) => return r,};- match state.composio_api.search(&key, q).await {- Ok(apps) => Json(json!({- "apps": apps,- "can_connect": server.url.as_deref().and_then(composio::user_id_of).is_some(),- "warning": COMPOSIO_WARNING,- }))- .into_response(),- Err(e) => composio_failed(e),+ if setup.connect {+ return connect_popular(&state, &space, &setup, &key, q).await;}+ let Some(q) = q else {+ return list_composio_apps(&state, &headers, &space, &setup, &key).await;+ };+ let apps = match state.composio_api.search(&key, q).await {+ Ok(apps) => apps,+ Err(e) => return composio_failed(e),+ };+ learn_names(&apps);+ let user = setup.user_id();+ // One call for every app on the page; if it fails the search still answers, unchecked.+ let connected = match &user {+ Some(u) if !apps.is_empty() => {+ let result = state.composio_api.connected_apps(&key, u).await;+ remember_apps(&cache_key(&state, &space), fingerprint(&key, u), &result);+ result.ok()+ }+ _ => None,+ };+ let rows: Vec<Value> = apps+ .iter()+ .map(|a| {+ let mut row = serde_json::to_value(a).unwrap_or(Value::Null);+ row["connected"] = json!(connected.as_ref().is_some_and(|c| c.contains(&a.slug)));+ row+ })+ .collect();+ Json(json!({+ "apps": rows,+ "connected_checked": connected.is_some(),+ "mode": setup.mode(),+ "can_connect": user.is_some(),+ "source": "all",+ "warning": COMPOSIO_WARNING,+ }))+ .into_response()}/// `POST /api/connections/composio/apps/:slug/connect?space=`: starts signing in to one app on-/// Composio for the user in the connector's URL (`user_id`), and returns the address the person-/// opens. The sign-in itself happens on Composio's site.+/// Composio for the space's Composio user (the session's in the one-key setup, else the URL's+/// `user_id`), and returns the address the person opens. The sign-in happens on Composio's site.pub async fn connect_composio_app(State(state): State<AppState>,headers: HeaderMap,@@ -629,25 +1533,30 @@ pub async fn connect_composio_app(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 {+ let (setup, 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 connect the app to. Connect it on composio.dev instead",- );+ let link = match &setup.session {+ _ if setup.connect => state.composio_api.connect_add_link(&key, &slug).await,+ Some(s) => state.composio_api.session_link(&key, &s.session_id, &slug).await,+ None => {+ let user_id = match user_or_switch(&setup) {+ Ok(u) => u,+ Err(r) => return r,+ };+ state.composio_api.connect_link(&key, &user_id, &slug).await+ }};- match state.composio_api.connect_link(&key, &user_id, &slug).await {+ match link {Ok(redirect_url) => Json(json!({"redirect_url": redirect_url, "warning": COMPOSIO_WARNING})).into_response(),Err(e) => composio_failed(e),}}-/// `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.+/// `GET /api/connections/composio/apps/:slug/status?space=`: whether the space's Composio user has+/// finished signing in to the app on Composio: `{"connected": bool}`. The connection card and Find+/// a tool poll it after Connect. 409 when Composio can't be used for this.pub async fn composio_app_status(State(state): State<AppState>,headers: HeaderMap,@@ -660,18 +1569,29 @@ pub async fn composio_app_status(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 {+ let (setup, 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",- );+ if setup.connect {+ return match state.composio_api.connect_active(&key, &[slug.as_str()]).await {+ Ok(active) => {+ let connected = active.contains(&slug);+ note_app(&cache_key(&state, &space), fingerprint(&key, ""), &slug, connected);+ Json(json!({"connected": connected})).into_response()+ }+ Err(e) => composio_failed(e),+ };+ }+ let user_id = match user_or_switch(&setup) {+ Ok(u) => u,+ Err(r) => return r,};match state.composio_api.is_connected(&key, &user_id, &slug).await {- Ok(connected) => Json(json!({"connected": connected})).into_response(),+ Ok(connected) => {+ note_app(&cache_key(&state, &space), fingerprint(&key, &user_id), &slug, connected);+ Json(json!({"connected": connected})).into_response()+ }Err(e) => composio_failed(e),}}diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 87cb18f5..02033453 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -242,7 +242,8 @@ pub fn offers_browser_sign_in(scope: &SelfScope) -> bool {/// A connection card is an extra only when the space's Composio is `ready`. Ends in a newline.pub fn browser_sign_in_rule(composio: super::connection_suggest::ComposioReady) -> String {let extra = if composio == super::connection_suggest::ComposioReady::Ready {- "If the app also has a Composio integration, you may add a `connection_suggest` card as an extra, after the sign-in step."+ "If the app also has a Composio integration, you may add a `connection_suggest` card as an extra, after the sign-in step. \+ When a Composio tool gives you a sign-in link, post a `connection_suggest` card instead of pasting the link."} else {"Composio isn't set up in this space, so don't post a `connection_suggest` card or Composio setup steps for a website you can open in the browser."};@@ -2254,6 +2255,7 @@ mod tests {}// A connection card is only an extra, and only when Composio can start a sign-inassert!(browser_sign_in_rule(ComposioReady::Ready).contains("may add a `connection_suggest` card as an extra, after the sign-in step"));+ assert!(browser_sign_in_rule(ComposioReady::Ready).contains("instead of pasting the link"));for ready in [ComposioReady::NotAdded, ComposioReady::NeedsKey, ComposioReady::Off] {let rule = browser_sign_in_rule(ready);assert!(rule.contains("don't post a `connection_suggest` card or Composio setup steps"), "{rule}");diff --git a/src/server/mod.rs b/src/server/mod.rsindex 0e4cc125..82bbc858 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -406,6 +406,8 @@ pub fn create_router(state: AppState) -> Router {.route("/api/connections/telegram/unpair/undo", post(telegram::routes::undo_unpair)).route("/api/connections/telegram/test", post(telegram::routes::test)).route("/api/connections/composio", post(connections::add_composio))+ .route("/api/connections/composio/switch", post(connections::switch_composio))+ .route("/api/connections/composio/key", put(connections::replace_composio_key)).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))diff --git a/tests/blocked_offers_test.rs b/tests/blocked_offers_test.rsindex 1055188b..c1e50734 100644--- a/tests/blocked_offers_test.rs+++ b/tests/blocked_offers_test.rs@@ -90,7 +90,8 @@ async fn a_connection_suggestion_posts_one_card_per_app_with_the_steps() {let cards: Vec<_> = messages(&env, &env.a).await.into_iter().filter(|m| m.text.starts_with("Suggested connection:")).collect();assert_eq!(cards.len(), 1);assert_eq!(cards[0].sender_role, "kwant");- assert!(cards[0].text.contains("find Google Search Console and press Connect"), "{}", cards[0].text);+ assert!(cards[0].text.contains("then find Google Search Console under Composio in Apps & accounts and press Connect"), "{}", cards[0].text);+ assert!(cards[0].text.contains("add Composio with your free key in Apps & accounts"), "{}", cards[0].text);let meta: Value = serde_json::from_str(cards[0].meta.as_deref().unwrap()).unwrap();assert_eq!(meta["kind"], "connection_suggestion");assert_eq!(meta["app"], "google_search_console");@@ -138,7 +139,7 @@ async fn with_composio_ready_the_card_goes_straight_to_connect() {let card = messages(&env, &env.a).await.into_iter().find(|m| m.text.starts_with("Suggested connection: Google Analytics")).unwrap();let meta: Value = serde_json::from_str(card.meta.as_deref().unwrap()).unwrap();assert_eq!(meta["composio"], "ready");- assert!(card.text.contains("To connect it, open Connections"), "{}", card.text);+ assert!(card.text.contains("To connect it, find Google Analytics under Composio in Apps & accounts"), "{}", card.text);}#[tokio::test]diff --git a/tests/composio_one_key_test.rs b/tests/composio_one_key_test.rsnew file mode 100644index 00000000..ed3cd484--- /dev/null+++ b/tests/composio_one_key_test.rs@@ -0,0 +1,939 @@+//! Composio with one key: the person pastes their Composio API key and kwant makes the Tool+//! Router session itself. A refused key saves nothing, an old URL setup stays as it is until+//! Switch (which keeps its Composio user), the key can be replaced, and the app search says which+//! apps are connected with one account call. A Composio Connect key (`ck_`) is checked and used+//! through Composio Connect's MCP server. A fake Composio API, with a fake Composio Connect MCP+//! server answering in SSE, stands in for the real ones.++mod common;++use axum::{+ extract::{Path, Query, State},+ http::{HeaderMap, StatusCode},+ routing::{get, post},+ Json, Router,+};+use common::*;+use kwnt::mcp::composio::ComposioApi;+use kwnt::server::{continuity::SelfScope, mcp_runtime};+use serde_json::{json, Value};+use std::collections::{BTreeSet, HashMap};+use std::sync::{Arc, Mutex};+use tower::ServiceExt;++const REFUSED: &str = "Composio didn't accept this key. Copy your key again from your Composio dashboard.";++#[derive(Default)]+struct Fake {+ /// method, path with sorted query, x-api-key, JSON body+ seen: Vec<(String, String, String, Value)>,+ /// session id → (project, user)+ sessions: HashMap<String, (String, String)>,+ /// apps with a working account on Composio Connect+ active: BTreeSet<String>,+}+type Shared = Arc<Mutex<Fake>>;++fn key_of(h: &HeaderMap) -> String {+ h.get("x-api-key").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string()+}++/// The fake's keys: two of project p1, one of p2, and the refusals.+fn project(key: &str) -> Result<&'static str, (StatusCode, Json<Value>)> {+ match key {+ "ak_good" | "ak_good2" | "ak_big" => Ok("p1"),+ "ak_other" => Ok("p2"),+ "ak_scoped" => Err((StatusCode::FORBIDDEN, Json(json!({"error": {"message": "missing permission"}})))),+ "ak_down" => Err((StatusCode::INTERNAL_SERVER_ERROR, Json(json!({"error": {"message": "boom"}})))),+ _ => Err((+ StatusCode::UNAUTHORIZED,+ Json(json!({"error": {"message": "Invalid API key: ak_**l123", "code": 10401, "slug": "APIKey_InvalidAPIKey"}})),+ )),+ }+}++fn query_path(path: &str, q: &HashMap<String, String>) -> String {+ let mut pairs: Vec<_> = q.iter().map(|(k, v)| format!("{k}={v}")).collect();+ pairs.sort();+ if pairs.is_empty() { path.to_string() } else { format!("{path}?{}", pairs.join("&")) }+}++/// Composio Connect's MCP server as Composio runs it: stateless, every answer one SSE event.+/// `ck_good` and `ck_other` are accepted, `ck_down` gets 500, any other key 401. Calls are+/// recorded as `/connect/mcp <method>` (and the action of a MANAGE_CONNECTIONS call) with the+/// `x-consumer-api-key` and the call's arguments.+async fn fake_connect(State(f): State<Shared>, h: HeaderMap, Json(body): Json<Value>) -> axum::response::Response {+ use axum::response::IntoResponse;+ let key = h.get("x-consumer-api-key").and_then(|v| v.to_str().ok()).unwrap_or_default().to_string();+ assert!(h.get("x-api-key").is_none(), "a Composio Connect key goes only in x-consumer-api-key");+ let method = body["method"].as_str().unwrap_or_default().to_string();+ let args = body["params"]["arguments"].clone();+ let what = match method.as_str() {+ "tools/call" => format!("/connect/mcp tools/call {}", args["toolkits"][0]["action"].as_str().unwrap_or_default()),+ m => format!("/connect/mcp {m}"),+ };+ let mut f = f.lock().unwrap();+ f.seen.push(("POST".into(), what, key.clone(), args.clone()));+ match key.as_str() {+ "ck_good" | "ck_other" => {}+ "ck_down" => return (StatusCode::INTERNAL_SERVER_ERROR, "boom").into_response(),+ _ => return (StatusCode::UNAUTHORIZED, Json(json!({"error": "invalid consumer api key"}))).into_response(),+ }+ let Some(id) = body.get("id").cloned() else {+ return StatusCode::ACCEPTED.into_response();+ };+ let result = match method.as_str() {+ "initialize" => json!({+ "protocolVersion": "2025-06-18",+ "capabilities": {"tools": {}},+ "serverInfo": {"name": "fake-composio-connect", "version": "1"},+ }),+ "tools/list" => json!({"tools": [+ {"name": "COMPOSIO_SEARCH_TOOLS", "description": "search", "inputSchema": {"type": "object"}},+ {"name": "COMPOSIO_MANAGE_CONNECTIONS", "description": "connections", "inputSchema": {"type": "object"}},+ {"name": "COMPOSIO_MULTI_EXECUTE_TOOL", "description": "run", "inputSchema": {"type": "object"}},+ ]}),+ "tools/call" if body["params"]["name"] == "COMPOSIO_MANAGE_CONNECTIONS" => {+ let mut results = serde_json::Map::new();+ for t in args["toolkits"].as_array().cloned().unwrap_or_default() {+ let slug = t["name"].as_str().unwrap_or_default().to_string();+ let entry = match t["action"].as_str() {+ Some("add") => json!({"toolkit": slug, "status": "initiated", "redirect_url": format!("https://connect.composio.dev/link/lk_{slug}")}),+ _ if f.active.contains(&slug) => json!({"toolkit": slug, "status": "active", "accounts": [{"id": format!("ca_{slug}"), "status": "active"}]}),+ _ => json!({"toolkit": slug, "status": "not_connected", "accounts": []}),+ };+ results.insert(slug, entry);+ }+ let text = json!({"successful": true, "data": {"results": results}, "error": null}).to_string();+ json!({"content": [{"type": "text", "text": text}], "isError": false})+ }+ _ => json!({"content": [{"type": "text", "text": "not in this fake"}], "isError": true}),+ };+ let event = format!("event: message\ndata: {}\n\n", json!({"jsonrpc": "2.0", "id": id, "result": result}));+ ([(axum::http::header::CONTENT_TYPE, "text/event-stream")], event).into_response()+}++async fn fake_composio() -> (String, Shared) {+ let fake: Shared = Arc::default();+ let app = Router::new()+ .route("/connect/mcp", post(fake_connect))+ .route(+ "/api/v3.1/tool_router/session",+ post(|State(f): State<Shared>, h: HeaderMap, Json(body): Json<Value>| async move {+ let mut f = f.lock().unwrap();+ f.seen.push(("POST".into(), "/api/v3.1/tool_router/session".into(), key_of(&h), body.clone()));+ let p = match project(&key_of(&h)) {+ Ok(p) => p,+ Err(e) => return e,+ };+ let id = format!("trs_{}", f.sessions.len() + 1);+ let user = body["user_id"].as_str().unwrap_or_default().to_string();+ f.sessions.insert(id.clone(), (p.into(), user.clone()));+ (+ StatusCode::CREATED,+ Json(json!({+ "session_id": id,+ "mcp": {"type": "http", "url": format!("https://backend.composio.dev/tool_router/{id}/mcp")},+ "tool_router_tools": ["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_MANAGE_CONNECTIONS", "COMPOSIO_MULTI_EXECUTE_TOOL"],+ "config": {"user_id": user, "manage_connections": {"enabled": true}},+ })),+ )+ }),+ )+ .route(+ "/api/v3.1/tool_router/session/:id",+ get(|State(f): State<Shared>, Path(id): Path<String>, h: HeaderMap| async move {+ let mut f = f.lock().unwrap();+ f.seen.push(("GET".into(), format!("/api/v3.1/tool_router/session/{id}"), key_of(&h), Value::Null));+ let p = match project(&key_of(&h)) {+ Ok(p) => p,+ Err(e) => return e,+ };+ match f.sessions.get(&id) {+ Some((sp, user)) if sp == p => {+ (StatusCode::OK, Json(json!({"session_id": id, "config": {"user_id": user}})))+ }+ _ => (StatusCode::NOT_FOUND, Json(json!({"error": {"message": "session not found"}}))),+ }+ }),+ )+ .route(+ "/api/v3.1/tool_router/session/:id/link",+ post(|State(f): State<Shared>, Path(id): Path<String>, h: HeaderMap, Json(body): Json<Value>| async move {+ f.lock().unwrap().seen.push(("POST".into(), format!("/api/v3.1/tool_router/session/{id}/link"), key_of(&h), body));+ if let Err(e) = project(&key_of(&h)) {+ return e;+ }+ (StatusCode::CREATED, Json(json!({"redirect_url": "https://connect.composio.dev/link/ln_1"})))+ }),+ )+ .route(+ "/api/v3.1/toolkits",+ get(|State(f): State<Shared>, h: HeaderMap, Query(q): Query<HashMap<String, String>>| async move {+ f.lock().unwrap().seen.push(("GET".into(), query_path("/api/v3.1/toolkits", &q), key_of(&h), Value::Null));+ if let Err(e) = project(&key_of(&h)) {+ return e;+ }+ // ak_big's project has a catalogue the size of Composio's: 1,000 apps in pages of 500.+ if key_of(&h) == "ak_big" && !q.contains_key("search") {+ let start = match q.get("cursor").map(String::as_str) { Some("p2") => 500, _ => 0 };+ let items: Vec<Value> = (start..start + 500)+ .map(|i| json!({"slug": format!("app_{i:04}"), "name": format!("Example App {i}"),+ "meta": {"tools_count": i % 120, "logo": format!("https://logos.composio.dev/api/app_{i:04}"),+ "description": "A long description that the compact list leaves out."}}))+ .collect();+ return (StatusCode::OK, Json(json!({"items": items, "next_cursor": if start == 0 { json!("p2") } else { Value::Null }})));+ }+ // The whole catalogue (no search) comes in pages.+ if !q.contains_key("search") {+ return match q.get("cursor").map(String::as_str) {+ None => (StatusCode::OK, Json(json!({"items": [+ {"slug": "gmail", "name": "Gmail", "meta": {"tools_count": 23, "logo": "https://logos.composio.dev/gmail.png", "description": "long text left out"}},+ {"slug": "slack", "name": "Slack", "meta": {"tools_count": 40, "logo": "http://insecure.example/slack.png"}}+ ], "next_cursor": "c2"}))),+ Some("c2") => (StatusCode::OK, Json(json!({"items": [+ {"slug": "notion", "name": "Notion"},+ {"slug": "gmail", "name": "Gmail again"},+ {"slug": "Bad Slug", "name": "Bad"}+ ], "next_cursor": null}))),+ _ => (StatusCode::BAD_REQUEST, Json(json!({"error": {"message": "bad cursor"}}))),+ };+ }+ (+ StatusCode::OK,+ Json(json!({"items": [+ {"slug": "gmail", "name": "Gmail", "meta": {"tools_count": 23}},+ {"slug": "slack", "name": "Slack", "meta": {"tools_count": 40}},+ {"slug": "notion", "name": "Notion", "meta": {"tools_count": 30}}+ ]})),+ )+ }),+ )+ .route(+ "/api/v3.1/connected_accounts",+ get(|State(f): State<Shared>, h: HeaderMap, Query(q): Query<HashMap<String, String>>| async move {+ f.lock().unwrap().seen.push(("GET".into(), query_path("/api/v3.1/connected_accounts", &q), key_of(&h), Value::Null));+ if let Err(e) = project(&key_of(&h)) {+ return e;+ }+ let user = q.get("user_ids").cloned().unwrap_or_default();+ let mut items = vec![];+ // the space's own user has Gmail and Notion; the old URL's user has Slack; Linear+ // is only half signed in+ let apps: &[&str] = if user.starts_with("kwant-") { &["gmail", "notion"] } else if user == "u-old" { &["slack"] } else { &[] };+ for a in apps {+ items.push(json!({"id": format!("ca_{a}"), "status": "ACTIVE", "user_id": user, "toolkit": {"slug": a}}));+ }+ items.push(json!({"id": "ca_linear", "status": "INITIATED", "user_id": user, "toolkit": {"slug": "linear"}}));+ if let Some(t) = q.get("toolkit_slugs") {+ items.retain(|i| i["toolkit"]["slug"] == json!(t));+ }+ (StatusCode::OK, Json(json!({"items": items, "next_cursor": null})))+ }),+ )+ .with_state(fake.clone());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ tokio::spawn(async move {+ let _ = axum::serve(listener, app).await;+ });+ (url, fake)+}++async fn env_with_fake() -> (Env, Shared) {+ let (url, fake) = fake_composio().await;+ let env = setup_with(|state| state.composio_api = Arc::new(ComposioApi::new(&url))).await;+ (env, fake)+}++fn calls(f: &Shared) -> Vec<(String, String, String, Value)> {+ std::mem::take(&mut f.lock().unwrap().seen)+}++async fn servers(env: &Env) -> Value {+ let (s, v) = call(&env.app, "GET", "/api/mcp/servers", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ v+}++async fn composio_entry(env: &Env) -> Value {+ let (s, v) = call(&env.app, "GET", "/api/connections", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ v["catalog"].as_array().unwrap().iter().find(|e| e["id"] == "composio").cloned().unwrap()+}++#[tokio::test]+async fn a_key_alone_adds_composio_through_a_session() {+ let (env, fake) = env_with_fake().await;+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": " ak_good \n"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["mode"], "session", "{v}");+ let user = v["user_id"].as_str().unwrap().to_string();+ assert!(user.starts_with("kwant-") && user.len() > "kwant-".len(), "the space's own Composio user: {user}");+ assert_eq!(v["server"]["name"], "composio");+ assert_eq!(v["server"]["url"], "https://backend.composio.dev/tool_router/trs_1/mcp");+ assert_eq!(v["server"]["enabled"], false, "off for bots until the person turns it on");+ assert!(v["connection_id"].as_str().unwrap().starts_with("mcp:"), "{v}");+ assert!(v["warning"].as_str().unwrap().contains("Composio's servers"));+ assert_eq!(v["tools"][1], "COMPOSIO_MANAGE_CONNECTIONS", "{v}");+ assert!(!v.to_string().contains("ak_good"), "the key is masked: {v}");++ // Exactly one call: the session, for the space's user, with connections managed in it.+ let c = calls(&fake);+ assert_eq!(c.len(), 1, "{c:?}");+ assert_eq!(c[0].1, "/api/v3.1/tool_router/session");+ assert_eq!(c[0].2, "ak_good", "the key is sent trimmed");+ assert_eq!(c[0].3, json!({"user_id": user, "manage_connections": {"enable": true}}));++ let list = servers(&env).await;+ assert_eq!(list.as_array().unwrap().len(), 1);+ assert!(!list.to_string().contains("ak_good"), "the key is masked: {list}");++ let entry = composio_entry(&env).await;+ assert_eq!(entry["added"], true);+ assert_eq!(entry["enabled"], false);+ assert_eq!(entry["mode"], "session", "{entry}");+ assert_eq!(entry["user_id"], json!(user));+ assert_eq!(entry["can_search"], true);+ assert_eq!(entry["can_connect"], true);+ assert_eq!(entry["can_switch"], false);+ assert_eq!(entry["problem"], Value::Null, "{entry}");+ assert_eq!(+ entry["apps_connected"],+ json!([{"slug": "gmail", "name": "Gmail"}, {"slug": "notion", "name": "Notion"}]),+ "{entry}"+ );+ assert!(!entry.to_string().contains("ak_good"));+ // the list asks once a minute+ composio_entry(&env).await;+ let c = calls(&fake);+ assert_eq!(c.len(), 1, "{c:?}");+ assert_eq!(c[0].1, format!("/api/v3.1/connected_accounts?limit=200&statuses=ACTIVE&user_ids={user}"));++ // Connect uses the saved session: no new one.+ let (s, v) = call(&env.app, "POST", "/api/connections/composio/apps/slack/connect", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["redirect_url"], "https://connect.composio.dev/link/ln_1");+ let c = calls(&fake);+ assert_eq!(c.iter().map(|x| x.1.as_str()).collect::<Vec<_>>(), vec!["/api/v3.1/tool_router/session/trs_1/link"]);+ assert_eq!(c[0].3, json!({"toolkit": "slack"}));++ // Status asks for the session's user.+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps/gmail/status", None).await;+ assert_eq!((s, v), (StatusCode::OK, json!({"connected": true})));+ assert!(calls(&fake)[0].1.contains(&format!("user_ids={user}")));++ // Adding again is refused: replace the key instead.+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ak_good2"}))).await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert_eq!(v["action"], "replace_key");+ assert!(calls(&fake).is_empty());+}++#[tokio::test]+async fn a_refused_key_saves_nothing() {+ let (env, fake) = env_with_fake().await;+ let add = |key: &'static str| {+ let app = env.app.clone();+ async move { call(&app, "POST", "/api/connections/composio", Some(json!({"api_key": key}))).await }+ };++ let (s, v) = add("ak_wrong").await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert_eq!(v["error"], REFUSED, "{v}");+ assert_eq!(v["action"], "replace_key");+ assert_eq!(v["key_url"], "https://dashboard.composio.dev");+ assert!(!v["error"].as_str().unwrap().contains("ak_"), "either kind of key is welcome: {v}");++ // Neither kind: tried as a project key, then on Composio Connect.+ let (s, v) = add("uak_x").await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert!(v["error"].as_str().unwrap().contains("That's a Composio user key"), "{v}");+ assert!(v["error"].as_str().unwrap().contains("It starts with ck_ or ak_."), "{v}");++ let (s, v) = add("ak_scoped").await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert!(v["error"].as_str().unwrap().contains("isn't allowed to do this"), "{v}");+ assert_eq!(v["action"], "replace_key");++ let (s, v) = add("ak_down").await;+ assert_eq!(s, StatusCode::BAD_GATEWAY, "{v}");+ assert_eq!(v["error"], "Composio couldn't be reached; try again in a minute.");+ assert_eq!(v["action"], "try_again");++ let (s, v) = add(" ").await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");+ assert_eq!(v["action"], "add_composio");+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");++ let c = calls(&fake);+ assert_eq!(c.len(), 5, "the blank keys never reach Composio: {c:?}");+ assert_eq!((c[1].1.as_str(), c[2].1.as_str()), ("/api/v3.1/connected_accounts?limit=1", "/connect/mcp initialize"), "{c:?}");+ assert_eq!(servers(&env).await, json!([]), "nothing saved");+ let entry = composio_entry(&env).await;+ assert_eq!((entry["added"].clone(), entry["mode"].clone()), (json!(false), Value::Null));+ assert!(calls(&fake).is_empty(), "nothing to list before Composio is added");+ for (_, _, _, body) in &c {+ assert!(!body.to_string().contains("ak_"), "the key goes in the header only");+ }++ // A key that can be added after all those works on the first try.+ let (s, v) = add("ak_good").await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["server"]["url"], "https://backend.composio.dev/tool_router/trs_1/mcp");+}++#[tokio::test]+async fn composio_out_of_reach_saves_nothing() {+ // Nothing listens on port 9 here.+ let env = setup_with(|state| state.composio_api = Arc::new(ComposioApi::new("http://127.0.0.1:9"))).await;+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ak_good"}))).await;+ assert_eq!(s, StatusCode::BAD_GATEWAY, "{v}");+ assert_eq!(v["error"], "Composio couldn't be reached; try again in a minute.");+ assert_eq!(v["action"], "try_again");+ assert_eq!(servers(&env).await, json!([]));+}++#[tokio::test]+async fn switch_keeps_the_user_of_the_old_setup() {+ let (env, fake) = env_with_fake().await;+ let old_url = "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-old";+ let (s, v) = call(+ &env.app,+ "POST",+ "/api/connections/composio",+ Some(json!({"url": old_url, "api_key": "ak_good", "enabled": true})),+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["mode"], "url");+ let id = v["server"]["id"].clone();+ assert!(calls(&fake).is_empty(), "a URL setup is saved as before, with no call");++ // Until Switch, listing, searching and status leave it as it is.+ let entry = composio_entry(&env).await;+ assert_eq!(entry["mode"], "url", "{entry}");+ assert_eq!(entry["can_switch"], true);+ assert_eq!(entry["user_id"], "u-old");+ assert_eq!(entry["apps_connected"], json!([{"slug": "slack", "name": "Slack"}]), "{entry}");+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps?q=sl", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["mode"], "url");+ let (s, _) = call(&env.app, "GET", "/api/connections/composio/apps/slack/status", None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(servers(&env).await[0]["url"], old_url, "untouched until Switch");+ assert!(calls(&fake).iter().all(|c| !c.1.starts_with("/api/v3.1/tool_router")), "no session made");++ let (s, v) = call(&env.app, "POST", "/api/connections/composio/switch", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!((v["switched"].clone(), v["mode"].clone(), v["user_id"].clone()), (json!(true), json!("session"), json!("u-old")), "{v}");+ assert_eq!(v["server"]["id"], id, "the same server, so which bots have it doesn't change");+ assert_eq!(v["server"]["enabled"], true, "its switch stays as it was");+ assert_eq!(v["server"]["url"], "https://backend.composio.dev/tool_router/trs_1/mcp");+ let c = calls(&fake);+ assert_eq!(c.len(), 1, "{c:?}");+ assert_eq!(c[0].3, json!({"user_id": "u-old", "manage_connections": {"enable": true}}));+ assert_eq!(c[0].2, "ak_good", "the saved key");++ let list = servers(&env).await;+ assert_eq!(list.as_array().unwrap().len(), 1);+ assert_eq!(list[0]["url"], "https://backend.composio.dev/tool_router/trs_1/mcp");+ let entry = composio_entry(&env).await;+ assert_eq!((entry["mode"].clone(), entry["user_id"].clone(), entry["can_switch"].clone()), (json!("session"), json!("u-old"), json!(false)));+ assert_eq!(entry["apps_connected"], json!([{"slug": "slack", "name": "Slack"}]), "apps connected before stay connected");++ // Again: nothing to do, nobody called.+ calls(&fake);+ let (s, v) = call(&env.app, "POST", "/api/connections/composio/switch", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["switched"], false);+ assert!(calls(&fake).is_empty());++ // Connect and status now go through the session and its user.+ let (s, _) = call(&env.app, "POST", "/api/connections/composio/apps/gmail/connect", None).await;+ assert_eq!(s, StatusCode::OK);+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps/slack/status", None).await;+ assert_eq!((s, v), (StatusCode::OK, json!({"connected": true})));+ let c: Vec<_> = calls(&fake).into_iter().map(|c| c.1).collect();+ assert_eq!(c[0], "/api/v3.1/tool_router/session/trs_1/link");+ assert!(c[1].contains("user_ids=u-old"), "{c:?}");+}++#[tokio::test]+async fn switch_without_a_user_picks_the_spaces_own_and_a_refused_key_changes_nothing() {+ let (env, fake) = env_with_fake().await;+ let old_url = "https://backend.composio.dev/v3/mcp/abc/mcp";+ let (s, _) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"url": old_url, "api_key": "ak_wrong"}))).await;+ assert_eq!(s, StatusCode::OK);+ let entry = composio_entry(&env).await;+ assert_eq!(entry["problem"]["action"], "switch", "{entry}");+ assert_eq!(entry["can_connect"], false);++ let (s, v) = call(&env.app, "POST", "/api/connections/composio/switch", None).await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert_eq!(v["error"], REFUSED);+ assert_eq!(servers(&env).await[0]["url"], old_url, "a refused key changes nothing");++ // A key given with the switch is used and saved.+ let (s, v) = call(&env.app, "POST", "/api/connections/composio/switch", Some(json!({"api_key": "ak_good"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert!(v["user_id"].as_str().unwrap().starts_with("kwant-"), "{v}");+ let c = calls(&fake);+ assert_eq!(c.last().unwrap().2, "ak_good");+ let (s, _) = call(&env.app, "GET", "/api/connections/composio/apps?q=gm", None).await;+ assert_eq!(s, StatusCode::OK);+ assert!(calls(&fake).iter().all(|c| c.2 == "ak_good"), "the new key is the saved one");++ // Not added at all: Switch says to add Composio.+ let (env2, _) = env_with_fake().await;+ let (s, v) = call(&env2.app, "POST", "/api/connections/composio/switch", None).await;+ assert_eq!((s, v["action"].clone()), (StatusCode::CONFLICT, json!("add_composio")), "{v}");+}++#[tokio::test]+async fn search_returns_connected_per_app_from_one_call() {+ let (env, fake) = env_with_fake().await;+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ak_good"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let user = v["user_id"].as_str().unwrap().to_string();+ calls(&fake);++ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps?q=a", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let connected: Vec<(String, bool)> = v["apps"]+ .as_array()+ .unwrap()+ .iter()+ .map(|a| (a["slug"].as_str().unwrap().to_string(), a["connected"].as_bool().unwrap()))+ .collect();+ assert_eq!(+ connected,+ vec![("gmail".into(), true), ("slack".into(), false), ("notion".into(), true)],+ "{v}"+ );+ assert_eq!(v["connected_checked"], true);+ assert_eq!(v["can_connect"], true, "the session can always connect");+ assert_eq!(v["mode"], "session");+ assert_eq!(v["apps"][0]["tools_count"], 23);++ let c: Vec<_> = calls(&fake).into_iter().map(|c| c.1).collect();+ assert_eq!(+ c,+ vec![+ "/api/v3.1/toolkits?limit=20&search=a&sort_by=usage".to_string(),+ format!("/api/v3.1/connected_accounts?limit=200&statuses=ACTIVE&user_ids={user}"),+ ],+ "one account call for the whole page"+ );++ // The search filled the list's cache: listing now costs nothing.+ let entry = composio_entry(&env).await;+ assert_eq!(entry["apps_connected"].as_array().unwrap().len(), 2, "{entry}");+ assert!(calls(&fake).is_empty());+}++#[tokio::test]+async fn replacing_the_key_checks_it_first() {+ let (env, fake) = env_with_fake().await;+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ak_good", "enabled": true}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let user = v["user_id"].clone();+ let id = v["server"]["id"].clone();+ calls(&fake);+ let put = |key: &'static str| {+ let app = env.app.clone();+ async move { call(&app, "PUT", "/api/connections/composio/key", Some(json!({"api_key": key}))).await }+ };+ let searched_with = || {+ let app = env.app.clone();+ let fake = fake.clone();+ async move {+ calls(&fake);+ let (s, _) = call(&app, "GET", "/api/connections/composio/apps?q=gm", None).await;+ assert_eq!(s, StatusCode::OK);+ calls(&fake)[0].2.clone()+ }+ };++ let (s, v) = put("ak_wrong").await;+ assert_eq!((s, v["error"].clone(), v["action"].clone()), (StatusCode::CONFLICT, json!(REFUSED), json!("replace_key")));+ assert_eq!(searched_with().await, "ak_good", "a refused key changes nothing");+ let (s, v) = put("").await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{v}");++ // Same Composio project: the session stays.+ let (s, v) = put("ak_good2").await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!((v["session_renewed"].clone(), v["user_id"].clone()), (json!(false), user.clone()));+ assert_eq!(v["server"]["url"], "https://backend.composio.dev/tool_router/trs_1/mcp");+ assert!(!v.to_string().contains("ak_good2"), "masked: {v}");+ assert_eq!(searched_with().await, "ak_good2");++ // Another project: a new session for the same user, on the same server.+ calls(&fake);+ let (s, v) = put("ak_other").await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!((v["session_renewed"].clone(), v["user_id"].clone()), (json!(true), user.clone()));+ assert_eq!(v["server"]["id"], id);+ assert_eq!(v["server"]["enabled"], true);+ assert_eq!(v["server"]["url"], "https://backend.composio.dev/tool_router/trs_2/mcp");+ let c = calls(&fake);+ assert_eq!(c.iter().map(|x| x.1.as_str()).collect::<Vec<_>>(), vec!["/api/v3.1/tool_router/session/trs_1", "/api/v3.1/tool_router/session"]);+ assert_eq!(c[1].3["user_id"], user);+ let (s, _) = call(&env.app, "POST", "/api/connections/composio/apps/gmail/connect", None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(calls(&fake)[0].1, "/api/v3.1/tool_router/session/trs_2/link");++ // A URL setup: the key is checked, then only the header changes.+ let (env2, fake2) = env_with_fake().await;+ let old_url = "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-old";+ call(&env2.app, "POST", "/api/connections/composio", Some(json!({"url": old_url, "api_key": "ak_good"}))).await;+ let (s, v) = call(&env2.app, "PUT", "/api/connections/composio/key", Some(json!({"api_key": "ak_wrong"}))).await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ let (s, v) = call(&env2.app, "PUT", "/api/connections/composio/key", Some(json!({"api_key": "ak_other"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!((v["mode"].clone(), v["server"]["url"].clone()), (json!("url"), json!(old_url)));+ let c: Vec<_> = calls(&fake2).into_iter().map(|c| (c.1, c.2)).collect();+ assert_eq!(+ c,+ vec![+ ("/api/v3.1/connected_accounts?limit=1".to_string(), "ak_wrong".to_string()),+ ("/api/v3.1/connected_accounts?limit=1".to_string(), "ak_other".to_string()),+ ]+ );+}++#[tokio::test]+async fn switch_and_replace_key_are_person_only() {+ let (env, fake) = env_with_fake().await;+ call(&env.app, "POST", "/api/connections/composio", Some(json!({"url": "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-old", "api_key": "ak_good"}))).await;+ assert_eq!(call_remote(&env.app, "POST", "/api/connections/composio/switch").await, StatusCode::UNAUTHORIZED);+ assert_eq!(call_remote(&env.app, "PUT", "/api/connections/composio/key").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}");+ for (method, path, body) in [+ ("POST", "/api/connections/composio/switch", json!({})),+ ("PUT", "/api/connections/composio/key", json!({"api_key": "ak_other"})),+ ("POST", "/api/connections/composio", json!({"api_key": "ak_other"})),+ ] {+ let (s, v) = call_with(&env.app, method, path, Some(body), &[("authorization", &bearer)]).await;+ assert_eq!(s, StatusCode::FORBIDDEN, "{method} {path}: {v}");+ }+ assert!(calls(&fake).is_empty(), "a bot's token never reaches Composio");+ assert_eq!(servers(&env).await[0]["url"], "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-old");+}++/// A GET with optional If-None-Match: status, ETag, JSON body.+async fn get_list(env: &Env, etag: Option<&str>) -> (StatusCode, Option<String>, Value) {+ let mut b = axum::http::Request::builder().method("GET").uri("/api/connections/composio/apps");+ if let Some(t) = etag {+ b = b.header("if-none-match", t);+ }+ let resp = env.app.clone().oneshot(b.body(axum::body::Body::empty()).unwrap()).await.unwrap();+ let status = resp.status();+ let tag = resp.headers().get("etag").map(|v| v.to_str().unwrap().to_string());+ let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (status, tag, serde_json::from_slice(&bytes).unwrap_or(Value::Null))+}++#[tokio::test]+async fn without_a_query_the_whole_catalogue_comes_back_for_autocomplete() {+ let (env, fake) = env_with_fake().await;+ // Before setup: Composio's popular apps, bundled with kwant, no Composio call.+ let (s, _, v) = get_list(&env, None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!((v["source"].clone(), v["mode"].clone(), v["can_connect"].clone()), (json!("popular"), Value::Null, json!(false)), "{v}");+ assert_eq!(v["count"], 120);+ assert_eq!(v["apps"][0]["slug"], "gmail");+ assert!(v["apps"].as_array().unwrap().iter().all(|a| a["connected"] == false), "{v}");+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps?q=gma", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let slugs: Vec<&str> = v["apps"].as_array().unwrap().iter().map(|a| a["slug"].as_str().unwrap()).collect();+ assert_eq!(slugs, vec!["gmail", "figma"], "{v}");+ assert_eq!(v["source"], "popular");+ assert!(calls(&fake).is_empty());++ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ak_good"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let user = v["user_id"].as_str().unwrap().to_string();+ calls(&fake);++ let (s, etag, v) = get_list(&env, None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let etag = etag.expect("an ETag");+ assert_eq!(+ v["apps"],+ json!([+ {"slug": "gmail", "name": "Gmail", "logo": "https://logos.composio.dev/gmail.png", "tools_count": 23, "connected": true},+ {"slug": "slack", "name": "Slack", "tools_count": 40, "connected": false},+ {"slug": "notion", "name": "Notion", "connected": true}+ ]),+ "compact, every page, no duplicates, no bad slugs, https logos only: {v}"+ );+ assert_eq!(v["count"], 3);+ assert_eq!(v["connected_checked"], true);+ assert_eq!(v["mode"], "session");+ assert_eq!(v["source"], "all", "a project key lists Composio's whole catalogue");+ assert!(v["fetched_at"].is_string(), "{v}");+ let c: Vec<_> = calls(&fake).into_iter().map(|c| c.1).collect();+ assert_eq!(+ c,+ vec![+ "/api/v3.1/toolkits?limit=500&sort_by=usage".to_string(),+ "/api/v3.1/toolkits?cursor=c2&limit=500&sort_by=usage".to_string(),+ format!("/api/v3.1/connected_accounts?limit=200&statuses=ACTIVE&user_ids={user}"),+ ]+ );++ // Unchanged: 304 with the same ETag and no Composio call.+ let (s, again, v) = get_list(&env, Some(&etag)).await;+ assert_eq!((s, again.as_deref(), v), (StatusCode::NOT_MODIFIED, Some(etag.as_str()), Value::Null));+ let (s, _, _) = get_list(&env, Some(&format!("W/{etag}, \"other\""))).await;+ assert_eq!(s, StatusCode::NOT_MODIFIED, "weak and listed tags match too");+ let (s, _, v) = get_list(&env, Some("\"stale\"")).await;+ assert_eq!((s, v["count"].clone()), (StatusCode::OK, json!(3)));+ assert!(calls(&fake).is_empty(), "the list is kept a day and the connected apps a minute");++ // A blank q is still a mistake; q searches as before.+ let (s, _) = call(&env.app, "GET", "/api/connections/composio/apps?q=", None).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps?q=gm", None).await;+ assert_eq!((s, v["apps"].as_array().unwrap().len()), (StatusCode::OK, 3), "{v}");++ // Another key gets its own list; a refused key gets the usual 409.+ let (s, _) = call(&env.app, "PUT", "/api/connections/composio/key", Some(json!({"api_key": "ak_good2"}))).await;+ assert_eq!(s, StatusCode::OK);+ calls(&fake);+ let (s, etag2, _) = get_list(&env, Some(&etag)).await;+ assert_eq!(s, StatusCode::OK, "a new key is a new list");+ assert_ne!(etag2.as_deref(), Some(etag.as_str()));+ assert_eq!(calls(&fake).iter().filter(|c| c.1.starts_with("/api/v3.1/toolkits")).count(), 2);+}++/// The figures for impl.md: a Composio-sized catalogue (1,000 apps) as the UI gets it, with the+/// response size raw and gzipped, and the time cold (fetched from the fake) and warm (from memory).+#[tokio::test]+async fn a_thousand_app_catalogue_is_small_and_served_from_memory() {+ use std::io::Write;+ let (env, fake) = env_with_fake().await;+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ak_big"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ calls(&fake);+ let raw = |env: &Env| {+ let app = env.app.clone();+ async move {+ let req = axum::http::Request::builder().uri("/api/connections/composio/apps").body(axum::body::Body::empty()).unwrap();+ let resp = app.oneshot(req).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ axum::body::to_bytes(resp.into_body(), usize::MAX).await.unwrap()+ }+ };+ let t = std::time::Instant::now();+ let cold = raw(&env).await;+ let cold_ms = t.elapsed().as_secs_f64() * 1000.0;+ let t = std::time::Instant::now();+ let warm = raw(&env).await;+ let warm_ms = t.elapsed().as_secs_f64() * 1000.0;+ let v: Value = serde_json::from_slice(&warm).unwrap();+ assert_eq!(v["count"], 1000);+ assert_eq!(v["apps"][0], json!({"slug": "app_0000", "name": "Example App 0", "logo": "https://logos.composio.dev/api/app_0000", "tools_count": 0, "connected": false}));+ let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());+ gz.write_all(&warm).unwrap();+ let gz = gz.finish().unwrap();+ eprintln!(+ "composio list: {} apps, {} bytes raw, {} bytes gzipped, cold {cold_ms:.1} ms, warm {warm_ms:.1} ms",+ v["count"], warm.len(), gz.len()+ );+ assert_eq!(cold.len(), warm.len());+ assert!(gz.len() < 64 * 1024, "about 60 KB gzipped at most: {}", gz.len());+ assert!(warm_ms < 1000.0, "the warm list comes from memory: {warm_ms} ms");+ let toolkit_calls = calls(&fake).iter().filter(|c| c.1.starts_with("/api/v3.1/toolkits")).count();+ assert_eq!(toolkit_calls, 2, "two pages, fetched once");+}++/// The `/connect/mcp` calls since the last look, as (what, key).+fn connect_calls(f: &Shared) -> Vec<(String, String)> {+ calls(f).into_iter().map(|c| (c.1, c.2)).collect()+}++fn handshake(key: &str) -> Vec<(String, String)> {+ ["initialize", "notifications/initialized"].iter().map(|m| (format!("/connect/mcp {m}"), key.to_string())).collect()+}++#[tokio::test]+async fn a_composio_connect_key_is_checked_over_mcp_and_saved_for_composio_connect() {+ let (env, fake) = env_with_fake().await;+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": " ck_good\n"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["mode"], "connect", "{v}");+ assert_eq!(v["user_id"], Value::Null, "the key is the person's own Composio account");+ assert_eq!(v["server"]["name"], "composio");+ assert_eq!(v["server"]["url"], "https://connect.composio.dev/mcp", "bots use Composio Connect itself");+ assert_eq!(v["server"]["enabled"], false, "off for bots until the person turns it on");+ assert_eq!(v["tools"][1], "COMPOSIO_MANAGE_CONNECTIONS", "{v}");+ assert!(v["warning"].as_str().unwrap().contains("Composio's servers"));+ assert!(!v.to_string().contains("ck_good"), "the key is masked: {v}");++ // The check is the MCP handshake and tools/list, with the key trimmed, and nothing else.+ let mut want = handshake("ck_good");+ want.push(("/connect/mcp tools/list".into(), "ck_good".into()));+ assert_eq!(connect_calls(&fake), want);++ let list = servers(&env).await;+ assert_eq!(list.as_array().unwrap().len(), 1);+ assert_eq!(list[0]["url"], "https://connect.composio.dev/mcp");+ assert!(!list.to_string().contains("ck_good"), "the key is masked: {list}");+ let saved = env.state.db.list_mcp_servers(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();+ assert_eq!(+ saved[0].headers,+ std::collections::BTreeMap::from([("x-consumer-api-key".to_string(), "ck_good".to_string())]),+ "the key is saved in Composio Connect's header"+ );++ // The tile: one list call over the popular apps, kept a minute.+ fake.lock().unwrap().active.insert("gmail".into());+ let entry = composio_entry(&env).await;+ assert_eq!(entry["mode"], "connect", "{entry}");+ assert_eq!(entry["user_id"], Value::Null);+ assert_eq!((entry["can_search"].clone(), entry["can_connect"].clone(), entry["can_switch"].clone()), (json!(true), json!(true), json!(false)));+ assert_eq!(entry["problem"], Value::Null, "{entry}");+ assert_eq!(entry["apps_connected"], json!([{"slug": "gmail", "name": "Gmail"}]), "{entry}");+ let c = calls(&fake);+ assert_eq!(c.iter().filter(|x| x.1 == "/connect/mcp tools/call list").count(), 1, "{c:?}");+ let asked = c.iter().find(|x| x.1 == "/connect/mcp tools/call list").unwrap();+ assert_eq!(asked.3["toolkits"].as_array().unwrap().len(), 120);+ assert!(c.iter().all(|x| x.1.starts_with("/connect/mcp")), "never the project API: {c:?}");+ composio_entry(&env).await;+ assert!(calls(&fake).is_empty(), "kept a minute");++ // The list: Composio's popular apps with connected, from the same minute.+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!((v["source"].clone(), v["mode"].clone(), v["can_connect"].clone(), v["count"].clone()), (json!("popular"), json!("connect"), json!(true), json!(120)));+ assert_eq!(v["apps"][0], json!({"slug": "gmail", "name": "Gmail", "rank": 0, "logo": v["apps"][0]["logo"], "connected": true}));+ assert!(calls(&fake).is_empty(), "from the tile's minute");+}++#[tokio::test]+async fn composio_connect_connects_and_checks_apps_through_manage_connections() {+ let (env, fake) = env_with_fake().await;+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ck_good"}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ calls(&fake);++ // Connect: MANAGE_CONNECTIONS add, and Composio's sign-in link.+ let (s, v) = call(&env.app, "POST", "/api/connections/composio/apps/slack/connect", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["redirect_url"], "https://connect.composio.dev/link/lk_slack");+ let c = calls(&fake);+ let call_ = c.iter().find(|x| x.1.starts_with("/connect/mcp tools/call")).unwrap();+ assert_eq!(call_.1, "/connect/mcp tools/call add");+ assert_eq!(call_.3, json!({"toolkits": [{"name": "slack", "action": "add"}]}));+ assert!(c.iter().all(|x| x.1 != "/connect/mcp tools/list"), "no tools/list, no search: {c:?}");++ // Status: MANAGE_CONNECTIONS list for the one app; never SEARCH_TOOLS.+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps/slack/status", None).await;+ assert_eq!((s, v), (StatusCode::OK, json!({"connected": false})));+ fake.lock().unwrap().active.insert("slack".into());+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps/slack/status", None).await;+ assert_eq!((s, v), (StatusCode::OK, json!({"connected": true})));+ let c = calls(&fake);+ let lists: Vec<&Value> = c.iter().filter(|x| x.1 == "/connect/mcp tools/call list").map(|x| &x.3).collect();+ assert_eq!(lists, vec![&json!({"toolkits": [{"name": "slack", "action": "list"}]}); 2]);++ // A search asks about its own apps only, in one call kept a minute.+ let (s, v) = call(&env.app, "GET", "/api/connections/composio/apps?q=sla", None).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["apps"][0]["slug"], "slack");+ assert_eq!(v["apps"][0]["connected"], true, "{v}");+ assert_eq!((v["source"].clone(), v["mode"].clone()), (json!("popular"), json!("connect")));+ let c = calls(&fake);+ let lists: Vec<&Value> = c.iter().filter(|x| x.1 == "/connect/mcp tools/call list").map(|x| &x.3).collect();+ assert_eq!(lists.len(), 1, "{c:?}");+ assert!(lists[0]["toolkits"].as_array().unwrap().len() <= 20);+ call(&env.app, "GET", "/api/connections/composio/apps?q=sla", None).await;+ assert!(calls(&fake).is_empty(), "the same search within the minute costs nothing");++ // Composio Connect down: a 502 that says to try again, and the setup stays.+ let (env2, fake2) = env_with_fake().await;+ let (s, v) = call(&env2.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ck_down"}))).await;+ assert_eq!((s, v["action"].clone()), (StatusCode::BAD_GATEWAY, json!("try_again")), "{v}");+ assert_eq!(servers(&env2).await, json!([]));+ assert!(calls(&fake2).iter().all(|c| c.2 == "ck_down"));+}++#[tokio::test]+async fn a_refused_composio_connect_key_saves_nothing() {+ let (env, fake) = env_with_fake().await;+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ck_wrong"}))).await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert_eq!((v["error"].clone(), v["action"].clone(), v["key_url"].clone()), (json!(REFUSED), json!("replace_key"), json!("https://dashboard.composio.dev")));+ assert!(!v.to_string().contains("ck_wrong"), "{v}");+ assert_eq!(connect_calls(&fake), vec![("/connect/mcp initialize".to_string(), "ck_wrong".to_string())], "a ck_ key is never sent to the project API");+ assert_eq!(servers(&env).await, json!([]), "nothing saved");+ let entry = composio_entry(&env).await;+ assert_eq!(entry["added"], false);++ // A good key then works at once.+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ck_good"}))).await;+ assert_eq!((s, v["mode"].clone()), (StatusCode::OK, json!("connect")), "{v}");+}++#[tokio::test]+async fn replacing_the_key_switches_between_project_and_composio_connect() {+ let (env, fake) = env_with_fake().await;+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(json!({"api_key": "ak_good", "enabled": true}))).await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let id = v["server"]["id"].clone();+ let user = v["user_id"].clone();+ calls(&fake);+ let put = |key: &'static str| {+ let app = env.app.clone();+ async move { call(&app, "PUT", "/api/connections/composio/key", Some(json!({"api_key": key}))).await }+ };++ // A refused ck_ changes nothing.+ let (s, v) = put("ck_wrong").await;+ assert_eq!((s, v["action"].clone()), (StatusCode::CONFLICT, json!("replace_key")), "{v}");+ assert_eq!(servers(&env).await[0]["url"], "https://backend.composio.dev/tool_router/trs_1/mcp");++ // ak_ → ck_: the same server, now Composio Connect, its switch as it was.+ let (s, v) = put("ck_good").await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!((v["mode"].clone(), v["user_id"].clone()), (json!("connect"), Value::Null), "{v}");+ assert_eq!(v["server"]["id"], id);+ assert_eq!(v["server"]["enabled"], true);+ assert_eq!(v["server"]["url"], "https://connect.composio.dev/mcp");+ assert!(!v.to_string().contains("ck_good"), "masked: {v}");+ let saved = env.state.db.list_mcp_servers(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();+ assert_eq!(+ saved[0].headers,+ std::collections::BTreeMap::from([("x-consumer-api-key".to_string(), "ck_good".to_string())]),+ "the project key is gone"+ );+ assert_eq!(composio_entry(&env).await["mode"], "connect");+ calls(&fake);+ let (s, v) = call(&env.app, "POST", "/api/connections/composio/apps/notion/connect", None).await;+ assert_eq!((s, v["redirect_url"].clone()), (StatusCode::OK, json!("https://connect.composio.dev/link/lk_notion")), "{v}");+ let (s, v) = call(&env.app, "POST", "/api/connections/composio/switch", None).await;+ assert_eq!((s, v["switched"].clone(), v["mode"].clone()), (StatusCode::OK, json!(false), json!("connect")), "{v}");++ // ck_ → ak_: a session for the space's own Composio user again.+ calls(&fake);+ let (s, v) = put("ak_other").await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!((v["mode"].clone(), v["user_id"].clone(), v["session_renewed"].clone()), (json!("session"), user.clone(), json!(true)), "{v}");+ assert_eq!(v["server"]["id"], id);+ assert_eq!(v["server"]["url"], "https://backend.composio.dev/tool_router/trs_2/mcp");+ let saved = env.state.db.list_mcp_servers(&kwnt::db::spaces::SpaceId::default_space()).await.unwrap();+ assert_eq!(saved[0].headers, std::collections::BTreeMap::from([("x-api-key".to_string(), "ak_other".to_string())]));+ let c = calls(&fake);+ assert_eq!(c.iter().map(|x| x.1.as_str()).collect::<Vec<_>>(), vec!["/api/v3.1/tool_router/session"], "{c:?}");+}diff --git a/tests/composio_search_test.rs b/tests/composio_search_test.rsindex 79f8abd1..a9761b5e 100644--- a/tests/composio_search_test.rs+++ b/tests/composio_search_test.rs@@ -131,14 +131,11 @@ async fn nothing_goes_to_composio_until_it_is_added_with_a_key() {None,).await;- assert_eq!(s, StatusCode::CONFLICT, "{v}");- assert!(- v["error"]- .as_str()- .unwrap()- .contains("Add the Composio connector first"),- "{v}"- );+ // Before Composio is added a search answers from Composio's popular apps, bundled with kwant.+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!((v["source"].clone(), v["mode"].clone(), v["can_connect"].clone()), (json!("popular"), Value::Null, json!(false)), "{v}");+ assert_eq!(v["apps"][0]["slug"], "gmail", "{v}");+ assert_eq!(v["apps"][0]["connected"], false, "{v}");let (s, _) = call(&env.app,"POST",@@ -166,7 +163,8 @@ async fn nothing_goes_to_composio_until_it_is_added_with_a_key() {).await;assert_eq!(s, StatusCode::CONFLICT, "{v}");- assert!(v["error"].as_str().unwrap().contains("x-api-key"), "{v}");+ assert!(v["error"].as_str().unwrap().contains("Add your Composio API key"), "{v}");+ assert_eq!(v["action"], "replace_key", "{v}");let (s, _) = call(&env.app,"POST",@@ -203,9 +201,13 @@ async fn search_and_connect_use_the_persons_key_and_user() {!list.to_string().contains("ck-secret-1"),"the key is never listed");- assert!(- seen.lock().unwrap().is_empty(),- "listing doesn't call Composio"+ // Listing asks Composio once which apps are connected, then keeps that for a minute.+ let (_, again) = call(&env.app, "GET", "/api/connections", None).await;+ assert_eq!(again["catalog"][0]["mode"], "url");+ assert_eq!(+ seen.lock().unwrap().drain(..).map(|c| c.1).collect::<Vec<_>>(),+ vec!["/api/v3.1/connected_accounts?limit=200&statuses=ACTIVE&user_ids=u-1".to_string()],+ "one call for two listings");// Bad queries and app names are refused before any call.@@ -250,6 +252,8 @@ async fn search_and_connect_use_the_persons_key_and_user() {assert_eq!(v["apps"][0]["slug"], "gmail");assert_eq!(v["apps"][0]["tools_count"], 23);assert_eq!(v["can_connect"], true);+ assert_eq!(v["apps"][0]["connected"], false, "the fake has no account for u-1 without a filter: {v}");+ assert_eq!(v["connected_checked"], true, "{v}");assert!(v["warning"].as_str().unwrap()@@ -270,7 +274,7 @@ async fn search_and_connect_use_the_persons_key_and_user() {.contains("Composio's servers"));let seen = seen.lock().unwrap().clone();- assert_eq!(seen.len(), 3, "{seen:?}");+ assert_eq!(seen.len(), 4, "{seen:?}");assert!(seen.iter().all(|(_, _, key, _)| key == "ck-secret-1"),"every call carries the person's key"@@ -280,11 +284,16 @@ async fn search_and_connect_use_the_persons_key_and_user() {"/api/v3.1/toolkits?limit=20&search=g mail&sort_by=usage");assert_eq!(- (seen[1].1.as_str(), &seen[1].3),- ("/api/v3.1/tool_router/session", &json!({"user_id": "u-1"}))+ seen[1].1,+ "/api/v3.1/connected_accounts?limit=200&statuses=ACTIVE&user_ids=u-1",+ "one account call for the whole page");assert_eq!((seen[2].1.as_str(), &seen[2].3),+ ("/api/v3.1/tool_router/session", &json!({"user_id": "u-1"}))+ );+ assert_eq!(+ (seen[3].1.as_str(), &seen[3].3),("/api/v3.1/tool_router/session/trs_1/link",&json!({"toolkit": "gmail"})@@ -313,7 +322,7 @@ async fn a_refused_key_or_missing_user_is_explained() {.await;assert_eq!(s, StatusCode::CONFLICT, "{v}");assert!(- v["error"].as_str().unwrap().contains("refused the API key"),+ v["error"].as_str().unwrap().contains("Composio didn't accept this key"),"{v}");assert!(@@ -329,7 +338,8 @@ async fn a_refused_key_or_missing_user_is_explained() {).await;assert_eq!(s, StatusCode::CONFLICT, "{v}");- assert!(v["error"].as_str().unwrap().contains("no user_id"), "{v}");+ assert!(v["error"].as_str().unwrap().contains("Switch to the one-key setup"), "{v}");+ assert_eq!(v["action"], "switch", "{v}");assert_eq!(seen.lock().unwrap().len(),1,@@ -409,11 +419,12 @@ async fn app_status_tells_whether_the_sign_in_finished() {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}");+ assert!(v["error"].as_str().unwrap().contains("Add Composio 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!(v["error"].as_str().unwrap().contains("Add your Composio API key"), "{v}");+ assert_eq!(v["action"], "replace_key", "{v}");assert!(seen.lock().unwrap().is_empty());}@@ -437,7 +448,8 @@ async fn app_status_asks_composio_for_this_user_and_app_only() {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}");+ assert!(v["error"].as_str().unwrap().contains("Composio couldn't be reached"), "{v}");+ assert_eq!(v["action"], "try_again", "{v}");let seen = seen.lock().unwrap().clone();assert_eq!(seen.len(), 4, "{seen:?}");@@ -454,7 +466,8 @@ async fn app_status_explains_a_refused_key_or_missing_user() {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!(v["error"].as_str().unwrap().contains("Switch to the one-key setup"), "{v}");+ assert_eq!(v["action"], "switch", "{v}");assert!(seen.lock().unwrap().is_empty());}