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
More MCP presets, and "Find an app" for the Composio connector
Linb6c085d37301
diff --git a/docs/connections.md b/docs/connections.mdindex 763a5898..72514f78 100644--- a/docs/connections.md+++ b/docs/connections.md@@ -148,12 +148,16 @@ empty again after a restart. Call the test route to refresh it ("Check now")."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"+ "add": "/api/connections/composio",+ "can_search": false,+ "can_connect": false,+ "search": "/api/connections/composio/apps"}```Show `warning` next to the add button and on the connection once it is added. Once added,-`connection_id` points at the MCP connection.+`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.## `POST /api/connections/composio?space=`@@ -181,6 +185,39 @@ Errors: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).++### `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`.++```json+{ "apps": [{ "slug": "gmail", "name": "Gmail", "description": "…", "logo": "https://…", "tools_count": 23, "no_auth": false }],+ "can_connect": true, "warning": "…" }+```++Apps without a plain slug are left out; `logo` is kept only when it is `https`.++### `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.++| 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 |+## Known limits- MCP `last_check` is kept in memory only (see the MCP status rules).diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex b30759ee..8d75386a 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -2908,7 +2908,20 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({{/* MCP tool servers (opened last so it sits above the bot form) */}<Suspense fallback={null}>- <McpServersModal isOpen={isMcpOpen} onClose={() => setIsMcpOpen(false)} kwants={kwants} />+ <McpServersModal+ isOpen={isMcpOpen}+ onClose={() => setIsMcpOpen(false)}+ kwants={kwants}+ onOpenConnections={() => {+ setIsMcpOpen(false);+ setShowConnections(true);+ setShowLoose(false);+ setShowParallel(false);+ setShowAway(false);+ setPhoneView('chat');+ playSfx('click');+ }}+ />{isSearchOpen && <SearchModal isOpen onClose={() => setIsSearchOpen(false)} kwants={kwants} onJump={handleJump} />}{isRoutinesOpen && <RoutinesModal isOpen onClose={() => setIsRoutinesOpen(false)} kwants={kwants} channels={channels} />}</Suspense>diff --git a/frontend/src/components/ConnectionsView.tsx b/frontend/src/components/ConnectionsView.tsxindex 0cc181fe..8fbd1baf 100644--- a/frontend/src/components/ConnectionsView.tsx+++ b/frontend/src/components/ConnectionsView.tsx@@ -1,10 +1,11 @@import React, { useCallback, useEffect, useId, useRef, useState } from 'react';-import { AlertTriangle, Bot, ChevronLeft, Github, KeyRound, Loader2, Lock, Mail, Plug, Plus, RefreshCw, Server, UserRound } from 'lucide-react';+import { AlertTriangle, Bot, ChevronLeft, ExternalLink, Github, KeyRound, Loader2, Lock, Mail, Plug, Plus, RefreshCw, Search, Server, UserRound } from 'lucide-react';import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';import { relativeTime } from '../away';import { UnlockDialog, usePasswordStore } from './PasswordStorePanel';import {CatalogEntry,+ ComposioApp,Connection,ConnectionsError,ConnectionsList,@@ -125,16 +126,150 @@ export const ConnectionRow: React.FC<ConnectionRowProps> = ({ c, now = Date.now();};+export interface ComposioSearchApi {+ search: (q: string) => Promise<{ apps: ComposioApp[]; can_connect: boolean }>;+ connect: (slug: string) => Promise<{ redirect_url: string }>;+}++const errorText = (e: unknown) => (e instanceof ConnectionsError || e instanceof Error ? e.message : 'Something went wrong.');++/** "Find an app": searches Composio's catalogue through kwnt, with the person's own Composio key. */+export const ComposioAppSearch: React.FC<{+ entry: CatalogEntry;+ api?: ComposioSearchApi;+ /** Tests show results without searching. */+ initialApps?: ComposioApp[];+}> = ({ entry, api = { search: connectionsApi.searchComposioApps, connect: connectionsApi.connectComposioApp }, initialApps }) => {+ const id = useId();+ const [q, setQ] = useState('');+ const [apps, setApps] = useState<ComposioApp[] | null>(initialApps ?? null);+ const [busy, setBusy] = useState(false);+ const [connecting, setConnecting] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [opened, setOpened] = useState<string | null>(null);+ const canConnect = entry.can_connect === true;++ if (!entry.can_search) {+ return (+ <p className="text-[11px] text-zinc-400" data-composio-search="needs-key">+ To find apps from here, add your Composio API key as the <code className="text-zinc-300">x-api-key</code> header of the Composio server in Tools.+ </p>+ );+ }++ const search = async (e: React.FormEvent) => {+ e.preventDefault();+ const query = q.trim();+ if (!query) return setError('Type an app name, like gmail.');+ setBusy(true);+ setError(null);+ setOpened(null);+ try {+ setApps((await api.search(query)).apps);+ } catch (err) {+ setError(errorText(err));+ } finally {+ setBusy(false);+ }+ };++ const connect = async (app: ComposioApp) => {+ // open the tab now, while the click still counts as the person's, then point it at Composio+ const tab = typeof window !== 'undefined' ? window.open('', '_blank') : null;+ if (tab) tab.opener = null;+ setConnecting(app.slug);+ setError(null);+ try {+ const { redirect_url } = await api.connect(app.slug);+ if (tab) tab.location.href = redirect_url;+ else window.open(redirect_url, '_blank', 'noopener,noreferrer');+ setOpened(app.name);+ } catch (err) {+ tab?.close();+ setError(errorText(err));+ } finally {+ setConnecting(null);+ }+ };++ return (+ <div className="space-y-2" data-composio-search>+ <form onSubmit={search} role="search" aria-label="Find an app on Composio" className="flex gap-2">+ <label htmlFor={`${id}-q`} className="sr-only">+ Find an app+ </label>+ <input+ id={`${id}-q`}+ className={field}+ type="search"+ autoComplete="off"+ spellCheck={false}+ maxLength={60}+ placeholder="Find an app, like gmail or figma"+ value={q}+ onChange={(e) => setQ(e.target.value)}+ />+ <button type="submit" disabled={busy} className={quietBtn}>+ {busy ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <Search size={12} aria-hidden="true" />}+ Find+ </button>+ </form>+ {!canConnect && (+ <p className="text-[11px] text-zinc-400">+ Your Composio URL has no <code className="text-zinc-300">user_id</code>, so connect apps on composio.dev. If your Composio server lists fixed apps, add the app to it there too.+ </p>+ )}+ <div role="status" aria-live="polite">+ {error && <p className="px-3 py-2 rounded-lg border border-rose-500/20 bg-rose-500/5 text-xs text-rose-300">{error}</p>}+ {opened && (+ <p className="text-xs text-emerald-200">+ Opened {opened}’s sign-in on Composio in a new tab. Its tools reach your bots through the Composio server once you finish there.+ </p>+ )}+ {apps && apps.length === 0 && <p className="text-xs text-zinc-400">No Composio apps match.</p>}+ </div>+ {apps && apps.length > 0 && (+ <ul className="divide-y divide-zinc-800 rounded-lg border border-zinc-800" aria-label="Composio apps">+ {apps.map((a) => (+ <li key={a.slug} className="flex flex-wrap items-center gap-2 px-3 py-2" data-composio-app={a.slug}>+ <div className="min-w-0 flex-1 basis-48">+ <p className="text-xs font-medium text-zinc-100">+ {a.name}+ <span className="ml-1.5 font-normal text-zinc-500">{a.slug}</span>+ </p>+ {a.description && <p className="text-[11px] text-zinc-400 line-clamp-2">{a.description}</p>}+ <p className="text-[11px] text-zinc-500">+ {a.tools_count != null && `${a.tools_count} tools · `}+ {a.no_auth ? 'No sign-in needed' : 'Sign-in kept on Composio'}+ </p>+ </div>+ {canConnect && !a.no_auth && (+ <button type="button" className={quietBtn} disabled={connecting !== null} onClick={() => connect(a)}>+ {connecting === a.slug ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <ExternalLink size={12} aria-hidden="true" />}+ Connect<span className="sr-only"> {a.name} on Composio (opens in a new tab)</span>+ </button>+ )}+ </li>+ ))}+ </ul>+ )}+ </div>+ );+};+export interface ComposioCardProps {entry: CatalogEntry;/** Tests open the form. */initialOpen?: boolean;onAdd: (url: string, apiKey: string, enabled: boolean) => Promise<string | null>;onOpenTools?: () => void;+ /** Tests: the search box's API and starting results. */+ searchApi?: ComposioSearchApi;+ initialApps?: ComposioApp[];}/** The optional Composio connector: what it is, where it keeps sign-ins, and the add form. */-export const ComposioCard: React.FC<ComposioCardProps> = ({ entry, initialOpen = false, onAdd, onOpenTools }) => {+export const ComposioCard: React.FC<ComposioCardProps> = ({ entry, initialOpen = false, onAdd, onOpenTools, searchApi, initialApps }) => {const id = useId();const [open, setOpen] = useState(initialOpen);const [url, setUrl] = useState('');@@ -187,6 +322,8 @@ export const ComposioCard: React.FC<ComposioCardProps> = ({ entry, initialOpen =<span>{entry.warning}</span></p>+ {entry.added && <ComposioAppSearch entry={entry} api={searchApi} initialApps={initialApps} />}+{open && !entry.added && (<form onSubmit={submit} className="space-y-3" aria-label={`Add ${entry.name}`} noValidate><div className="space-y-1">diff --git a/frontend/src/components/McpServersModal.tsx b/frontend/src/components/McpServersModal.tsxindex 200b6492..802a491e 100644--- a/frontend/src/components/McpServersModal.tsx+++ b/frontend/src/components/McpServersModal.tsx@@ -24,6 +24,7 @@ import {Users,Search,ExternalLink,+ AlertTriangle,} from 'lucide-react';import { playSfx } from '../audio/chiptune';import {@@ -35,6 +36,9 @@ import {SecretRow,StoredStatus,McpPreset,+ ComposioOnlyApp,+ searchComposioOnly,+ COMPOSIO_ONLY_APPS,MCP_PRESETS,searchPresets,groupPresets,@@ -59,6 +63,8 @@ interface McpServersModalProps {onClose: () => void;/** For "Off for: …" on each card. */kwants?: Array<{ id: string; name: string }>;+ /** Opens the Connections page, where Composio is added (for apps that go through it). */+ onOpenConnections?: () => void;}const inputCls =@@ -212,14 +218,50 @@ const ToolChips: React.FC<{ tools: Array<{ name: string; description?: string }>);};-const PresetCatalog: React.FC<{+/** A Composio-only app picked in the catalog: why it goes through Composio, and where to set it up. */+const ComposioOnlyNote: React.FC<{ app: ComposioOnlyApp; onOpenConnections?: () => void; onClose: () => void }> = ({ app, onOpenConnections, onClose }) => (+ <div role="status" className="space-y-2 p-3 rounded-xl border border-amber-500/30 bg-amber-500/5 text-xs text-zinc-300" data-composio-note={app.id}>+ <p>+ <span className="font-medium text-zinc-100">{app.label}</span> goes through Composio. {app.why} This app doesn’t offer unofficial servers for it.+ </p>+ <p className="flex items-start gap-1.5 text-amber-100">+ <AlertTriangle size={12} className="mt-px shrink-0 text-amber-300" aria-hidden="true" />+ <span>Composio keeps your {app.label} sign-in on Composio’s servers, not in this app’s vault.</span>+ </p>+ <p className="text-zinc-400">+ Add Composio under Connections, then use “Find an app” there and search for “{app.toolkit}”.+ </p>+ <div className="flex flex-wrap gap-2">+ {onOpenConnections && (+ <button type="button" onClick={onOpenConnections} className="px-2.5 py-1 rounded-lg bg-sky-500 text-zinc-950 hover:bg-sky-400 text-xs font-medium">+ Open Connections+ </button>+ )}+ <a href={app.source} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-0.5 text-sky-300 hover:text-sky-200 hover:underline underline-offset-2">+ {app.label} on Composio+ <ExternalLink size={10} aria-hidden="true" />+ <span className="sr-only">(opens in a new tab)</span>+ </a>+ <button type="button" onClick={onClose} className="text-zinc-400 hover:text-zinc-200">+ Close+ </button>+ </div>+ </div>+);++export const PresetCatalog: React.FC<{query: string;onQuery: (q: string) => void;onPick: (preset: McpPreset) => void;onCustom: () => void;+ onOpenConnections?: () => void;autoFocus?: boolean;-}> = ({ query, onQuery, onPick, onCustom, autoFocus }) => {- const groups = groupPresets(searchPresets(query));+ /** Tests open a Composio-only note. */+ initialComposioApp?: string;+}> = ({ query, onQuery, onPick, onCustom, onOpenConnections, autoFocus, initialComposioApp }) => {+ const [composioApp, setComposioApp] = useState<string | null>(initialComposioApp ?? null);+ const groups = groupPresets(searchPresets(query), searchComposioOnly(query));+ const total = MCP_PRESETS.length + COMPOSIO_ONLY_APPS.length;return (<div className="space-y-4 text-left"><div className="relative">@@ -230,7 +272,7 @@ const PresetCatalog: React.FC<{value={query}autoFocus={autoFocus}onChange={(e) => onQuery(e.target.value)}- placeholder={`Search ${MCP_PRESETS.length} servers, like notion or database`}+ placeholder={`Search ${total} apps and servers, like gmail or database`}className={`${inputCls} pl-8`}/></div>@@ -276,6 +318,28 @@ const PresetCatalog: React.FC<{</button></li>))}+ {g.composio.map((a) => (+ <li key={a.id} className={composioApp === a.id ? 'sm:col-span-2 space-y-2' : undefined}>+ <button+ type="button"+ onClick={() => setComposioApp(composioApp === a.id ? null : a.id)}+ aria-expanded={composioApp === a.id}+ className="group w-full h-full p-3 rounded-xl border border-zinc-800 bg-zinc-950/60 hover:border-sky-500/40 hover:bg-sky-500/5 focus-visible:border-sky-500/60 focus-visible:outline-none text-left transition-all"+ >+ <span className="flex items-center gap-1.5 text-xs font-medium text-zinc-200 group-hover:text-sky-200">+ <span className="text-sky-400" aria-hidden="true">+ <Plug size={13} />+ </span>+ {a.label}+ </span>+ <span className="mt-1 block text-[11px] text-zinc-500 leading-snug">{a.blurb}</span>+ <span className="mt-2 flex flex-wrap gap-1">+ <span className="px-1.5 py-px rounded border text-[10px] border-amber-500/25 text-amber-300/90">via Composio</span>+ </span>+ </button>+ {composioApp === a.id && <ComposioOnlyNote app={a} onOpenConnections={onOpenConnections} onClose={() => setComposioApp(null)} />}+ </li>+ ))}</ul></section>))}@@ -294,7 +358,7 @@ const PresetCatalog: React.FC<{);};-export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClose, kwants = [] }) => {+export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClose, kwants = [], onOpenConnections }) => {const [servers, setServers] = useState<McpServer[] | null>(null);const [loadError, setLoadError] = useState<string | null>(null);const [statuses, setStatuses] = useState<Record<string, StoredStatus>>({});@@ -591,7 +655,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClosconst preset = editing === 'new' && presetId ? MCP_PRESETS.find((p) => p.id === presetId) : undefined;const renderPicker = () => (- <PresetCatalog query={query} onQuery={setQuery} onPick={(p) => openForm('new', p)} onCustom={() => openForm('new')} autoFocus />+ <PresetCatalog query={query} onQuery={setQuery} onPick={(p) => openForm('new', p)} onCustom={() => openForm('new')} onOpenConnections={onOpenConnections} autoFocus />);const renderEmpty = () => (@@ -607,7 +671,7 @@ export const McpServersModal: React.FC<McpServersModalProps> = ({ isOpen, onClosPick a popular one below and just add your key or sign in.</p></div>- <PresetCatalog query={query} onQuery={setQuery} onPick={(p) => openForm('new', p)} onCustom={() => openForm('new')} />+ <PresetCatalog query={query} onQuery={setQuery} onPick={(p) => openForm('new', p)} onCustom={() => openForm('new')} onOpenConnections={onOpenConnections} /></div>);diff --git a/frontend/src/connections.ts b/frontend/src/connections.tsindex 3d7e9ce9..6b13a36e 100644--- a/frontend/src/connections.ts+++ b/frontend/src/connections.ts@@ -41,6 +41,21 @@ export interface CatalogEntry {logins_stored: string;warning: string;add: string;+ /** Composio only: kwant has the person's Composio API key, so "Find an app" works. */+ can_search?: boolean;+ /** Composio only: the Composio URL names a user, so kwant can start an app's sign-in. */+ can_connect?: boolean;+ search?: string;+}++/** One app from Composio's catalogue (Composio calls it a toolkit). */+export interface ComposioApp {+ slug: string;+ name: string;+ description: string;+ logo: string | null;+ tools_count: number | null;+ no_auth: boolean;}export interface VaultSummary {@@ -94,6 +109,12 @@ const enc = encodeURIComponent;export const connectionsApi = {list: () => call<ConnectionsList>('/api/connections'),addComposio: (body: ComposioBody) => call<{ connection_id: string; warning: string }>('/api/connections/composio', 'POST', body),+ /** Searches Composio's apps with the person's own Composio key (only once Composio is added). */+ searchComposioApps: (q: string) =>+ call<{ apps: ComposioApp[]; can_connect: boolean; warning: string }>(`/api/connections/composio/apps?q=${enc(q)}`),+ /** Starts signing in to one Composio app; the answer is the address to open. */+ connectComposioApp: (slug: string) =>+ call<{ redirect_url: string; warning: string }>(`/api/connections/composio/apps/${enc(slug)}/connect`, 'POST'),/** "Check now" for an MCP server: the server records the result as its last check. */testMcp: (serverId: string) => call<{ ok?: boolean; error?: string }>(`/api/mcp/servers/${enc(serverId)}/test`, 'POST'),};diff --git a/frontend/src/mcp.ts b/frontend/src/mcp.tsindex f09baac3..f456a187 100644--- a/frontend/src/mcp.ts+++ b/frontend/src/mcp.ts@@ -75,7 +75,7 @@ export const emptyMcpForm = (transport: McpTransport = 'stdio'): McpFormState =>timeout_secs: 30,});-export type McpPresetCategory = 'files' | 'web' | 'data' | 'productivity' | 'devtools';+export type McpPresetCategory = 'files' | 'web' | 'data' | 'productivity' | 'business' | 'creative' | 'devtools';/** Catalog groups, in display order. */export const MCP_PRESET_CATEGORIES: Array<{ id: McpPresetCategory; label: string }> = [@@ -83,7 +83,9 @@ export const MCP_PRESET_CATEGORIES: Array<{ id: McpPresetCategory; label: string{ id: 'web', label: 'Web' },{ id: 'data', label: 'Data' },{ id: 'productivity', label: 'Productivity' },- { id: 'devtools', label: 'Dev tools' },+ { id: 'business', label: 'Payments & customers' },+ { id: 'creative', label: 'Design & media' },+ { id: 'devtools', label: 'Dev tools & hosting' },];/** What a preset needs before it works, shown as small tags on its card. */@@ -280,22 +282,207 @@ export const MCP_PRESETS: McpPreset[] = [source: 'https://github.com/modelcontextprotocol/servers/tree/main/src/sequentialthinking',form: stdioPreset('sequential-thinking', 'npx -y @modelcontextprotocol/server-sequential-thinking'),},+ {+ // Cloudflare's hosted server: the whole Cloudflare API (Workers, DNS, R2, D1…) with sign-in.+ // Checked 2026-10-24: automatic client registration at mcp.cloudflare.com/register.+ id: 'cloudflare',+ label: 'Cloudflare',+ blurb: 'Workers, DNS, R2, D1 and the rest of your Cloudflare account. Sign in after adding.',+ category: 'devtools',+ needs: ['Sign-in'],+ source: 'https://developers.cloudflare.com/agents/model-context-protocol/mcp-servers-for-cloudflare/',+ form: httpPreset('cloudflare', 'https://mcp.cloudflare.com/mcp'),+ },+ {+ // Vercel's hosted server with sign-in. Checked 2026-10-24: registration at api.vercel.com.+ id: 'vercel',+ label: 'Vercel',+ blurb: 'Projects, deployments and build logs. Sign in after adding.',+ category: 'devtools',+ needs: ['Sign-in'],+ source: 'https://vercel.com/docs/mcp/vercel-mcp',+ form: httpPreset('vercel', 'https://mcp.vercel.com'),+ },+ {+ // Neon's hosted server with sign-in. Checked 2026-10-24: registration at mcp.neon.tech/api/register.+ id: 'neon',+ label: 'Neon Postgres',+ blurb: 'Neon projects, branches and SQL. Sign in after adding.',+ category: 'data',+ needs: ['Sign-in'],+ source: 'https://neon.com/docs/ai/neon-mcp-server',+ form: httpPreset('neon', 'https://mcp.neon.tech/mcp'),+ },+ {+ // Airtable's hosted server with sign-in. Checked 2026-10-24: registration at airtable.com/oauth2/v1/register.+ id: 'airtable',+ label: 'Airtable',+ blurb: 'Read and update bases, tables and records. Sign in after adding.',+ category: 'data',+ needs: ['Sign-in'],+ source: 'https://airtable.com/developers/agents/mcp/getting-started',+ form: httpPreset('airtable', 'https://mcp.airtable.com/mcp'),+ },+ {+ // PostHog's hosted server with sign-in. Checked 2026-10-24: registration at oauth.posthog.com.+ id: 'posthog',+ label: 'PostHog',+ blurb: 'Product analytics, feature flags and errors. Sign in after adding.',+ category: 'data',+ needs: ['Sign-in'],+ source: 'https://posthog.com/docs/model-context-protocol',+ form: httpPreset('posthog', 'https://mcp.posthog.com/mcp'),+ },+ {+ // monday.com's hosted server with sign-in. Checked 2026-10-24: registration at auth.monday.com.+ id: 'monday',+ label: 'monday.com',+ blurb: 'Boards, items and updates. Sign in after adding.',+ category: 'productivity',+ needs: ['Sign-in'],+ source: 'https://github.com/mondaycom/mcp',+ form: httpPreset('monday', 'https://mcp.monday.com/mcp'),+ },+ {+ // Zapier's hosted server with sign-in; the actions it offers are the ones chosen at mcp.zapier.com.+ // Checked 2026-10-24: registration at mcp.zapier.com/api/v1/oauth/register.+ id: 'zapier',+ label: 'Zapier',+ blurb: 'Thousands of apps through the Zapier actions you pick. Sign in after adding.',+ category: 'productivity',+ needs: ['Sign-in'],+ source: 'https://docs.zapier.com/mcp/get-started/connect/other',+ form: httpPreset('zapier', 'https://mcp.zapier.com/api/v1/connect'),+ },+ {+ // Stripe's hosted server with sign-in. Checked 2026-10-24: registration at access.stripe.com.+ id: 'stripe',+ label: 'Stripe',+ blurb: 'Customers, payments, invoices and Stripe docs. Sign in after adding.',+ category: 'business',+ needs: ['Sign-in'],+ source: 'https://docs.stripe.com/mcp',+ form: httpPreset('stripe', 'https://mcp.stripe.com'),+ },+ {+ // Intercom's hosted server with sign-in. Checked 2026-10-24: registration at mcp.intercom.com/register.+ id: 'intercom',+ label: 'Intercom',+ blurb: 'Search conversations and contacts. Sign in after adding.',+ category: 'business',+ needs: ['Sign-in'],+ source: 'https://developers.intercom.com/docs/guides/mcp',+ form: httpPreset('intercom', 'https://mcp.intercom.com/mcp'),+ },+ {+ // Picsart's hosted Gen AI server; it takes no API keys, only sign-in. Generations use Picsart credits.+ // Checked 2026-10-24: registration at auth.picsart.com/api/oauth2/register.+ id: 'picsart',+ label: 'Picsart',+ blurb: 'Generate and edit images and video, remove backgrounds. Sign in after adding.',+ category: 'creative',+ needs: ['Sign-in'],+ source: 'https://picsart.github.io/picsart-mcp-cli-docs/guide/mcp-quickstart',+ form: httpPreset('picsart', 'https://api.picsart.com/gen-ai/mcp'),+ },];+/**+ * Popular apps without a vendor MCP server kwnt can sign in to on its own, offered through the+ * optional Composio connector instead of an unofficial third-party server. Checked 2026-10-24:+ * Google's Gmail server is a Developer Preview that needs your own Google Cloud OAuth client;+ * Slack's server needs a registered Slack app; Figma's only accepts clients on its own list.+ */+export interface ComposioOnlyApp {+ id: string;+ label: string;+ blurb: string;+ category: McpPresetCategory;+ /** The app's Composio toolkit slug, for "Find an app" on Connections. */+ toolkit: string;+ /** Why there's no direct preset, in one sentence. */+ why: string;+ /** Composio's page for the toolkit. */+ source: string;+}++export const COMPOSIO_ONLY_APPS: ComposioOnlyApp[] = [+ {+ id: 'gmail',+ label: 'Gmail',+ blurb: 'Read, search, draft and send email.',+ category: 'productivity',+ toolkit: 'gmail',+ why: 'Google’s own Gmail server is a preview that needs your own Google Cloud sign-in app.',+ source: 'https://docs.composio.dev/toolkits/gmail',+ },+ {+ id: 'google-calendar',+ label: 'Google Calendar',+ blurb: 'See, create and move events.',+ category: 'productivity',+ toolkit: 'googlecalendar',+ why: 'Google has no Calendar server that apps can sign in to on their own.',+ source: 'https://docs.composio.dev/toolkits/googlecalendar',+ },+ {+ id: 'google-drive',+ label: 'Google Drive',+ blurb: 'Find, read and upload files.',+ category: 'productivity',+ toolkit: 'googledrive',+ why: 'Google has no Drive server that apps can sign in to on their own.',+ source: 'https://docs.composio.dev/toolkits/googledrive',+ },+ {+ id: 'slack',+ label: 'Slack',+ blurb: 'Read channels and send messages.',+ category: 'productivity',+ toolkit: 'slack',+ why: 'Slack’s own server only works with a Slack app you register first.',+ source: 'https://docs.composio.dev/toolkits/slack',+ },+ {+ id: 'figma',+ label: 'Figma',+ blurb: 'Read files, frames and comments.',+ category: 'creative',+ toolkit: 'figma',+ why: 'Figma’s own server only accepts the apps on Figma’s list.',+ source: 'https://docs.composio.dev/toolkits/figma',+ },+];++const presetText = (p: { id: string; label: string; blurb: string; category: McpPresetCategory }, extra: string[]) => {+ const label = MCP_PRESET_CATEGORIES.find((x) => x.id === p.category)?.label ?? p.category;+ return [p.id, p.label, p.blurb, label, ...extra].join(' ').toLowerCase();+};++const matches = (query: string) => {+ const words = query.toLowerCase().split(/\s+/).filter(Boolean);+ return (text: string) => words.every((w) => text.includes(w));+};+/** Presets matching a search, by name, blurb, group or what they need. A blank query keeps all. */export const searchPresets = (query: string, presets: McpPreset[] = MCP_PRESETS): McpPreset[] => {- const words = query.toLowerCase().split(/\s+/).filter(Boolean);- if (words.length === 0) return presets;- const label = (c: McpPresetCategory) => MCP_PRESET_CATEGORIES.find((x) => x.id === c)?.label ?? c;- return presets.filter((p) => {- const text = [p.id, p.label, p.blurb, label(p.category), ...p.needs].join(' ').toLowerCase();- return words.every((w) => text.includes(w));- });+ const hit = matches(query);+ return presets.filter((p) => hit(presetText(p, p.needs)));+};++/** Composio-only apps matching a search, the same way. A blank query keeps all. */+export const searchComposioOnly = (query: string, apps: ComposioOnlyApp[] = COMPOSIO_ONLY_APPS): ComposioOnlyApp[] => {+ const hit = matches(query);+ return apps.filter((a) => hit(presetText(a, ['composio', a.toolkit])));};/** Presets grouped for display, in category order, leaving out empty groups. */-export const groupPresets = (presets: McpPreset[]) =>- MCP_PRESET_CATEGORIES.map((c) => ({ ...c, presets: presets.filter((p) => p.category === c.id) })).filter((g) => g.presets.length > 0);+export const groupPresets = (presets: McpPreset[], composio: ComposioOnlyApp[] = []) =>+ MCP_PRESET_CATEGORIES.map((c) => ({+ ...c,+ presets: presets.filter((p) => p.category === c.id),+ composio: composio.filter((a) => a.category === c.id),+ })).filter((g) => g.presets.length + g.composio.length > 0);/** Splits a command line into words, honouring '…' and "…" quotes and backslash escapes. */export const splitCommandLine = (line: string): string[] => {diff --git a/frontend/tests/connections.test.mjs b/frontend/tests/connections.test.mjsindex a671c3bd..8344c11a 100644--- a/frontend/tests/connections.test.mjs+++ b/frontend/tests/connections.test.mjs@@ -144,3 +144,65 @@ test('empty groups say so instead of leaving a gap', () => {for (const t of ['No tool servers yet.', 'No engine accounts yet.', 'No saved website logins.', 'No mail or GitHub sources.']) assert.ok(html.includes(t));assert.ok(!html.includes('Optional connectors'));});++const apps = [+ { slug: 'gmail', name: 'Gmail', description: 'Read and send mail.', logo: null, tools_count: 23, no_auth: false },+ { slug: 'hackernews', name: 'Hacker News', description: '', logo: null, tools_count: 4, no_auth: true },+];++test('"Find an app" shows only once Composio is added, and the warning stays', () => {+ const notAdded = ui.composio({ entry: composioEntry({ can_search: true }), onAdd: async () => null });+ assert.ok(!notAdded.includes('data-composio-search'), 'no search before Composio is added');+ const noKey = ui.composio({ entry: composioEntry({ added: true, can_search: false }), onAdd: async () => null });+ assert.ok(noKey.includes('data-composio-search="needs-key"') && noKey.includes('x-api-key'));+ const ready = ui.composio({ entry: composioEntry({ added: true, can_search: true, can_connect: true }), onAdd: async () => null });+ assert.ok(ready.includes('Find an app') && ready.includes('role="search"'));+ for (const html of [noKey, ready]) assert.ok(html.includes('Composio keeps your app sign-ins'), 'the warning stays');+});++test('found apps offer Connect when the Composio URL names a user, else point to composio.dev', () => {+ const entry = composioEntry({ added: true, can_search: true, can_connect: true });+ const html = ui.composio({ entry, onAdd: async () => null, initialApps: apps });+ assert.ok(html.includes('data-composio-app="gmail"') && html.includes('23 tools'));+ assert.equal((html.match(/>Connect</g) ?? []).length, 1, 'only apps that need a sign-in get Connect');+ assert.ok(html.includes('No sign-in needed'));+ const noUser = ui.composio({ entry: { ...entry, can_connect: false }, onAdd: async () => null, initialApps: apps });+ assert.ok(!noUser.includes('>Connect<') && noUser.includes('connect apps on composio.dev'));+});++test('the search and connect calls go to kwnt, never straight to Composio', async () => {+ const prev = globalThis.fetch;+ const seen = [];+ globalThis.fetch = async (url, init = {}) => {+ seen.push([String(url), init.method]);+ return new Response(JSON.stringify(String(url).endsWith('/connect') ? { redirect_url: 'https://connect.composio.dev/x', warning: WARNING } : { apps, can_connect: true, warning: WARNING }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' },+ });+ };+ try {+ assert.equal((await m.connectionsApi.searchComposioApps('g mail&x')).apps.length, 2);+ assert.equal((await m.connectionsApi.connectComposioApp('gmail')).redirect_url, 'https://connect.composio.dev/x');+ } finally {+ globalThis.fetch = prev;+ }+ assert.deepEqual(seen, [+ ['/api/connections/composio/apps?q=g%20mail%26x', 'GET'],+ ['/api/connections/composio/apps/gmail/connect', 'POST'],+ ]);+});++test('the server catalog lists Gmail as "via Composio" and explains why, with the warning', async () => {+ const cat = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { PresetCatalog } from './src/components/McpServersModal';+ export const render = (props) => renderToStaticMarkup(React.createElement(PresetCatalog, props));+ `);+ const base = { query: 'gmail', onQuery: noop, onPick: noop, onCustom: noop, onOpenConnections: noop };+ const list = cat.render(base);+ assert.ok(list.includes('Gmail') && list.includes('via Composio'));+ const open = cat.render({ ...base, initialComposioApp: 'gmail' });+ assert.ok(open.includes('data-composio-note="gmail"') && open.includes('Open Connections'));+ assert.ok(open.includes('not in this app’s vault'));+});diff --git a/frontend/tests/mcp.test.mjs b/frontend/tests/mcp.test.mjsindex 643a9dae..57430ae8 100644--- a/frontend/tests/mcp.test.mjs+++ b/frontend/tests/mcp.test.mjs@@ -13,6 +13,8 @@ const {MCP_PRESET_CATEGORIES,searchPresets,groupPresets,+ COMPOSIO_ONLY_APPS,+ searchComposioOnly,SECRET_MASK,emptyMcpForm,formToPayload,@@ -176,6 +178,40 @@ test('groups presets in category order and drops empty groups', () => {assert.equal(groups.reduce((n, g) => n + g.presets.length, 0), MCP_PRESETS.length);assert.deepEqual(groupPresets(searchPresets('notion')).map((g) => g.id), ['productivity']);assert.deepEqual(groupPresets([]), []);+ assert.ok(groups.every((g) => Array.isArray(g.composio) && g.composio.length === 0));+});++test('apps without a usable official server point to Composio instead of an invented preset', () => {+ const presetIds = new Set(MCP_PRESETS.map((p) => p.id));+ const ids = COMPOSIO_ONLY_APPS.map((a) => a.id);+ assert.equal(new Set(ids).size, ids.length);+ for (const a of COMPOSIO_ONLY_APPS) {+ assert.ok(!presetIds.has(a.id), `${a.id} is both a preset and Composio-only`);+ assert.match(a.toolkit, /^[a-z0-9_-]+$/, a.id);+ assert.match(a.source, /^https:\/\/docs\.composio\.dev\/toolkits\//, a.id);+ assert.ok(a.why.length > 10 && a.blurb.length <= 100, a.id);+ assert.ok(MCP_PRESET_CATEGORIES.some((c) => c.id === a.category), a.id);+ }+ assert.ok(ids.includes('gmail'));+});++test('the asked-for apps are offered: Cloudflare and Picsart as presets, Gmail via Composio', () => {+ for (const id of ['cloudflare', 'picsart']) {+ const p = MCP_PRESETS.find((x) => x.id === id);+ assert.ok(p && p.needs.includes('Sign-in') && p.form.transport === 'http', id);+ assert.match(p.source, /^https:\/\//, id);+ }+ assert.deepEqual(searchComposioOnly('gmail').map((a) => a.id), ['gmail']);+ assert.deepEqual(searchPresets('gmail'), []);+});++test('search finds Composio-only apps, and groups put them with their category', () => {+ assert.deepEqual(searchComposioOnly('').length, COMPOSIO_ONLY_APPS.length);+ assert.ok(searchComposioOnly('composio').length === COMPOSIO_ONLY_APPS.length);+ assert.deepEqual(searchComposioOnly('googledrive').map((a) => a.id), ['google-drive']);+ assert.deepEqual(searchComposioOnly('zzz-nothing'), []);+ const groups = groupPresets(searchPresets('figma'), searchComposioOnly('figma'));+ assert.deepEqual(groups.map((g) => [g.id, g.composio.map((a) => a.id)]), [['creative', ['figma']]]);});test('reads MCP tool names and recorded tool calls', () => {diff --git a/src/mcp/composio.rs b/src/mcp/composio.rsnew file mode 100644index 00000000..4f7bef61--- /dev/null+++ b/src/mcp/composio.rs@@ -0,0 +1,302 @@+//! Composio's app catalogue (API v3.1): search its toolkits and start a sign-in for one, with the+//! person's own Composio API key. kwnt only calls this once the person has added Composio as a+//! connector, and only from person-only routes (`server::connections`).+//!+//! Sources: <https://docs.composio.dev/reference/api-reference/toolkits/getToolkits>,+//! <https://docs.composio.dev/reference/api-reference/tool-router/postToolRouterSession> and+//! <https://docs.composio.dev/reference/api-reference/tool-router/postToolRouterSessionBySessionIdLink>.++use serde::Serialize;+use serde_json::{json, Value};+use std::time::Duration;++pub const DEFAULT_API_URL: &str = "https://backend.composio.dev";+/// Points kwnt at another Composio API address (tests).+pub const API_URL_ENV: &str = "KWNT_COMPOSIO_API_URL";+const TIMEOUT: Duration = Duration::from_secs(10);+/// Largest Composio answer kwnt reads.+const MAX_BODY: usize = 2 * 1024 * 1024;+pub const MAX_QUERY_CHARS: usize = 60;+/// How many apps one search returns.+const PAGE: usize = 20;++/// One app (Composio calls it a toolkit), as kwnt shows it.+#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct ComposioApp {+ pub slug: String,+ pub name: String,+ pub description: String,+ /// An https logo address, or none.+ pub logo: Option<String>,+ pub tools_count: Option<u64>,+ /// The app works without signing in to it.+ pub no_auth: bool,+}++/// Why a Composio call failed, in words for the person.+#[derive(Debug, Clone, PartialEq)]+pub enum ComposioError {+ /// Composio refused the API key (401/403).+ KeyRefused,+ /// Composio answered with an error; carries a short message.+ Upstream(u16, String),+ Unreachable,+}++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::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(),+ }+ }+}++pub struct ComposioApi {+ base_url: String,+ client: reqwest::Client,+}++/// Whether `slug` looks like a Composio toolkit slug (`gmail`, `google_drive`, `x-twitter`).+pub fn valid_slug(slug: &str) -> bool {+ !slug.is_empty()+ && slug.len() <= 64+ && slug+ .chars()+ .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')+}++/// The Composio user an MCP URL acts for: its `user_id` query value.+pub fn user_id_of(mcp_url: &str) -> Option<String> {+ let url = url::Url::parse(mcp_url).ok()?;+ let id = url+ .query_pairs()+ .find(|(k, _)| k == "user_id")+ .map(|(_, v)| v.trim().to_string())?;+ (!id.is_empty() && id.len() <= 256).then_some(id)+}++fn https_or_none(v: &Value) -> Option<String> {+ v.as_str()+ .filter(|s| s.starts_with("https://") && s.len() <= 2048)+ .map(str::to_string)+}++fn clip(text: &str, max: usize) -> String {+ match text.char_indices().nth(max) {+ Some((i, _)) => format!("{}…", &text[..i]),+ None => text.to_string(),+ }+}++/// Apps from a `GET /api/v3.1/toolkits` answer; entries without a usable slug are left out.+pub fn parse_apps(body: &Value) -> Vec<ComposioApp> {+ body["items"]+ .as_array()+ .map(|items| {+ items+ .iter()+ .filter_map(|t| {+ let slug = t["slug"].as_str().filter(|s| valid_slug(s))?.to_string();+ let name = t["name"]+ .as_str()+ .map(|n| clip(n, 80))+ .unwrap_or_else(|| slug.clone());+ Some(ComposioApp {+ description: clip(+ t["meta"]["description"].as_str().unwrap_or_default(),+ 240,+ ),+ logo: https_or_none(&t["meta"]["logo"]),+ tools_count: t["meta"]["tools_count"].as_u64(),+ no_auth: t["no_auth"] == json!(true),+ slug,+ name,+ })+ })+ .collect()+ })+ .unwrap_or_default()+}++impl ComposioApi {+ pub fn new(base_url: &str) -> Self {+ Self {+ base_url: base_url.trim_end_matches('/').to_string(),+ client: reqwest::Client::builder()+ .timeout(TIMEOUT)+ // the key goes in a header: never follow a redirect to another host with it+ .redirect(reqwest::redirect::Policy::none())+ .user_agent(concat!("kwnt/", env!("CARGO_PKG_VERSION")))+ .build()+ .unwrap_or_default(),+ }+ }++ /// [`API_URL_ENV`], else Composio's own API.+ 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))+ }++ fn url(&self, segments: &[&str]) -> Result<reqwest::Url, ComposioError> {+ let mut url =+ reqwest::Url::parse(&self.base_url).map_err(|_| ComposioError::Unreachable)?;+ url.path_segments_mut()+ .map_err(|_| ComposioError::Unreachable)?+ .pop_if_empty()+ .extend(segments);+ Ok(url)+ }++ async fn send(+ &self,+ req: reqwest::RequestBuilder,+ api_key: &str,+ ) -> Result<Value, ComposioError> {+ let res = req+ .header("x-api-key", api_key)+ .send()+ .await+ .map_err(|_| ComposioError::Unreachable)?;+ let status = res.status();+ if res.content_length().is_some_and(|n| n as usize > MAX_BODY) {+ return Err(ComposioError::Upstream(+ status.as_u16(),+ "the answer was too large".into(),+ ));+ }+ let body = res.bytes().await.map_err(|_| ComposioError::Unreachable)?;+ if body.len() > MAX_BODY {+ return Err(ComposioError::Upstream(+ status.as_u16(),+ "the answer was too large".into(),+ ));+ }+ let value: Value = serde_json::from_slice(&body).unwrap_or(Value::Null);+ if status == reqwest::StatusCode::UNAUTHORIZED || status == reqwest::StatusCode::FORBIDDEN {+ return Err(ComposioError::KeyRefused);+ }+ if !status.is_success() {+ let message = value["error"]["message"]+ .as_str()+ .or_else(|| value["message"].as_str())+ .unwrap_or_default();+ return Err(ComposioError::Upstream(status.as_u16(), clip(message, 200)));+ }+ Ok(value)+ }++ /// Apps whose name, slug or description match `query`.+ pub async fn search(+ &self,+ api_key: &str,+ query: &str,+ ) -> Result<Vec<ComposioApp>, ComposioError> {+ let mut url = self.url(&["api", "v3.1", "toolkits"])?;+ url.query_pairs_mut()+ .append_pair("search", query)+ .append_pair("sort_by", "usage")+ .append_pair("limit", &PAGE.to_string());+ let body = self.send(self.client.get(url), api_key).await?;+ Ok(parse_apps(&body))+ }++ /// 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.+ pub async fn connect_link(+ &self,+ api_key: &str,+ user_id: &str,+ slug: &str,+ ) -> Result<String, ComposioError> {+ let session = self+ .send(+ self.client+ .post(self.url(&["api", "v3.1", "tool_router", "session"])?)+ .json(&json!({"user_id": user_id})),+ api_key,+ )+ .await?;+ let session_id = session["session_id"]+ .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())+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn slugs_are_plain_lowercase_words() {+ assert!(valid_slug("gmail") && valid_slug("google_drive") && valid_slug("x-twitter"));+ for bad in ["", "Gmail", "../x", "a/b", "a b", "a?b", &"a".repeat(65)] {+ assert!(!valid_slug(bad), "{bad}");+ }+ }++ #[test]+ fn user_id_comes_from_the_mcp_url() {+ assert_eq!(+ user_id_of("https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-1").as_deref(),+ Some("u-1")+ );+ assert_eq!(+ user_id_of("https://backend.composio.dev/v3/mcp/abc/mcp?user_id=me%40x.dev&a=1")+ .as_deref(),+ Some("[email protected]")+ );+ assert_eq!(+ user_id_of("https://backend.composio.dev/v3/mcp/abc/mcp"),+ None+ );+ assert_eq!(+ user_id_of("https://backend.composio.dev/v3/mcp/abc/mcp?user_id="),+ None+ );+ }++ #[test]+ fn apps_keep_only_safe_fields() {+ let body = json!({"items": [+ {"slug": "gmail", "name": "Gmail", "no_auth": false,+ "meta": {"description": "Mail", "logo": "https://logos.composio.dev/gmail.png", "tools_count": 23}},+ {"slug": "hack", "name": "Hack", "meta": {"logo": "javascript:alert(1)"}},+ {"slug": "../etc", "name": "Bad"},+ {"name": "No slug"}+ ]});+ let apps = parse_apps(&body);+ assert_eq!(apps.len(), 2);+ assert_eq!(+ apps[0].logo.as_deref(),+ Some("https://logos.composio.dev/gmail.png")+ );+ assert_eq!(apps[0].tools_count, Some(23));+ assert_eq!(apps[1].logo, None, "only https logos");+ assert!(parse_apps(&Value::Null).is_empty());+ }+}diff --git a/src/mcp/mod.rs b/src/mcp/mod.rsindex 18d907ea..c4f1e3e6 100644--- a/src/mcp/mod.rs+++ b/src/mcp/mod.rs@@ -4,6 +4,7 @@pub mod builtin_tools;pub mod cli_config;pub mod client;+pub mod composio;pub mod echo_server;pub mod fetch_risk;pub mod oauth;diff --git a/src/server/connections.rs b/src/server/connections.rsindex 75f07718..1bba023f 100644--- a/src/server/connections.rs+++ b/src/server/connections.rs@@ -12,7 +12,7 @@ use super::spaces::Scope;use super::AppState;use crate::db::models::{Kwant, McpServer};use crate::db::spaces::SpaceId;-use crate::mcp::{self, McpServerInput};+use crate::mcp::{self, composio, McpServerInput};use crate::profiles::Engine;use crate::sandbox::credentials::{CredentialStore, StoreError};use axum::{@@ -329,6 +329,16 @@ 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 composio_key(server: &McpServer) -> Option<&str> {+ server+ .headers+ .iter()+ .find(|(k, _)| k.eq_ignore_ascii_case("x-api-key"))+ .map(|(_, v)| v.trim())+ .filter(|v| !v.is_empty())+}+/// The optional connectors kwnt offers, with whether each is added.fn catalog(servers: &[McpServer]) -> Value {let added = servers.iter().find(|s| is_composio(s));@@ -344,6 +354,10 @@ 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()),+ "search": "/api/connections/composio/apps",}])}@@ -452,6 +466,95 @@ 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.+#[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"));+ };+ 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"));+ };+ Ok((server, key))+}++fn composio_failed(e: composio::ComposioError) -> Response {+ let status = match e {+ composio::ComposioError::KeyRefused => StatusCode::CONFLICT,+ _ => StatusCode::BAD_GATEWAY,+ };+ error(status, &e.message())+}++#[derive(Debug, Deserialize)]+pub struct AppSearch {+ #[serde(default)]+ pub q: String,+}++/// `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.+pub async fn search_composio_apps(+ State(state): State<AppState>,+ headers: HeaderMap,+ Scope(space): Scope,+ axum::extract::Query(query): axum::extract::Query<AppSearch>,+) -> Response {+ 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 {+ return error(StatusCode::BAD_REQUEST, "type an app name, up to 60 characters");+ }+ let (server, 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),+ }+}++/// `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.+pub async fn connect_composio_app(+ State(state): State<AppState>,+ headers: HeaderMap,+ Scope(space): Scope,+ axum::extract::Path(slug): axum::extract::Path<String>,+) -> Response {+ if let Err(r) = refuse_agent_tokens(&state, &headers, REFUSAL).await {+ return r;+ }+ if !composio::valid_slug(&slug) {+ return error(StatusCode::BAD_REQUEST, "not a Composio app name");+ }+ let (server, key) = match composio_with_key(&state, &space).await {+ Ok(found) => found,+ Err(r) => return r,+ };+ let Some(user_id) = server.url.as_deref().and_then(composio::user_id_of) else {+ return error(+ StatusCode::CONFLICT,+ "Your Composio URL has no user_id, so kwant can't tell which Composio user to connect the app to. Connect it on composio.dev instead",+ );+ };+ match state.composio_api.connect_link(&key, &user_id, &slug).await {+ Ok(redirect_url) => Json(json!({"redirect_url": redirect_url, "warning": COMPOSIO_WARNING})).into_response(),+ Err(e) => composio_failed(e),+ }+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/server/mod.rs b/src/server/mod.rsindex 58a48ddc..8a321fc2 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -87,6 +87,8 @@ pub struct AppState {pub claude_login: Arc<engine_login::ClaudeLogin>,/// The MCP Registry agents search and suggest servers from (`KWNT_MCP_REGISTRY_URL`).pub mcp_registry: Arc<crate::mcp::registry::McpRegistry>,+ /// Composio's app catalogue (`KWNT_COMPOSIO_API_URL`), called only once Composio is added.+ pub composio_api: Arc<crate::mcp::composio::ComposioApi>,/// Saved website passwords, outside every bot's folder (see `sandbox::credentials`).pub credentials: Arc<crate::sandbox::vault::PasswordVault>,/// Zombie Mission Hunter: one scan at a time, and the last scan's report.@@ -135,6 +137,7 @@ impl AppState {human_steps: Default::default(),claude_login: Default::default(),mcp_registry: Arc::new(crate::mcp::registry::McpRegistry::from_env()),+ composio_api: Arc::new(crate::mcp::composio::ComposioApi::from_env()),credentials: Arc::new(crate::sandbox::vault::PasswordVault::open(&config_data_dir)),zombie: Default::default(),parallel: Default::default(),@@ -256,6 +259,8 @@ pub fn create_router(state: AppState) -> Router {.route("/api/parallel/runs/:id", get(parallel_routes::get_run)).route("/api/connections", get(connections::list)).route("/api/connections/composio", post(connections::add_composio))+ .route("/api/connections/composio/apps", get(connections::search_composio_apps))+ .route("/api/connections/composio/apps/:slug/connect", post(connections::connect_composio_app)).route("/api/mcp/servers", get(mcp_routes::list_servers).post(mcp_routes::create_server)).route("/api/mcp/servers/:id",diff --git a/tests/common/mod.rs b/tests/common/mod.rsindex 6724d892..1758ad8c 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -162,6 +162,12 @@ pub struct Env {/// A server listening on a loopback port (the CLI reaches its tools there).pub async fn setup() -> Env {+ setup_with(|_| {}).await+}++/// [`setup`], with a chance to change the state (say, point it at a fake service) before the+/// router is built.+pub async fn setup_with(change: impl FnOnce(&mut AppState)) -> Env {prompts_dir();let tmp = tempfile::tempdir().unwrap();let data = tmp.path().join("data");@@ -176,13 +182,14 @@ pub async fn setup() -> Env {browser_cdp_url: Some("http://127.0.0.1:9".into()),..Config::default()};- let state = AppState::new(+ let mut state = AppState::new(config.clone(),db,ToolRunner::new(data.join("workspace")),PermissionBroker::new(),LayaRouter::new(config.laya_url.clone()),);+ change(&mut state);let app = create_router(state.clone());let served = app.clone().into_make_service_with_connect_info::<std::net::SocketAddr>();tokio::spawn(async move {diff --git a/tests/composio_search_test.rs b/tests/composio_search_test.rsnew file mode 100644index 00000000..6cea084a--- /dev/null+++ b/tests/composio_search_test.rs@@ -0,0 +1,381 @@+//! "Find an app" on the Composio connector: kwnt searches Composio's catalogue and starts an app's+//! sign-in with the person's own Composio key, through person-only routes. Before Composio is+//! added, or without a key, kwnt never sends Composio a request: a fake Composio API counts them.++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::HashMap;+use std::sync::{Arc, Mutex};++/// Every request the fake Composio API got: method, path with query, x-api-key, JSON body.+type Seen = Arc<Mutex<Vec<(String, String, String, Value)>>>;++fn key_of(h: &HeaderMap) -> String {+ h.get("x-api-key")+ .and_then(|v| v.to_str().ok())+ .unwrap_or_default()+ .to_string()+}++async fn fake_composio() -> (String, Seen) {+ let seen: Seen = Arc::default();+ let app = Router::new()+ .route(+ "/api/v3.1/toolkits",+ get(|State(seen): State<Seen>, h: HeaderMap, Query(q): Query<HashMap<String, String>>| async move {+ let mut pairs: Vec<_> = q.iter().map(|(k, v)| format!("{k}={v}")).collect();+ pairs.sort();+ seen.lock().unwrap().push(("GET".into(), format!("/api/v3.1/toolkits?{}", pairs.join("&")), key_of(&h), Value::Null));+ if key_of(&h) == "ck-wrong" {+ return (StatusCode::UNAUTHORIZED, Json(json!({"error": {"message": "bad key"}})));+ }+ (+ StatusCode::OK,+ Json(json!({"items": [+ {"slug": "gmail", "name": "Gmail", "no_auth": false,+ "meta": {"description": "Mail from Google", "logo": "https://logos.composio.dev/gmail.png", "tools_count": 23}},+ {"slug": "../evil", "name": "Evil"}+ ], "next_cursor": null})),+ )+ }),+ )+ .route(+ "/api/v3.1/tool_router/session",+ post(|State(seen): State<Seen>, h: HeaderMap, Json(body): Json<Value>| async move {+ seen.lock().unwrap().push(("POST".into(), "/api/v3.1/tool_router/session".into(), key_of(&h), body));+ (StatusCode::CREATED, Json(json!({"session_id": "trs_1", "mcp": {"type": "http", "url": "https://x"}})))+ }),+ )+ .route(+ "/api/v3.1/tool_router/session/:id/link",+ post(|State(seen): State<Seen>, Path(id): Path<String>, h: HeaderMap, Json(body): Json<Value>| async move {+ seen.lock().unwrap().push(("POST".into(), format!("/api/v3.1/tool_router/session/{id}/link"), key_of(&h), body));+ (StatusCode::CREATED, Json(json!({"redirect_url": "https://connect.composio.dev/link/ln_1", "link_token": "ln_1"})))+ }),+ )+ .with_state(seen.clone());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ tokio::spawn(async move {+ let _ = axum::serve(listener, app).await;+ });+ (url, seen)+}++async fn env_with_fake() -> (Env, Seen) {+ let (url, seen) = fake_composio().await;+ let env = setup_with(|state| state.composio_api = Arc::new(ComposioApi::new(&url))).await;+ (env, seen)+}++async fn add_composio(env: &Env, url: &str, key: Option<&str>) {+ let mut body = json!({"url": url});+ if let Some(k) = key {+ body["api_key"] = json!(k);+ }+ let (s, v) = call(&env.app, "POST", "/api/connections/composio", Some(body)).await;+ assert_eq!(s, StatusCode::OK, "{v}");+}++#[tokio::test]+async fn nothing_goes_to_composio_until_it_is_added_with_a_key() {+ let (env, seen) = env_with_fake().await;++ // Not added: the page loads, other servers are added, and finding or connecting an app is refused.+ let (s, list) = call(&env.app, "GET", "/api/connections", None).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(list["catalog"][0]["can_search"], false);+ let (s, v) = call(+ &env.app,+ "POST",+ "/api/mcp/servers",+ Some(json!({"name": "other", "transport": "http", "url": "https://example.com/mcp"})),+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ let (s, v) = call(+ &env.app,+ "GET",+ "/api/connections/composio/apps?q=gmail",+ None,+ )+ .await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert!(+ v["error"]+ .as_str()+ .unwrap()+ .contains("Add the Composio connector first"),+ "{v}"+ );+ let (s, _) = call(+ &env.app,+ "POST",+ "/api/connections/composio/apps/gmail/connect",+ None,+ )+ .await;+ assert_eq!(s, StatusCode::CONFLICT);++ // Added without a key: still refused, still nothing sent.+ add_composio(+ &env,+ "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-1",+ None,+ )+ .await;+ let (_, list) = call(&env.app, "GET", "/api/connections", None).await;+ assert_eq!(list["catalog"][0]["added"], true);+ assert_eq!(list["catalog"][0]["can_search"], false);+ let (s, v) = call(+ &env.app,+ "GET",+ "/api/connections/composio/apps?q=gmail",+ None,+ )+ .await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert!(v["error"].as_str().unwrap().contains("x-api-key"), "{v}");+ let (s, _) = call(+ &env.app,+ "POST",+ "/api/connections/composio/apps/gmail/connect",+ None,+ )+ .await;+ assert_eq!(s, StatusCode::CONFLICT);++ assert!(+ seen.lock().unwrap().is_empty(),+ "no request to Composio: {:?}",+ seen.lock().unwrap()+ );+}++#[tokio::test]+async fn search_and_connect_use_the_persons_key_and_user() {+ let (env, seen) = env_with_fake().await;+ add_composio(+ &env,+ "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-1",+ Some("ck-secret-1"),+ )+ .await;+ let (_, list) = call(&env.app, "GET", "/api/connections", None).await;+ let entry = &list["catalog"][0];+ assert_eq!(+ (entry["can_search"].clone(), entry["can_connect"].clone()),+ (json!(true), json!(true)),+ "{entry}"+ );+ assert!(+ !list.to_string().contains("ck-secret-1"),+ "the key is never listed"+ );+ assert!(+ seen.lock().unwrap().is_empty(),+ "listing doesn't call Composio"+ );++ // Bad queries and app names are refused before any call.+ for q in ["", "%20%20", &"a".repeat(61)] {+ let (s, _) = call(+ &env.app,+ "GET",+ &format!("/api/connections/composio/apps?q={q}"),+ None,+ )+ .await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "q={q}");+ }+ for slug in ["Gmail", "a.b", "x%2F..%2Fy"] {+ let (s, _) = call(+ &env.app,+ "POST",+ &format!("/api/connections/composio/apps/{slug}/connect"),+ None,+ )+ .await;+ assert!(+ s == StatusCode::BAD_REQUEST || s == StatusCode::NOT_FOUND,+ "{slug}: {s}"+ );+ }+ assert!(seen.lock().unwrap().is_empty());++ let (s, v) = call(+ &env.app,+ "GET",+ "/api/connections/composio/apps?q=g%20mail",+ None,+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(+ v["apps"].as_array().unwrap().len(),+ 1,+ "an entry with a bad slug is left out: {v}"+ );+ assert_eq!(v["apps"][0]["slug"], "gmail");+ assert_eq!(v["apps"][0]["tools_count"], 23);+ assert_eq!(v["can_connect"], true);+ assert!(v["warning"]+ .as_str()+ .unwrap()+ .contains("Composio's servers"));++ let (s, v) = call(+ &env.app,+ "POST",+ "/api/connections/composio/apps/gmail/connect",+ None,+ )+ .await;+ assert_eq!(s, StatusCode::OK, "{v}");+ assert_eq!(v["redirect_url"], "https://connect.composio.dev/link/ln_1");+ assert!(v["warning"]+ .as_str()+ .unwrap()+ .contains("Composio's servers"));++ let seen = seen.lock().unwrap().clone();+ assert_eq!(seen.len(), 3, "{seen:?}");+ assert!(+ seen.iter().all(|(_, _, key, _)| key == "ck-secret-1"),+ "every call carries the person's key"+ );+ assert_eq!(+ seen[0].1,+ "/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"}))+ );+ assert_eq!(+ (seen[2].1.as_str(), &seen[2].3),+ (+ "/api/v3.1/tool_router/session/trs_1/link",+ &json!({"toolkit": "gmail"})+ )+ );+}++#[tokio::test]+async fn a_refused_key_or_missing_user_is_explained() {+ let (env, seen) = env_with_fake().await;+ add_composio(+ &env,+ "https://backend.composio.dev/v3/mcp/abc/mcp",+ Some("ck-wrong"),+ )+ .await;+ let (_, list) = call(&env.app, "GET", "/api/connections", None).await;+ assert_eq!(list["catalog"][0]["can_connect"], false);++ let (s, v) = call(+ &env.app,+ "GET",+ "/api/connections/composio/apps?q=gmail",+ None,+ )+ .await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert!(+ v["error"].as_str().unwrap().contains("refused the API key"),+ "{v}"+ );+ assert!(+ !v.to_string().contains("ck-wrong"),+ "the key is never echoed"+ );++ let (s, v) = call(+ &env.app,+ "POST",+ "/api/connections/composio/apps/gmail/connect",+ None,+ )+ .await;+ assert_eq!(s, StatusCode::CONFLICT, "{v}");+ assert!(v["error"].as_str().unwrap().contains("no user_id"), "{v}");+ assert_eq!(+ seen.lock().unwrap().len(),+ 1,+ "only the search reached Composio"+ );+}++#[tokio::test]+async fn finding_apps_is_person_only() {+ let (env, seen) = env_with_fake().await;+ add_composio(+ &env,+ "https://backend.composio.dev/v3/mcp/abc/mcp?user_id=u-1",+ Some("ck-secret-1"),+ )+ .await;+ assert_eq!(+ call_remote(&env.app, "GET", "/api/connections/composio/apps?q=gmail").await,+ StatusCode::UNAUTHORIZED+ );+ assert_eq!(+ call_remote(+ &env.app,+ "POST",+ "/api/connections/composio/apps/gmail/connect"+ )+ .await,+ StatusCode::UNAUTHORIZED+ );++ let bot = env.state.db.get_kwant(&env.a).await.unwrap().unwrap();+ let scope = SelfScope {+ kwant_id: bot.id.clone(),+ kwant_name: bot.name.clone(),+ ..Default::default()+ };+ let folder = tempfile::tempdir().unwrap();+ let (_, token) = mcp_runtime::prepare_turn_with_self(+ &env.state,+ &bot,+ None,+ Some(folder.path().to_path_buf()),+ Some(scope),+ )+ .await+ .unwrap();+ let bearer = format!("Bearer {token}");+ let (s, _) = call_with(+ &env.app,+ "GET",+ "/api/connections/composio/apps?q=gmail",+ None,+ &[("authorization", &bearer)],+ )+ .await;+ assert_eq!(s, StatusCode::FORBIDDEN);+ let (s, _) = call_with(+ &env.app,+ "POST",+ "/api/connections/composio/apps/gmail/connect",+ None,+ &[("authorization", &bearer)],+ )+ .await;+ assert_eq!(s, StatusCode::FORBIDDEN);+ assert!(+ seen.lock().unwrap().is_empty(),+ "a bot's token never reaches Composio"+ );+}