Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(apps): connect API-key Composio apps automatically and browse All apps by category (MUL-9920) (#11255)
Jiayuan Zhangb4485ab165e5
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex a098fcc35f..c044f85213 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -5050,9 +5050,11 @@ const AppCatalogEntrySchema = z.object({name: z.string().default(""),logo: z.string().optional().catch(undefined),category: z.string().optional().catch(undefined),+ category_id: z.string().optional().catch(undefined),curated: z.boolean().default(false).catch(false),recommended_scope: AppAccountScopeSchema.optional(),allowed: z.boolean().optional().catch(undefined),+ connect_method: z.enum(["oauth", "key"]).optional().catch(undefined),}).loose();export const AppCatalogResponseSchema = z.object({diff --git a/packages/core/types/connected-apps.ts b/packages/core/types/connected-apps.tsindex fbbc776002..3b15fe9565 100644--- a/packages/core/types/connected-apps.ts+++ b/packages/core/types/connected-apps.ts@@ -80,10 +80,13 @@ export interface AppCatalogEntry {name: string;logo?: string;category?: string;+ category_id?: string;curated: boolean;recommended_scope?: AppAccountScope;/** False only in the admin's full view for apps the catalog leaves out. */allowed?: boolean;+ /** "key" when connecting asks the member for an API key or token. */+ connect_method?: "oauth" | "key";}export type AppCallOutcome =diff --git a/packages/views/agents/components/add-agent-app-dialog.tsx b/packages/views/agents/components/add-agent-app-dialog.tsxindex b5928b75c2..0d9bb9f589 100644--- a/packages/views/agents/components/add-agent-app-dialog.tsx+++ b/packages/views/agents/components/add-agent-app-dialog.tsx@@ -27,8 +27,12 @@ import { ComposioToolkitLogo } from "../../common/composio-toolkit-logo";import { useT } from "../../i18n";import { useTeamAppAccess } from "../../common/use-team-app-access";import { scopeForNewApp } from "./agent-app-status";+import { useAppCategoryLabel } from "../../apps/hooks/use-app-category-label";import { useAppStatusLabel } from "./use-agent-apps";+/** Rows rendered before "Show more"; the full catalog has well over a thousand apps. */+const PAGE_SIZE = 50;+/*** Adds one catalog app to the agent. The account it uses is decided for the* viewer (`scopeForNewApp`); a personal-account app needs no account of the@@ -51,8 +55,11 @@ export function AddAgentAppDialog({const update = useUpdateAgentApps(agent.id);const statusLabel = useAppStatusLabel();const teamAccess = useTeamAppAccess(overview.data);+ const { t: ts } = useT("settings");+ const categoryLabel = useAppCategoryLabel();const [query, setQuery] = useState("");const [adding, setAdding] = useState<string | null>(null);+ const [page, setPage] = useState({ query: "", limit: PAGE_SIZE });const available = useMemo(() => {const onAgent = new Set((appsQuery.data ?? []).map((a) => a.toolkit_slug));@@ -67,9 +74,11 @@ export function AddAgentAppDialog({(app) =>app.name.toLowerCase().includes(q) ||app.slug.includes(q) ||- (app.category ?? "").toLowerCase().includes(q),+ (app.category ?? "").toLowerCase().includes(q) ||+ (categoryLabel.entry(app) ?? "").toLowerCase().includes(q),);- }, [available, query]);+ }, [available, query, categoryLabel]);+ const limit = page.query === query ? page.limit : PAGE_SIZE;const ready = appsQuery.isSuccess && overview.isSuccess;@@ -113,7 +122,7 @@ export function AddAgentAppDialog({? t(($) => $.add_app_dialog.recommended_team): app.recommended_scope === "personal"? t(($) => $.add_app_dialog.recommended_personal)- : app.category;+ : categoryLabel.entry(app);return [usual, overview.isSuccess ? status : null].filter(Boolean).join(" · ");};@@ -146,7 +155,7 @@ export function AddAgentAppDialog({<p className="p-4 text-caption text-muted-foreground">{t(($) => $.add_app_dialog.empty)}</p>) : (<ul className="divide-y">- {filtered.map((app) => (+ {filtered.slice(0, limit).map((app) => (<li key={app.slug} className="flex items-center gap-3 px-3 py-2.5"><ComposioToolkitLogo slug={app.slug} name={app.name} fallbackLogo={app.logo} /><div className="min-w-0 flex-1">@@ -170,6 +179,14 @@ export function AddAgentAppDialog({</Button></li>))}+ {filtered.length > limit && (+ <li className="flex justify-center px-3 py-2">+ <Button size="xs" variant="ghost" onClick={() => setPage({ query, limit: limit + PAGE_SIZE })}>+ {ts(($) => $.connected_apps.hub.show_more)}+ <span className="text-muted-foreground tabular-nums">{filtered.length - limit}</span>+ </Button>+ </li>+ )}</ul>)}</div>diff --git a/packages/views/apps/components/app-detail-page.tsx b/packages/views/apps/components/app-detail-page.tsxindex 986956e59b..7adee57a25 100644--- a/packages/views/apps/components/app-detail-page.tsx+++ b/packages/views/apps/components/app-detail-page.tsx@@ -12,6 +12,7 @@ import { useComposioAvailable } from "../../common/use-composio-available";import { CollectionPageState } from "../../layout/collection-page";import { OBJECT_PAGE_BODY, ObjectIdentity, ObjectPage } from "../../layout/object-page";import { useT } from "../../i18n";+import { useAppCategoryLabel } from "../hooks/use-app-category-label";import { useAppConnectReturn } from "../hooks/use-app-connect-return";import { AppAccountsSection } from "./app-accounts-card";import { AppActivityCard } from "./app-activity-card";@@ -29,6 +30,7 @@ export function AppDetailPage({ toolkitSlug }: { toolkitSlug: string }) {const available = useComposioAvailable();const overview = useQuery({ ...appsOverviewOptions(wsId), enabled: available });const catalog = useQuery({ ...appCatalogOptions(wsId), enabled: available });+ const categoryLabel = useAppCategoryLabel();useAppConnectReturn();const entry = catalog.data?.apps.find((a) => a.slug === toolkitSlug);@@ -86,7 +88,7 @@ export function AppDetailPage({ toolkitSlug }: { toolkitSlug: string }) {/>}title={name}- description={entry?.category}+ description={categoryLabel.entry(entry)}/>{data ? (<>diff --git a/packages/views/apps/components/apps-page.test.tsx b/packages/views/apps/components/apps-page.test.tsxindex d2e85fbd41..0d890eb9fb 100644--- a/packages/views/apps/components/apps-page.test.tsx+++ b/packages/views/apps/components/apps-page.test.tsx@@ -142,6 +142,48 @@ describe("AppsPage", () => {expect(within(screen.getAllByRole("list")[0]!).getAllByRole("link").map((l) => l.textContent)).toEqual(["Linear"]);});+ it("narrows All apps to a category from the URL and names how each app connects", async () => {+ vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "all", apps: [+ { slug: "gmail", name: "Gmail", curated: true, category: "Collaboration & Communication", connect_method: "oauth" },+ { slug: "openai", name: "OpenAI", curated: false, category: "AI & Machine Learning", category_id: "ai-machine-learning", connect_method: "key" },+ { slug: "tavily", name: "Tavily", curated: false, category: "Data & Analytics", connect_method: "key" },+ { slug: "gemini", name: "Gemini", curated: false, category_id: "ai_ml", connect_method: "key" },+ ] });+ overview = { ...overview, team: [], agent_apps: [] };+ const user = userEvent.setup();+ nav.search = "tab=all";+ renderPage();+ const rail = await screen.findByRole("navigation", { name: "App categories" });+ expect(within(rail).getAllByRole("button").map((b) => b.textContent)).toEqual([+ "All4", "Featured1", "AI & Machine Learning2", "Collaboration & Communication1", "Data & Analytics1",+ ]);+ // Without a category, cards name theirs.+ expect(screen.getByRole("link", { name: "Tavily" }).closest("li")).toHaveTextContent("Data & Analytics");++ await user.click(within(rail).getByRole("button", { name: /AI & Machine Learning/ }));+ expect(replace).toHaveBeenLastCalledWith("/acme/apps?tab=all&category=ai_ml");+ expect(screen.getByRole("heading", { name: /^AI & Machine Learning/ })).toHaveTextContent(/2$/);+ const list = screen.getAllByRole("list")[0]!;+ expect(within(list).getAllByRole("link").map((l) => l.textContent)).toEqual(["OpenAI", "Gemini"]);+ expect(within(list).getAllByText("Uses an API key")).toHaveLength(2);++ await user.click(screen.getByRole("tab", { name: /In use/ }));+ expect(replace).toHaveBeenLastCalledWith("/acme/apps");+ });++ it("shows a long catalog a page at a time", async () => {+ vi.mocked(api.listAppCatalog).mockResolvedValue({ catalog_mode: "all", apps: Array.from({ length: 75 }, (_, i) => ({+ slug: `app${i}`, name: `App ${String(i).padStart(2, "0")}`, curated: false,+ })) });+ overview = { ...overview, team: [], agent_apps: [] };+ const user = userEvent.setup();+ nav.search = "tab=all";+ renderPage();+ await user.click(await screen.findByRole("button", { name: /Show more/ }));+ expect(within(screen.getAllByRole("list")[0]!).getAllByRole("link")).toHaveLength(75);+ expect(screen.queryByRole("button", { name: /Show more/ })).not.toBeInTheDocument();+ });+it("recovers an empty saved catalog only after an admin confirms", async () => {overview = { ...overview, catalog_mode: "custom", allowed_toolkits: [], can_manage: true };vi.mocked(api.updateAppSettings).mockImplementation(async () => {diff --git a/packages/views/apps/components/apps-page.tsx b/packages/views/apps/components/apps-page.tsxindex 3748203901..f632635e1d 100644--- a/packages/views/apps/components/apps-page.tsx+++ b/packages/views/apps/components/apps-page.tsx@@ -1,6 +1,6 @@"use client";-import { useMemo, useState } from "react";+import { useMemo, useState, type ReactNode } from "react";import { useQuery } from "@tanstack/react-query";import { toast } from "sonner";import { AlertCircle, Plug, Search } from "@multica/ui/icons";@@ -27,7 +27,9 @@ import { useTeamAppAccess } from "../../common/use-team-app-access";import { useViewerAppsOverview } from "../../common/use-viewer-apps-overview";import { useT } from "../../i18n";import { useNavigation } from "../../navigation";+import { useAppCategoryLabel } from "../hooks/use-app-category-label";import { useAppConnectReturn } from "../hooks/use-app-connect-return";+import { groupAppsByCategory } from "../lib/categories";import { buildAppDirectory, matchesAppSearch, type DirectoryApp } from "../lib/directory";import { AccountsList, useAccountRows } from "./accounts-list";import { DirectoryCard, SetUpCard, type DirectoryCardHandlers } from "./directory-card";@@ -35,6 +37,10 @@ import { DirectoryCard, SetUpCard, type DirectoryCardHandlers } from "./directorconst TABS = ["in_use", "attention", "accounts", "all"] as const;type DirectoryTab = (typeof TABS)[number];+/** Cards rendered before "Show more"; the full catalog has well over a thousand apps. */+const PAGE_SIZE = 60;+const CURATED = "curated";+function parseTab(value: string | null): DirectoryTab {return (TABS as readonly string[]).includes(value ?? "") ? (value as DirectoryTab) : "in_use";}@@ -79,25 +85,39 @@ function AppsDirectory() {const withdrawTeam = useDismissTeamAppRequests();const navigation = useNavigation();const tab = parseTab(navigation.searchParams.get("tab"));+ const categoryParam = tab === "all" ? navigation.searchParams.get("category") : null;const [query, setQuery] = useState("");const [connecting, setConnecting] = useState<ConnectTarget | null>(null);const [asking, setAsking] = useState<string | null>(null);+ const [page, setPage] = useState({ key: "", limit: PAGE_SIZE });+ const categoryLabel = useAppCategoryLabel();useAppConnectReturn();const accountRows = useAccountRows(viewerOverview, catalog.data?.apps ?? []);- // The tab lives in the URL so a connect flow started here comes back to it.- const setTab = (next: DirectoryTab) => {+ // The tab and category live in the URL so a connect flow started here comes back to them.+ const replaceParams = (update: (params: URLSearchParams) => void) => {const params = new URLSearchParams(navigation.searchParams);- if (next === "in_use") params.delete("tab");- else params.set("tab", next);+ update(params);const search = params.toString();navigation.replace(`${navigation.pathname}${search ? `?${search}` : ""}`);};+ const setTab = (next: DirectoryTab) =>+ replaceParams((params) => {+ if (next === "in_use") params.delete("tab");+ else params.set("tab", next);+ params.delete("category");+ });+ const setCategory = (next: string | null) =>+ replaceParams((params) => {+ if (next) params.set("category", next);+ else params.delete("category");+ });const directory = useMemo(() => {if (!viewerOverview) return null;return buildAppDirectory({ overview: viewerOverview, catalog: catalog.data?.apps ?? [], viewerId });}, [viewerOverview, catalog.data, viewerId]);+ const categories = useMemo(() => groupAppsByCategory(directory?.all ?? []), [directory]);const handlers: DirectoryCardHandlers = {asking,@@ -143,8 +163,19 @@ function AppsDirectory() {attention: directory.attention,all: directory.all,};- const shown = tab === "accounts" ? [] : lists[tab].filter((app) => matchesAppSearch(app, query));const needle = query.trim().toLowerCase();+ const matches = (app: DirectoryApp) =>+ matchesAppSearch(app, query) || !!categoryLabel.entry(app.entry)?.toLowerCase().includes(needle);+ const found = tab === "accounts" ? [] : lists[tab].filter(matches);+ const category =+ categoryParam === CURATED || categories.groups.some((group) => group.key === categoryParam)+ ? categoryParam+ : null;+ const inCategory = (app: DirectoryApp) =>+ category === CURATED ? !!app.entry?.curated : categories.categoryOf.get(app.slug) === category;+ const shown = category ? found.filter(inCategory) : found;+ const pageKey = `${tab}|${category ?? ""}|${needle}`;+ const limit = page.key === pageKey ? page.limit : PAGE_SIZE;const matchesAccount = (name: string) => !needle || name.toLowerCase().includes(needle);const emptyText = query.trim()? t(($) => $.connected_apps.hub.no_matches)@@ -198,14 +229,71 @@ function AppsDirectory() {{tab === "accounts" ? (<AccountsList overview={viewerOverview} rows={accountRows} matches={matchesAccount} />- ) : shown.length > 0 ? (- <ul className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">- {shown.map((app) => <DirectoryCard key={app.slug} app={app} handlers={handlers} />)}- </ul>+ ) : tab === "all" ? (+ <div className="grid gap-6 md:grid-cols-[12rem_minmax(0,1fr)]">+ <nav+ aria-label={t(($) => $.connected_apps.hub.categories_nav)}+ className="-mx-1 flex gap-1 overflow-x-auto px-1 md:sticky md:top-0 md:mx-0 md:flex-col md:gap-px md:self-start md:overflow-visible md:px-0"+ >+ <CategoryItem+ label={t(($) => $.connected_apps.hub.category_all)}+ count={found.length}+ active={category === null}+ onSelect={() => setCategory(null)}+ />+ <CategoryItem+ label={t(($) => $.connected_apps.hub.category_curated)}+ count={found.filter((app) => app.entry?.curated).length}+ active={category === CURATED}+ onSelect={() => setCategory(CURATED)}+ />+ <p className="hidden px-2 pt-3 pb-1 text-caption font-medium text-muted-foreground md:block">+ {t(($) => $.connected_apps.hub.categories_label)}+ </p>+ {categories.groups.map((group) => {+ const count = found.filter((app) => categories.categoryOf.get(app.slug) === group.key).length;+ if (count === 0 && category !== group.key) return null;+ return (+ <CategoryItem+ key={group.key}+ label={categoryLabel.group(group)}+ count={count}+ active={category === group.key}+ onSelect={() => setCategory(group.key)}+ />+ );+ })}+ </nav>+ <section className="min-w-0 space-y-3">+ {category && (+ <h3 className="flex items-baseline gap-2 text-body font-semibold">+ {category === CURATED+ ? t(($) => $.connected_apps.hub.category_curated)+ : categoryLabel.group(categories.groups.find((group) => group.key === category)!)}+ <span className="text-caption font-normal text-muted-foreground tabular-nums">{shown.length}</span>+ </h3>+ )}+ <AppGrid+ apps={shown}+ limit={limit}+ onShowMore={() => setPage({ key: pageKey, limit: limit + PAGE_SIZE })}+ emptyText={emptyText}+ columns="sm:grid-cols-2 xl:grid-cols-3"+ render={(app) => (+ <DirectoryCard key={app.slug} app={app} handlers={handlers} detail={category ? "connect" : "category"} />+ )}+ />+ </section>+ </div>) : (- <p className="rounded-lg border border-dashed px-4 py-6 text-center text-caption text-muted-foreground">- {emptyText}- </p>+ <AppGrid+ apps={shown}+ limit={limit}+ onShowMore={() => setPage({ key: pageKey, limit: limit + PAGE_SIZE })}+ emptyText={emptyText}+ columns="sm:grid-cols-2 lg:grid-cols-3"+ render={(app) => <DirectoryCard key={app.slug} app={app} handlers={handlers} />}+ />)}{popular.length > 0 && (@@ -234,6 +322,69 @@ function AppsDirectory() {);}+function AppGrid({+ apps,+ limit,+ onShowMore,+ emptyText,+ columns,+ render,+}: {+ apps: DirectoryApp[];+ limit: number;+ onShowMore: () => void;+ emptyText: string;+ columns: string;+ render: (app: DirectoryApp) => ReactNode;+}) {+ const { t } = useT("settings");+ if (apps.length === 0) {+ return (+ <p className="rounded-lg border border-dashed px-4 py-6 text-center text-caption text-muted-foreground">+ {emptyText}+ </p>+ );+ }+ const hidden = apps.length - limit;+ return (+ <>+ <ul className={`grid gap-3 ${columns}`}>{apps.slice(0, limit).map(render)}</ul>+ {hidden > 0 && (+ <div className="flex justify-center">+ <Button variant="outline" size="sm" onClick={onShowMore}>+ {t(($) => $.connected_apps.hub.show_more)}+ <span className="text-muted-foreground tabular-nums">{hidden}</span>+ </Button>+ </div>+ )}+ </>+ );+}++function CategoryItem({+ label,+ count,+ active,+ onSelect,+}: {+ label: string;+ count: number;+ active: boolean;+ onSelect: () => void;+}) {+ return (+ <button+ type="button"+ aria-current={active ? "true" : undefined}+ onClick={onSelect}+ className="flex h-7 shrink-0 items-center gap-2 rounded-md px-2 text-left text-body whitespace-nowrap outline-none hover:bg-accent/60 focus-visible:ring-2 focus-visible:ring-ring aria-[current=true]:bg-accent aria-[current=true]:font-medium md:w-full"+ >+ <span className="min-w-0 flex-1 truncate">{label}</span>+ <span className="text-caption text-muted-foreground tabular-nums">{count}</span>+ </button>+ );+}+function TabTrigger({ value, label, count }: { value: DirectoryTab; label: string; count: number }) {return (<TabsTrigger value={value} className="px-2.5">diff --git a/packages/views/apps/components/directory-card.tsx b/packages/views/apps/components/directory-card.tsxindex 06a88cc97d..589b6ac11a 100644--- a/packages/views/apps/components/directory-card.tsx+++ b/packages/views/apps/components/directory-card.tsx@@ -9,6 +9,7 @@ import type { AppAccountScope } from "@multica/core/types";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";import { UpgradeToAddLink } from "../../billing";import { useT } from "../../i18n";+import { useAppCategoryLabel } from "../hooks/use-app-category-label";import type { DirectoryApp } from "../lib/directory";import { AppCard } from "./app-card";import { AppStatusLabel } from "./app-status-label";@@ -23,13 +24,24 @@ export interface DirectoryCardHandlers {needsUpgrade: (slug: string) => boolean;}+/** What a card for an unused app says under its name. */+export type SetUpDetail = "category" | "connect";+/** An app in use: where its account stands, whose it is, and what to do or who uses it. */-export function DirectoryCard({ app, handlers }: { app: DirectoryApp; handlers: DirectoryCardHandlers }) {+export function DirectoryCard({+ app,+ handlers,+ detail,+}: {+ app: DirectoryApp;+ handlers: DirectoryCardHandlers;+ detail?: SetUpDetail;+}) {const { t } = useT("settings");const paths = useWorkspacePaths();const { getActorName } = useActorName();- if (!app.inUse && !app.request) return <SetUpCard app={app} />;+ if (!app.inUse && !app.request) return <SetUpCard app={app} detail={detail} />;const scopeLine =app.scopes.length === 2@@ -85,16 +97,26 @@ export function DirectoryCard({ app, handlers }: { app: DirectoryApp; handlers:);}-export function SetUpCard({ app }: { app: DirectoryApp }) {+export function SetUpCard({ app, detail = "category" }: { app: DirectoryApp; detail?: SetUpDetail }) {+ const { t } = useT("settings");const paths = useWorkspacePaths();- const category = app.entry?.category;+ const categoryLabel = useAppCategoryLabel();+ const method = app.entry?.connect_method;+ const connect =+ method === "key"+ ? t(($) => $.connected_apps.hub.connect_key)+ : method === "oauth"+ ? t(($) => $.connected_apps.hub.connect_oauth)+ : undefined;+ const category = categoryLabel.entry(app.entry);+ const text = detail === "connect" ? (connect ?? category) : (category ?? connect);return (<AppCardslug={app.slug}name={app.name}logo={app.entry?.logo}href={paths.appDetail(app.slug)}- meta={category ? <span className="truncate">{category}</span> : undefined}+ meta={text ? <span className="truncate">{text}</span> : undefined}/>);}diff --git a/packages/views/apps/hooks/use-app-category-label.ts b/packages/views/apps/hooks/use-app-category-label.tsnew file mode 100644index 0000000000..cc5ecfacd3--- /dev/null+++ b/packages/views/apps/hooks/use-app-category-label.ts@@ -0,0 +1,19 @@+import { useMemo } from "react";+import type { AppCatalogEntry } from "@multica/core/types";+import { useT } from "../../i18n";+import { knownCategory, type AppCategoryGroup, type KnownAppCategory } from "../lib/categories";++/** Labels for app categories: translated when Multica knows them, Composio's name otherwise. */+export function useAppCategoryLabel() {+ const { t } = useT("settings");+ return useMemo(() => {+ const known = (key: KnownAppCategory) => t(($) => $.connected_apps.hub.categories[key]);+ return {+ group: (group: AppCategoryGroup) => (group.known ? known(group.known) : group.name),+ entry: (entry: AppCatalogEntry | undefined) => {+ const key = knownCategory(entry);+ return key ? known(key) : entry?.category || undefined;+ },+ };+ }, [t]);+}diff --git a/packages/views/apps/lib/categories.test.ts b/packages/views/apps/lib/categories.test.tsnew file mode 100644index 0000000000..1a86994822--- /dev/null+++ b/packages/views/apps/lib/categories.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from "vitest";+import type { AppCatalogEntry } from "@multica/core/types";+import { groupAppsByCategory, knownCategory, normalizeCategory } from "./categories";++const app = (slug: string, entry: Partial<AppCatalogEntry> = {}) => ({+ slug,+ entry: { slug, name: slug, curated: false, ...entry },+});++describe("app categories", () => {+ it("reads Composio ids and names alike", () => {+ expect(normalizeCategory("Developer Tools & DevOps")).toBe("developer_tools_devops");+ expect(normalizeCategory("developer-tools-and-devops")).toBe("developer_tools_devops");+ expect(knownCategory({ slug: "a", name: "a", curated: false, category_id: "e-commerce" })).toBe("ecommerce");+ expect(knownCategory({ slug: "a", name: "a", curated: false, category: "Social Media" })).toBe("marketing_social");+ expect(knownCategory({ slug: "a", name: "a", curated: false, category_id: "x", category: "CRM" })).toBe("crm");+ });++ it("sorts categories by size, keeps sizeable unknown ones and puts the rest in Other", () => {+ const { groups, categoryOf } = groupAppsByCategory([+ app("a", { category: "AI & Machine Learning" }),+ app("b", { category_id: "ai-machine-learning" }),+ app("c", { category: "CRM" }),+ app("d", { category: "Wi-Fi Management" }),+ app("e", { category: "Fundraising" }),+ app("f", { category: "Fundraising" }),+ app("g", { category: "Fundraising" }),+ app("h"),+ { slug: "remote" },+ ]);+ expect(groups.map((g) => [g.key, g.slugs.length])).toEqual([+ ["name:fundraising", 3],+ ["ai_ml", 2],+ ["crm", 1],+ ["other", 3],+ ]);+ expect(groups[0]!.name).toBe("Fundraising");+ expect(categoryOf.get("d")).toBe("other");+ });+});diff --git a/packages/views/apps/lib/categories.ts b/packages/views/apps/lib/categories.tsnew file mode 100644index 0000000000..91debc98b1--- /dev/null+++ b/packages/views/apps/lib/categories.ts@@ -0,0 +1,140 @@+import type { AppCatalogEntry } from "@multica/core/types";++/** Categories the Apps page names in every locale, in Composio's order. */+export const APP_CATEGORIES = [+ "ai_ml",+ "developer_tools",+ "data_analytics",+ "productivity",+ "collaboration",+ "marketing_social",+ "documents",+ "sales_support",+ "crm",+ "finance",+ "workflow_automation",+ "design",+ "ecommerce",+ "advertising",+ "scheduling",+ "entertainment",+ "hr_recruiting",+ "education",+ "other",+] as const;++export type KnownAppCategory = (typeof APP_CATEGORIES)[number];++// Normalized Composio ids and names; both "Developer Tools & DevOps" and+// "developer-tools-and-devops" normalize to "developer_tools_devops".+const ALIASES: Record<string, KnownAppCategory> = {+ ai_machine_learning: "ai_ml",+ ai: "ai_ml",+ machine_learning: "ai_ml",+ developer_tools_devops: "developer_tools",+ developer_tools: "developer_tools",+ devops: "developer_tools",+ data_analytics: "data_analytics",+ analytics: "data_analytics",+ productivity_project_management: "productivity",+ productivity: "productivity",+ project_management: "productivity",+ collaboration_communication: "collaboration",+ collaboration: "collaboration",+ communication: "collaboration",+ marketing_social_media: "marketing_social",+ marketing: "marketing_social",+ social_media: "marketing_social",+ document_file_management: "documents",+ documents: "documents",+ file_management: "documents",+ sales_customer_support: "sales_support",+ customer_support: "sales_support",+ sales: "sales_support",+ crm: "crm",+ finance_accounting: "finance",+ finance: "finance",+ accounting: "finance",+ workflow_automation: "workflow_automation",+ automation: "workflow_automation",+ design_creative_tools: "design",+ design: "design",+ e_commerce: "ecommerce",+ ecommerce: "ecommerce",+ advertising_marketing: "advertising",+ advertising: "advertising",+ scheduling_booking: "scheduling",+ scheduling: "scheduling",+ entertainment_media: "entertainment",+ entertainment: "entertainment",+ hr_recruiting: "hr_recruiting",+ recruiting: "hr_recruiting",+ education_lms: "education",+ education: "education",+};++/** A category Multica has no label for keeps Composio's name once this many apps share it. */+const MIN_UNNAMED_CATEGORY = 3;++export function normalizeCategory(value: string): string {+ return value+ .toLowerCase()+ .split(/[^a-z0-9]+/)+ .filter((word) => word && word !== "and")+ .join("_");+}++export function knownCategory(entry: AppCatalogEntry | undefined): KnownAppCategory | null {+ for (const raw of [entry?.category_id, entry?.category]) {+ if (!raw) continue;+ const key = normalizeCategory(raw);+ const known = ALIASES[key] ?? APP_CATEGORIES.find((category) => category === key);+ if (known) return known;+ }+ return null;+}++export interface AppCategoryGroup {+ /** A known category, or `name:<normalized>` for one only Composio names. */+ key: string;+ known: KnownAppCategory | null;+ /** Composio's name, for categories without a translation. */+ name: string;+ slugs: string[];+}++/**+ * Sorts apps into categories: largest first, "other" last. Apps without a+ * category, or in a small one Multica has no label for, go to "other".+ */+export function groupAppsByCategory(+ apps: { slug: string; entry?: AppCatalogEntry }[],+): { groups: AppCategoryGroup[]; categoryOf: Map<string, string> } {+ const byKey = new Map<string, AppCategoryGroup>();+ const add = (key: string, known: KnownAppCategory | null, name: string, slug: string) => {+ const group = byKey.get(key) ?? { key, known, name, slugs: [] };+ group.slugs.push(slug);+ byKey.set(key, group);+ };+ for (const app of apps) {+ const known = knownCategory(app.entry);+ const name = app.entry?.category?.trim() ?? "";+ if (known) add(known, known, "", app.slug);+ else if (name) add(`name:${normalizeCategory(name)}`, null, name, app.slug);+ else add("other", "other", "", app.slug);+ }+ for (const group of [...byKey.values()]) {+ if (group.known || group.slugs.length >= MIN_UNNAMED_CATEGORY) continue;+ byKey.delete(group.key);+ for (const slug of group.slugs) add("other", "other", "", slug);+ }+ const groups = [...byKey.values()].sort(+ (a, b) =>+ Number(a.key === "other") - Number(b.key === "other") ||+ b.slugs.length - a.slugs.length ||+ a.key.localeCompare(b.key),+ );+ const categoryOf = new Map<string, string>();+ for (const group of groups) for (const slug of group.slugs) categoryOf.set(slug, group.key);+ return { groups, categoryOf };+}diff --git a/packages/views/locales/en/settings.json b/packages/views/locales/en/settings.jsonindex e73df9d2ce..80ed4ae391 100644--- a/packages/views/locales/en/settings.json+++ b/packages/views/locales/en/settings.json@@ -2052,7 +2052,35 @@"empty_attention": "Nothing needs your attention.","no_matches": "No apps match your search.","unavailable": "Apps aren't available on this server.",- "retry": "Try again"+ "retry": "Try again",+ "category_all": "All",+ "category_curated": "Featured",+ "categories_label": "Categories",+ "categories_nav": "App categories",+ "connect_oauth": "Signs in with OAuth",+ "connect_key": "Uses an API key",+ "show_more": "Show more",+ "categories": {+ "ai_ml": "AI & Machine Learning",+ "developer_tools": "Developer Tools & DevOps",+ "data_analytics": "Data & Analytics",+ "productivity": "Productivity & Project Management",+ "collaboration": "Collaboration & Communication",+ "marketing_social": "Marketing & Social Media",+ "documents": "Documents & Files",+ "sales_support": "Sales & Customer Support",+ "crm": "CRM",+ "finance": "Finance & Accounting",+ "workflow_automation": "Workflow Automation",+ "design": "Design & Creative Tools",+ "ecommerce": "E-commerce",+ "advertising": "Advertising",+ "scheduling": "Scheduling & Booking",+ "entertainment": "Entertainment & Media",+ "hr_recruiting": "HR & Recruiting",+ "education": "Education",+ "other": "Other"+ }},"app_page": {"agents_title": "Agents",diff --git a/packages/views/locales/es/settings.json b/packages/views/locales/es/settings.jsonindex 8bbee0cc3a..60bf6b9827 100644--- a/packages/views/locales/es/settings.json+++ b/packages/views/locales/es/settings.json@@ -2052,7 +2052,35 @@"empty_attention": "No hay nada que requiera tu atención.","no_matches": "Ninguna aplicación coincide con tu búsqueda.","unavailable": "Las aplicaciones no están disponibles en este servidor.",- "retry": "Reintentar"+ "retry": "Reintentar",+ "category_all": "Todas",+ "category_curated": "Destacadas",+ "categories_label": "Categorías",+ "categories_nav": "Categorías de apps",+ "connect_oauth": "Inicio de sesión con OAuth",+ "connect_key": "Usa una clave de API",+ "show_more": "Mostrar más",+ "categories": {+ "ai_ml": "IA y aprendizaje automático",+ "developer_tools": "Desarrollo y DevOps",+ "data_analytics": "Datos y analítica",+ "productivity": "Productividad y gestión de proyectos",+ "collaboration": "Colaboración y comunicación",+ "marketing_social": "Marketing y redes sociales",+ "documents": "Documentos y archivos",+ "sales_support": "Ventas y atención al cliente",+ "crm": "CRM",+ "finance": "Finanzas y contabilidad",+ "workflow_automation": "Automatización de flujos de trabajo",+ "design": "Diseño y herramientas creativas",+ "ecommerce": "Comercio electrónico",+ "advertising": "Publicidad",+ "scheduling": "Agenda y reservas",+ "entertainment": "Entretenimiento y medios",+ "hr_recruiting": "RR. HH. y selección",+ "education": "Educación",+ "other": "Otras"+ }},"app_page": {"agents_title": "Agentes",diff --git a/packages/views/locales/fr/settings.json b/packages/views/locales/fr/settings.jsonindex ea6dda3690..d14c6cb230 100644--- a/packages/views/locales/fr/settings.json+++ b/packages/views/locales/fr/settings.json@@ -2052,7 +2052,35 @@"empty_attention": "Rien ne nécessite votre attention.","no_matches": "Aucune app ne correspond à votre recherche.","unavailable": "Les apps ne sont pas disponibles sur ce serveur.",- "retry": "Réessayer"+ "retry": "Réessayer",+ "category_all": "Toutes",+ "category_curated": "À la une",+ "categories_label": "Catégories",+ "categories_nav": "Catégories d'apps",+ "connect_oauth": "Connexion OAuth",+ "connect_key": "Utilise une clé API",+ "show_more": "Afficher plus",+ "categories": {+ "ai_ml": "IA et apprentissage automatique",+ "developer_tools": "Outils de développement et DevOps",+ "data_analytics": "Données et analyse",+ "productivity": "Productivité et gestion de projet",+ "collaboration": "Collaboration et communication",+ "marketing_social": "Marketing et réseaux sociaux",+ "documents": "Documents et fichiers",+ "sales_support": "Ventes et support client",+ "crm": "CRM",+ "finance": "Finance et comptabilité",+ "workflow_automation": "Automatisation des workflows",+ "design": "Design et outils créatifs",+ "ecommerce": "E-commerce",+ "advertising": "Publicité",+ "scheduling": "Planning et réservations",+ "entertainment": "Divertissement et médias",+ "hr_recruiting": "RH et recrutement",+ "education": "Éducation",+ "other": "Autres"+ }},"app_page": {"agents_title": "Agents",diff --git a/packages/views/locales/ja/settings.json b/packages/views/locales/ja/settings.jsonindex 1ec47f1351..7f0a41498c 100644--- a/packages/views/locales/ja/settings.json+++ b/packages/views/locales/ja/settings.json@@ -2030,7 +2030,35 @@"empty_attention": "対応が必要なものはありません。","no_matches": "検索に一致するアプリはありません。","unavailable": "このサーバーではアプリを利用できません。",- "retry": "再試行"+ "retry": "再試行",+ "category_all": "すべて",+ "category_curated": "おすすめ",+ "categories_label": "カテゴリ",+ "categories_nav": "アプリのカテゴリ",+ "connect_oauth": "OAuth でログイン",+ "connect_key": "API キーを入力",+ "show_more": "さらに表示",+ "categories": {+ "ai_ml": "AI・機械学習",+ "developer_tools": "開発ツール・DevOps",+ "data_analytics": "データ・分析",+ "productivity": "生産性・プロジェクト管理",+ "collaboration": "コラボレーション・コミュニケーション",+ "marketing_social": "マーケティング・SNS",+ "documents": "ドキュメント・ファイル",+ "sales_support": "営業・カスタマーサポート",+ "crm": "CRM",+ "finance": "財務・会計",+ "workflow_automation": "ワークフロー自動化",+ "design": "デザイン・クリエイティブ",+ "ecommerce": "EC",+ "advertising": "広告",+ "scheduling": "スケジュール・予約",+ "entertainment": "エンタメ・メディア",+ "hr_recruiting": "人事・採用",+ "education": "教育",+ "other": "その他"+ }},"app_page": {"agents_title": "エージェント",diff --git a/packages/views/locales/ko/settings.json b/packages/views/locales/ko/settings.jsonindex 63d392db2a..f9f9ae7c69 100644--- a/packages/views/locales/ko/settings.json+++ b/packages/views/locales/ko/settings.json@@ -2030,7 +2030,35 @@"empty_attention": "확인할 항목이 없습니다.","no_matches": "검색과 일치하는 앱이 없습니다.","unavailable": "이 서버에서는 앱을 사용할 수 없습니다.",- "retry": "다시 시도"+ "retry": "다시 시도",+ "category_all": "전체",+ "category_curated": "추천",+ "categories_label": "카테고리",+ "categories_nav": "앱 카테고리",+ "connect_oauth": "OAuth로 로그인",+ "connect_key": "API 키 입력",+ "show_more": "더 보기",+ "categories": {+ "ai_ml": "AI 및 머신러닝",+ "developer_tools": "개발 도구 및 DevOps",+ "data_analytics": "데이터 및 분석",+ "productivity": "생산성 및 프로젝트 관리",+ "collaboration": "협업 및 커뮤니케이션",+ "marketing_social": "마케팅 및 소셜 미디어",+ "documents": "문서 및 파일",+ "sales_support": "영업 및 고객 지원",+ "crm": "CRM",+ "finance": "재무 및 회계",+ "workflow_automation": "워크플로 자동화",+ "design": "디자인 및 크리에이티브",+ "ecommerce": "이커머스",+ "advertising": "광고",+ "scheduling": "일정 및 예약",+ "entertainment": "엔터테인먼트 및 미디어",+ "hr_recruiting": "HR 및 채용",+ "education": "교육",+ "other": "기타"+ }},"app_page": {"agents_title": "에이전트",diff --git a/packages/views/locales/ru/settings.json b/packages/views/locales/ru/settings.jsonindex 8f8e431725..ad577e8cc6 100644--- a/packages/views/locales/ru/settings.json+++ b/packages/views/locales/ru/settings.json@@ -2096,7 +2096,35 @@"empty_attention": "Ничего не требует вашего внимания.","no_matches": "Нет приложений по вашему запросу.","unavailable": "Приложения недоступны на этом сервере.",- "retry": "Повторить"+ "retry": "Повторить",+ "category_all": "Все",+ "category_curated": "Рекомендуемые",+ "categories_label": "Категории",+ "categories_nav": "Категории приложений",+ "connect_oauth": "Вход через OAuth",+ "connect_key": "Нужен API-ключ",+ "show_more": "Показать ещё",+ "categories": {+ "ai_ml": "ИИ и машинное обучение",+ "developer_tools": "Разработка и DevOps",+ "data_analytics": "Данные и аналитика",+ "productivity": "Продуктивность и управление проектами",+ "collaboration": "Совместная работа и общение",+ "marketing_social": "Маркетинг и соцсети",+ "documents": "Документы и файлы",+ "sales_support": "Продажи и поддержка клиентов",+ "crm": "CRM",+ "finance": "Финансы и бухгалтерия",+ "workflow_automation": "Автоматизация процессов",+ "design": "Дизайн и творчество",+ "ecommerce": "Электронная коммерция",+ "advertising": "Реклама",+ "scheduling": "Расписание и бронирование",+ "entertainment": "Развлечения и медиа",+ "hr_recruiting": "HR и подбор персонала",+ "education": "Образование",+ "other": "Другое"+ }},"app_page": {"agents_title": "Агенты",diff --git a/packages/views/locales/zh-Hans/settings.json b/packages/views/locales/zh-Hans/settings.jsonindex d56db07e27..f30aaf7640 100644--- a/packages/views/locales/zh-Hans/settings.json+++ b/packages/views/locales/zh-Hans/settings.json@@ -2030,7 +2030,35 @@"empty_attention": "没有需要你处理的事项。","no_matches": "没有匹配的应用。","unavailable": "此服务器未提供应用功能。",- "retry": "重试"+ "retry": "重试",+ "category_all": "全部",+ "category_curated": "精选",+ "categories_label": "分类",+ "categories_nav": "应用分类",+ "connect_oauth": "OAuth 登录",+ "connect_key": "填写 API key",+ "show_more": "显示更多",+ "categories": {+ "ai_ml": "AI 与机器学习",+ "developer_tools": "开发与运维",+ "data_analytics": "数据分析",+ "productivity": "效率与项目管理",+ "collaboration": "协作与沟通",+ "marketing_social": "营销与社交媒体",+ "documents": "文档与文件",+ "sales_support": "销售与客服",+ "crm": "CRM",+ "finance": "财务与会计",+ "workflow_automation": "工作流自动化",+ "design": "设计与创意",+ "ecommerce": "电商",+ "advertising": "广告投放",+ "scheduling": "日程与预约",+ "entertainment": "娱乐与媒体",+ "hr_recruiting": "人事与招聘",+ "education": "教育",+ "other": "其他"+ }},"app_page": {"agents_title": "智能体",diff --git a/packages/views/locales/zh-Hant/settings.json b/packages/views/locales/zh-Hant/settings.jsonindex 816930e730..b454642cae 100644--- a/packages/views/locales/zh-Hant/settings.json+++ b/packages/views/locales/zh-Hant/settings.json@@ -2030,7 +2030,35 @@"empty_attention": "沒有需要你處理的事項。","no_matches": "沒有符合的應用。","unavailable": "此伺服器未提供應用功能。",- "retry": "重試"+ "retry": "重試",+ "category_all": "全部",+ "category_curated": "精選",+ "categories_label": "分類",+ "categories_nav": "應用程式分類",+ "connect_oauth": "OAuth 登入",+ "connect_key": "填寫 API key",+ "show_more": "顯示更多",+ "categories": {+ "ai_ml": "AI 與機器學習",+ "developer_tools": "開發與維運",+ "data_analytics": "資料分析",+ "productivity": "效率與專案管理",+ "collaboration": "協作與溝通",+ "marketing_social": "行銷與社群媒體",+ "documents": "文件與檔案",+ "sales_support": "銷售與客服",+ "crm": "CRM",+ "finance": "財務與會計",+ "workflow_automation": "工作流程自動化",+ "design": "設計與創意",+ "ecommerce": "電子商務",+ "advertising": "廣告投放",+ "scheduling": "排程與預約",+ "entertainment": "娛樂與媒體",+ "hr_recruiting": "人資與招募",+ "education": "教育",+ "other": "其他"+ }},"app_page": {"agents_title": "AI 代理",diff --git a/scripts/fake-composio.mjs b/scripts/fake-composio.mjsindex 5d0fd43e6d..cef0c62a25 100644--- a/scripts/fake-composio.mjs+++ b/scripts/fake-composio.mjs@@ -10,8 +10,10 @@// It serves the part of the Composio v3.1 REST API that server/pkg/composio// calls (toolkits, auth configs, connect links, connected accounts, tools, tool// execution and tool-router sessions), plus a stand-in for the hosted connect-// page: Allow finishes the connection, Cancel fails it. Every toolkit has a-// Composio-managed auth config, and tool calls return canned data.+// page: Allow finishes the connection, Cancel fails it. OAuth toolkits come+// with a Composio-managed auth config; API-key toolkits get one when Multica+// creates it, and their connect page asks for the key. Tool calls return+// canned data.//// `up` appends a marked block to the environment's env file with// COMPOSIO_API_KEY, COMPOSIO_BASE_URL, COMPOSIO_STATE_SECRET and@@ -58,39 +60,67 @@ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));// ------------------------------------------------------------------ catalog ---+const COLLAB = "Collaboration & Communication";+const PRODUCTIVITY = "Productivity & Project Management";+const DOCS = "Document & File Management";+const DEV = "Developer Tools & DevOps";+const DATA = "Data & Analytics";+const AI = "AI & Machine Learning";+const MARKETING = "Marketing & Social Media";+const SUPPORT = "Sales & Customer Support";++// [slug, name, category, auth]: "managed" toolkits sign in through Composio's+// own OAuth app and come with an auth config; "api_key" and "bearer_token"+// toolkits have none until Multica creates one, and their connect page asks+// for the key. "none" toolkits need no account, so Multica does not list them.const TOOLKITS = [- ["gmail", "Gmail", "email"],- ["googlecalendar", "Google Calendar", "scheduling"],- ["outlook", "Outlook", "email"],- ["slack", "Slack", "communication"],- ["notion", "Notion", "productivity"],- ["googledrive", "Google Drive", "file storage"],- ["googledocs", "Google Docs", "documents"],- ["googlesheets", "Google Sheets", "spreadsheets"],- ["confluence", "Confluence", "documents"],- ["linear", "Linear", "project management"],- ["jira", "Jira", "project management"],- ["asana", "Asana", "project management"],- ["figma", "Figma", "design"],- ["sentry", "Sentry", "developer tools"],- ["posthog", "PostHog", "analytics"],- ["hubspot", "HubSpot", "crm"],- ["zendesk", "Zendesk", "customer support"],- ["intercom", "Intercom", "customer support"],- ["stripe", "Stripe", "payments"],- ["airtable", "Airtable", "databases"],- ["github", "GitHub", "developer tools"],- ["discord", "Discord", "communication"],- ["trello", "Trello", "project management"],- ["dropbox", "Dropbox", "file storage"],-].map(([slug, name, category]) => ({+ ["gmail", "Gmail", COLLAB, "managed"],+ ["googlecalendar", "Google Calendar", "Scheduling & Booking", "managed"],+ ["outlook", "Outlook", COLLAB, "managed"],+ ["slack", "Slack", COLLAB, "managed"],+ ["notion", "Notion", PRODUCTIVITY, "managed"],+ ["googledrive", "Google Drive", DOCS, "managed"],+ ["googledocs", "Google Docs", DOCS, "managed"],+ ["googlesheets", "Google Sheets", PRODUCTIVITY, "managed"],+ ["confluence", "Confluence", COLLAB, "managed"],+ ["linear", "Linear", PRODUCTIVITY, "managed"],+ ["jira", "Jira", PRODUCTIVITY, "managed"],+ ["asana", "Asana", PRODUCTIVITY, "managed"],+ ["figma", "Figma", "Design & Creative Tools", "managed"],+ ["sentry", "Sentry", DEV, "managed"],+ ["posthog", "PostHog", DATA, "api_key"],+ ["hubspot", "HubSpot", "CRM", "managed"],+ ["zendesk", "Zendesk", SUPPORT, "managed"],+ ["intercom", "Intercom", SUPPORT, "managed"],+ ["stripe", "Stripe", "Finance & Accounting", "managed"],+ ["airtable", "Airtable", PRODUCTIVITY, "managed"],+ ["github", "GitHub", DEV, "managed"],+ ["discord", "Discord", COLLAB, "managed"],+ ["trello", "Trello", PRODUCTIVITY, "managed"],+ ["dropbox", "Dropbox", DOCS, "managed"],+ ["mailchimp", "Mailchimp", MARKETING, "managed"],+ ["tavily", "Tavily", DATA, "api_key"],+ ["exa", "Exa", DATA, "bearer_token"],+ ["firecrawl", "Firecrawl", DATA, "api_key"],+ ["openai", "OpenAI", AI, "api_key"],+ ["perplexityai", "Perplexity AI", AI, "api_key"],+ ["elevenlabs", "ElevenLabs", AI, "api_key"],+ ["sendgrid", "SendGrid", MARKETING, "api_key"],+ ["datadog", "Datadog", DEV, "api_key"],+ ["vercel", "Vercel", DEV, "bearer_token"],+ ["shopify", "Shopify", "E-commerce", "api_key"],+ ["hackernews", "Hacker News", "Entertainment & Media", "none"],+].map(([slug, name, category, auth]) => ({slug,name,- logo: `https://logos.composio.dev/api/${slug}`,- description: `${name} through the local Composio stand-in.`,- categories: [category],- auth_schemes: ["OAUTH2"],- composio_managed_auth_schemes: ["OAUTH2"],+ meta: {+ logo: `https://logos.composio.dev/api/${slug}`,+ description: `${name} through the local Composio stand-in.`,+ categories: [{ id: category.toLowerCase().replace(/[^a-z0-9]+/g, "-"), name: category }],+ },+ no_auth: auth === "none",+ auth_schemes: auth === "managed" ? ["oauth2"] : auth === "none" ? [] : [auth],+ composio_managed_auth_schemes: auth === "managed" ? ["oauth2"] : [],}));// Slugs follow Composio's VERB_OBJECT naming, which is what the gateway@@ -186,13 +216,18 @@ function cannedResult(toolSlug, args) {// ------------------------------------------------------------------- server ---function serve({ port, stateFile, watchFile }) {- const authConfigs = new Map(TOOLKITS.map((t) => [t.slug, `ac_${t.slug}`]));+ const authConfigs = new Map(+ TOOLKITS.filter((t) => t.composio_managed_auth_schemes.length > 0).map((t) => [+ t.slug,+ { id: `ac_${t.slug}`, scheme: "OAUTH2", managed: true },+ ]),+ );const links = new Map();const accounts = new Map();let seq = 1;let baseURL = "";- const slugOfAuthConfig = (id) => [...authConfigs.entries()].find(([, value]) => value === id)?.[0];+ const slugOfAuthConfig = (id) => [...authConfigs.entries()].find(([, config]) => config.id === id)?.[0];const toolkitName = (slug) => TOOLKITS.find((t) => t.slug === slug)?.name ?? slug;function send(res, code, body) {@@ -216,20 +251,31 @@ function serve({ port, stateFile, watchFile }) {function connectPage(token, link) {const name = toolkitName(link.slug);+ const scheme = authConfigs.get(link.slug)?.scheme ?? "OAUTH2";const finish = (ok) => `/connect/finish?token=${encodeURIComponent(token)}&ok=${ok}`;+ const keyLabel = scheme === "BEARER_TOKEN" ? "Token" : scheme === "BASIC" ? "Password" : "API key";+ const body =+ scheme === "OAUTH2"+ ? `<h1>Multica wants to access your ${name} account</h1>+<p>In production this step is ${name}'s own consent screen, reached through Composio's connect link.</p>+<div class="row"><a class="no" id="deny" href="${finish(0)}">Cancel</a><a class="ok" id="allow" href="${finish(1)}">Allow</a></div>`+ : `<h1>Connect ${name}</h1>+<p>In production Composio's connect page asks for your ${name} ${scheme === "API_KEY" ? keyLabel : keyLabel.toLowerCase()}. The fake accepts anything.</p>+<form action="/connect/finish" method="get"><input type="hidden" name="token" value="${token}"/><input type="hidden" name="ok" value="1"/>+<label>${keyLabel}<input id="key" name="key" type="password" required placeholder="${keyLabel}"/></label>+<div class="row"><a class="no" id="deny" href="${finish(0)}">Cancel</a><button class="ok" id="allow" type="submit">Connect</button></div></form>`;return `<!doctype html><html><head><meta charset="utf-8"><title>Connect ${name}</title><style>body{font-family:-apple-system,system-ui,sans-serif;background:#f5f5f7;margin:0;display:flex;align-items:center;justify-content:center;height:100vh}.card{background:#fff;border-radius:16px;padding:36px 40px;width:420px;box-shadow:0 8px 30px rgba(0,0,0,.08)}.tag{display:inline-block;background:#fff3cd;color:#7a5b00;font-size:12px;padding:3px 8px;border-radius:6px;margin-bottom:18px}h1{font-size:20px;margin:0 0 8px}p{color:#555;font-size:14px;line-height:1.5}.logo{width:44px;height:44px;border-radius:10px;margin-bottom:14px}-.row{display:flex;gap:10px;margin-top:24px}a{flex:1;text-align:center;padding:10px 0;border-radius:8px;text-decoration:none;font-size:14px;font-weight:600}-.ok{background:#111;color:#fff}.no{background:#eee;color:#333}</style></head><body><div class="card">+.row{display:flex;gap:10px;margin-top:24px}a,button{flex:1;text-align:center;padding:10px 0;border-radius:8px;border:0;text-decoration:none;font:600 14px inherit;cursor:pointer}+.ok{background:#111;color:#fff}.no{background:#eee;color:#333}+label{display:block;font-size:13px;font-weight:600;margin-top:16px}input[type=password]{display:block;box-sizing:border-box;width:100%;margin-top:6px;padding:9px 10px;border:1px solid #ccc;border-radius:8px;font-size:14px}</style></head><body><div class="card"><div class="tag">Local stand-in for Composio's hosted connect page</div><br/><img class="logo" alt="" src="https://logos.composio.dev/api/${link.slug}"/>-<h1>Multica wants to access your ${name} account</h1>-<p>In production this step is ${name}'s own consent screen, reached through Composio's connect link.</p>-<div class="row"><a class="no" id="deny" href="${finish(0)}">Cancel</a><a class="ok" id="allow" href="${finish(1)}">Allow</a></div>+${body}</div></body></html>`;}@@ -254,11 +300,12 @@ h1{font-size:20px;margin:0 0 8px}p{color:#555;font-size:14px;line-height:1.5}if (url.searchParams.get("ok") === "1") {const id = `ca_${link.slug}_${seq++}`;const now = new Date().toISOString();+ const config = authConfigs.get(link.slug);accounts.set(id, {id,user_id: link.user_id,auth_config_id: link.auth_config_id,- auth_config: { id: link.auth_config_id, auth_scheme: "OAUTH2", is_composio_managed: true },+ auth_config: { id: link.auth_config_id, auth_scheme: config?.scheme ?? "OAUTH2", is_composio_managed: Boolean(config?.managed) },toolkit: { slug: link.slug },status: "ACTIVE",created_at: now,@@ -278,34 +325,61 @@ h1{font-size:20px;margin:0 0 8px}p{color:#555;font-size:14px;line-height:1.5}if (method === "GET" && api === "/toolkits") {const category = url.searchParams.get("category");- const items = category ? TOOLKITS.filter((t) => t.categories.includes(category)) : TOOLKITS;+ const items = category ? TOOLKITS.filter((t) => t.meta.categories.some((c) => c.id === category)) : TOOLKITS;return send(res, 200, { items, total_items: items.length });}if (method === "GET" && api.startsWith("/toolkits/")) {const slug = decodeURIComponent(api.slice("/toolkits/".length)).toLowerCase();const toolkit = TOOLKITS.find((t) => t.slug === slug);- return toolkit ? send(res, 200, toolkit) : send(res, 404, { error: { message: "toolkit not found" } });+ if (!toolkit) return send(res, 404, { error: { message: "toolkit not found" } });+ // Unlike the list, the single-toolkit response has no auth_schemes or+ // no_auth: each scheme is an auth_config_details entry.+ const { auth_schemes: schemes, no_auth: noAuth, ...rest } = toolkit;+ const modes = noAuth ? ["NO_AUTH"] : schemes.map((s) => s.toUpperCase());+ return send(res, 200, {+ ...rest,+ auth_config_details: modes.map((mode) => ({+ mode,+ name: `${slug}_${mode.toLowerCase()}`,+ fields: {+ auth_config_creation: { required: [], optional: [] },+ connected_account_initiation: {+ required: mode === "OAUTH2" || mode === "NO_AUTH" ? [] : [{ name: "generic_api_key", displayName: "API Key", type: "string", required: true, default: null }],+ optional: [],+ },+ },+ })),+ });}if (method === "GET" && api === "/auth_configs") {const wanted = (url.searchParams.get("toolkit_slug") ?? "").split(",").filter(Boolean);const items = [...authConfigs.entries()].filter(([slug]) => wanted.length === 0 || wanted.includes(slug))- .map(([slug, id]) => ({- id,+ .map(([slug, config]) => ({+ id: config.id,name: `${toolkitName(slug)} (fake)`,toolkit: { slug },- auth_scheme: "OAUTH2",- is_composio_managed: true,+ auth_scheme: config.scheme,+ is_composio_managed: config.managed,status: "ENABLED",last_updated_at: "2026-01-01T00:00:00Z",}));return send(res, 200, { items, total_items: items.length });}if (method === "POST" && api === "/auth_configs") {- const slug = (await readBody(req))?.toolkit?.slug;- if (!slug) return send(res, 400, { error: { message: "toolkit.slug is required" } });- authConfigs.set(slug, `ac_${slug}`);- return send(res, 201, { auth_config: { id: `ac_${slug}`, toolkit: { slug }, is_composio_managed: true } });+ const body = await readBody(req);+ const slug = body?.toolkit?.slug;+ const toolkit = TOOLKITS.find((t) => t.slug === slug);+ if (!toolkit) return send(res, 400, { error: { message: "toolkit.slug must name a known toolkit" } });+ const custom = body.auth_config?.type === "use_custom_auth";+ const scheme = custom ? String(body.auth_config.authScheme ?? "").toUpperCase() : "OAUTH2";+ const offered = custom ? toolkit.auth_schemes : toolkit.composio_managed_auth_schemes;+ if (!offered.some((s) => s.toUpperCase() === scheme)) {+ return send(res, 400, { error: { message: `${slug} does not offer ${custom ? scheme : "managed"} auth` } });+ }+ const config = { id: `ac_${slug}`, scheme, managed: !custom };+ authConfigs.set(slug, config);+ return send(res, 201, { auth_config: { id: config.id, auth_scheme: scheme, is_composio_managed: config.managed }, toolkit: { slug } });}if (method === "POST" && api === "/connected_accounts/link") {const body = await readBody(req);diff --git a/server/internal/handler/connected_apps.go b/server/internal/handler/connected_apps.goindex 6a957cfcbf..874f6a61be 100644--- a/server/internal/handler/connected_apps.go+++ b/server/internal/handler/connected_apps.go@@ -76,8 +76,12 @@ type AppCatalogEntry struct {Name string `json:"name"`Logo string `json:"logo,omitempty"`Category string `json:"category,omitempty"`+ CategoryID string `json:"category_id,omitempty"`Curated bool `json:"curated"`RecommendedScope string `json:"recommended_scope,omitempty"`+ // ConnectMethod is "oauth" or "key" (the member enters an API key or+ // token); empty for apps that are not Composio toolkits.+ ConnectMethod string `json:"connect_method,omitempty"`// Allowed is false only in the admin's full view (?view=all) for apps// the workspace catalog leaves out.Allowed bool `json:"allowed"`@@ -391,7 +395,10 @@ func (h *Handler) ListAppCatalog(w http.ResponseWriter, r *http.Request) {if !allowed && !viewAll {continue}- entry := AppCatalogEntry{Slug: slug, Name: tk.Name, Logo: tk.LogoURL, Category: tk.Category, Allowed: allowed}+ entry := AppCatalogEntry{+ Slug: slug, Name: tk.Name, Logo: tk.LogoURL, Category: tk.Category, CategoryID: tk.CategoryID,+ ConnectMethod: tk.ConnectMethod, Allowed: allowed,+ }if app, ok := connectedapps.Curated(slug); ok {entry.Curated, entry.RecommendedScope = true, app.Scope}diff --git a/server/internal/integrations/composio/auth_config_test.go b/server/internal/integrations/composio/auth_config_test.gonew file mode 100644index 0000000000..5ca4350754--- /dev/null+++ b/server/internal/integrations/composio/auth_config_test.go@@ -0,0 +1,204 @@+package composio++import (+ "context"+ "errors"+ "strings"+ "testing"++ sdk "github.com/multica-ai/multica/server/pkg/composio"+)++// catalogFakeSDK serves a toolkit catalog and records the auth configs+// ensureAuthConfig creates, which then show up in ListAuthConfigs.+type catalogFakeSDK struct {+ fakeSDK+ created []string+ custom map[string]string+ // projectFields names, per toolkit, the scheme whose auth config needs a+ // project-level field (GET /toolkits/{slug} only).+ projectFields map[string]string+}++// GetToolkit answers like GET /toolkits/{slug}: schemes come only as+// auth_config_details, without auth_schemes or no_auth.+func (f *catalogFakeSDK) GetToolkit(_ context.Context, slug string) (*sdk.Toolkit, error) {+ for _, listed := range f.toolkits {+ if listed.Slug != slug {+ continue+ }+ tk := sdk.Toolkit{Slug: listed.Slug, Name: listed.Name, Meta: listed.Meta, ComposioManagedAuthSchemes: listed.ComposioManagedAuthSchemes}+ for _, scheme := range listed.AuthSchemes {+ detail := sdk.ToolkitAuthConfigDetail{Mode: strings.ToUpper(scheme)}+ if strings.EqualFold(f.projectFields[slug], scheme) {+ detail.Fields.AuthConfigCreation.Required = []sdk.ToolkitAuthField{{Name: "subdomain"}}+ }+ tk.AuthConfigDetails = append(tk.AuthConfigDetails, detail)+ }+ return &tk, nil+ }+ return nil, &sdk.APIError{HTTPStatus: 404}+}++func (f *catalogFakeSDK) ListTools(context.Context, sdk.ListToolsRequest) (*sdk.ListToolsResponse, error) {+ return &sdk.ListToolsResponse{}, nil+}++func (f *catalogFakeSDK) GetTool(context.Context, string) (*sdk.Tool, error) {+ return nil, errors.New("no tools")+}++func (f *catalogFakeSDK) ExecuteTool(context.Context, string, sdk.ExecuteToolRequest) (*sdk.ExecuteToolResponse, error) {+ return nil, errors.New("no tools")+}++func (f *catalogFakeSDK) CreateManagedAuthConfig(_ context.Context, slug string) (string, error) {+ id := "ac_managed_" + slug+ f.created = append(f.created, id)+ f.authConfigs = append(f.authConfigs, sdk.AuthConfig{ID: id, Toolkit: sdk.Toolkit{Slug: slug}, AuthScheme: "OAUTH2", IsComposioManaged: true, Status: "ENABLED"})+ return id, nil+}++// keyCreatingSDK adds custom auth configs to catalogFakeSDK.+type keyCreatingSDK struct{ *catalogFakeSDK }++func (f keyCreatingSDK) CreateCustomAuthConfig(_ context.Context, slug, scheme, name string) (string, error) {+ id := "ac_" + scheme + "_" + slug+ f.created = append(f.created, id)+ if f.custom == nil {+ f.custom = map[string]string{}+ }+ f.custom[slug] = name+ f.authConfigs = append(f.authConfigs, sdk.AuthConfig{ID: id, Toolkit: sdk.Toolkit{Slug: slug}, AuthScheme: scheme, Status: "ENABLED"})+ return id, nil+}++func newCatalogFake() *catalogFakeSDK {+ return &catalogFakeSDK{fakeSDK: fakeSDK{+ authConfigsSet: true,+ authConfigs: []sdk.AuthConfig{+ {ID: "ac_slack", Toolkit: sdk.Toolkit{Slug: "slack"}, AuthScheme: "OAUTH2", Status: "ENABLED", IsComposioManaged: true},+ {ID: "ac_sendgrid", Toolkit: sdk.Toolkit{Slug: "sendgrid"}, AuthScheme: "API_KEY", Status: "ENABLED"},+ },+ toolkits: []sdk.Toolkit{+ {Slug: "slack", Name: "Slack", AuthSchemes: []string{"oauth2"}},+ {Slug: "sendgrid", Name: "SendGrid", AuthSchemes: []string{"api_key"}},+ {Slug: "github", Name: "GitHub", AuthSchemes: []string{"oauth2", "api_key"}, ComposioManagedAuthSchemes: []string{"oauth2"},+ Meta: map[string]any{"categories": []any{map[string]any{"id": "developer-tools", "name": "Developer Tools"}}}},+ {Slug: "tavily", Name: "Tavily", AuthSchemes: []string{"api_key"},+ Meta: map[string]any{"categories": []any{map[string]any{"id": "ai-machine-learning", "name": "AI & Machine Learning"}}}},+ {Slug: "pagerduty", Name: "PagerDuty", AuthSchemes: []string{"OAUTH2", "BEARER_TOKEN"}},+ {Slug: "salesforce", Name: "Salesforce", AuthSchemes: []string{"oauth2"}},+ {Slug: "hackernews", Name: "Hacker News", NoAuth: true, AuthSchemes: []string{"no_auth"}},+ {Slug: "zendesk", Name: "Zendesk", AuthSchemes: []string{"api_key", "basic"}},+ {Slug: "freshdesk", Name: "Freshdesk", AuthSchemes: []string{"api_key"}},+ },+ }, projectFields: map[string]string{"zendesk": "api_key", "freshdesk": "api_key"}}+}++func TestListToolkits_SurfacesKeyToolkits(t *testing.T) {+ t.Parallel()+ svc := newTestService(t, keyCreatingSDK{newCatalogFake()}, newFakeStore())+ tks, err := svc.ListToolkits(context.Background())+ if err != nil {+ t.Fatalf("ListToolkits: %v", err)+ }+ got := map[string]ToolkitView{}+ order := []string{}+ for _, tk := range tks {+ got[tk.Slug] = tk+ order = append(order, tk.Slug)+ }+ // salesforce needs our own OAuth app and hackernews needs no account:+ // neither can be connected, so neither is listed.+ want := map[string]string{+ "slack": ConnectOAuth,+ "sendgrid": ConnectKey,+ "github": ConnectOAuth,+ "tavily": ConnectKey,+ "pagerduty": ConnectKey,+ "zendesk": ConnectKey,+ "freshdesk": ConnectKey,+ }+ if len(got) != len(want) {+ t.Fatalf("listed %v, want %d toolkits", order, len(want))+ }+ for slug, method := range want {+ if got[slug].ConnectMethod != method {+ t.Errorf("%s connect method = %q, want %q", slug, got[slug].ConnectMethod, method)+ }+ }+ if tv := got["tavily"]; tv.Category != "AI & Machine Learning" || tv.CategoryID != "ai-machine-learning" {+ t.Errorf("tavily category = %q / %q", tv.Category, tv.CategoryID)+ }+}++func TestListToolkits_KeyToolkitsNeedCustomAuthSupport(t *testing.T) {+ t.Parallel()+ svc := newTestService(t, newCatalogFake(), newFakeStore())+ tks, err := svc.ListToolkits(context.Background())+ if err != nil {+ t.Fatalf("ListToolkits: %v", err)+ }+ for _, tk := range tks {+ if tk.Slug == "tavily" || tk.Slug == "pagerduty" {+ t.Errorf("%s listed although no key config can be created for it", tk.Slug)+ }+ }+}++func TestEnsureAuthConfig_CreatesPerToolkitKind(t *testing.T) {+ t.Parallel()+ fake := newCatalogFake()+ svc := newTestService(t, keyCreatingSDK{fake}, newFakeStore())+ ctx := context.Background()++ cases := []struct {+ slug string+ want string+ }{+ {"sendgrid", "ac_sendgrid"},+ {"github", "ac_managed_github"},+ {"tavily", "ac_API_KEY_tavily"},+ {"pagerduty", "ac_BEARER_TOKEN_pagerduty"},+ // Its API_KEY config would need a project-level field.+ {"zendesk", "ac_BASIC_zendesk"},+ }+ for _, tc := range cases {+ id, err := svc.ensureAuthConfig(ctx, tc.slug)+ if err != nil || id != tc.want {+ t.Errorf("ensureAuthConfig(%s) = %q, %v; want %q", tc.slug, id, err, tc.want)+ }+ }+ for _, slug := range []string{"salesforce", "hackernews", "freshdesk", "unknown"} {+ if _, err := svc.ensureAuthConfig(ctx, slug); !errors.Is(err, ErrToolkitNotSupported) {+ t.Errorf("ensureAuthConfig(%s) err = %v, want ErrToolkitNotSupported", slug, err)+ }+ }+ if fake.custom["tavily"] != "Tavily" {+ t.Errorf("custom config name = %q, want the toolkit name", fake.custom["tavily"])+ }++ // A second connect reuses the config the first one created.+ fake.created = nil+ if id, err := svc.ensureAuthConfig(ctx, "tavily"); err != nil || id != "ac_API_KEY_tavily" || len(fake.created) != 0 {+ t.Errorf("second ensureAuthConfig = %q, %v; created %v", id, err, fake.created)+ }+ tks, err := svc.ListToolkits(ctx)+ if err != nil {+ t.Fatalf("ListToolkits: %v", err)+ }+ for _, tk := range tks {+ if tk.Slug == "tavily" && tk.ConnectMethod != ConnectKey {+ t.Errorf("tavily connect method after its config exists = %q", tk.ConnectMethod)+ }+ }+}++func TestEnsureAuthConfig_KeyToolkitWithoutCustomAuthSupport(t *testing.T) {+ t.Parallel()+ svc := newTestService(t, newCatalogFake(), newFakeStore())+ if _, err := svc.ensureAuthConfig(context.Background(), "tavily"); !errors.Is(err, ErrToolkitNotSupported) {+ t.Fatalf("err = %v, want ErrToolkitNotSupported", err)+ }+}diff --git a/server/internal/integrations/composio/service.go b/server/internal/integrations/composio/service.goindex a5f90adf50..928e6f2f5c 100644--- a/server/internal/integrations/composio/service.go+++ b/server/internal/integrations/composio/service.go@@ -18,6 +18,7 @@ import ("errors""fmt""net/url"+ "slices""strings""sync""time"@@ -130,14 +131,14 @@ type Service struct {stateTTL time.Durationnow func() time.Time- // authCache holds the resolved toolkit_slug → auth_config_id map for the+ // authCache holds the resolved toolkit_slug → auth config map for the// project. It is rebuilt from Composio's /auth_configs endpoint on first// use and whenever authCacheExp has passed; authCacheMu guards both fields.authCacheMu sync.Mutex- authCache map[string]string+ authCache map[string]authConfigRefauthCacheExp time.TimeauthCacheTTL time.Duration- // authCreateMu serializes creating managed auth configs so two concurrent+ // authCreateMu serializes creating auth configs so two concurrent// connects for the same new app do not register two configs.authCreateMu sync.Mutextools toolCache@@ -221,7 +222,58 @@ type ToolkitView struct {Name string `json:"name"`LogoURL string `json:"logo,omitempty"`Category string `json:"category,omitempty"`+ CategoryID string `json:"category_id,omitempty"`Connectable bool `json:"connectable"`+ // ConnectMethod is how a member connects an account: ConnectOAuth or+ // ConnectKey.+ ConnectMethod string `json:"connect_method,omitempty"`+}++// How a member connects an account for a toolkit.+const (+ // ConnectOAuth signs in on the provider's consent screen.+ ConnectOAuth = "oauth"+ // ConnectKey enters an API key, token, or username and password on the+ // hosted Connect Link page.+ ConnectKey = "key"+)++// userKeySchemes are the auth schemes whose credentials a member enters+// themselves on the Connect Link page, in order of preference.+var userKeySchemes = []string{"API_KEY", "BEARER_TOKEN", "BASIC"}++// userKeyScheme returns the scheme to register for a toolkit a member connects+// with their own credentials, or "" when it offers none. A scheme whose auth+// config needs a project-level value does not count: Multica has none to give.+func userKeyScheme(tk sdk.Toolkit) string {+ if tk.NoAuth {+ return ""+ }+ modes := tk.AuthModes()+ for _, want := range userKeySchemes {+ for _, have := range modes {+ if strings.EqualFold(strings.TrimSpace(have), want) && !tk.NeedsProjectCredentials(want) {+ return want+ }+ }+ }+ return ""+}++// connectMethodFor reports how members connect a toolkit: through its+// existing auth config when the project has one, else through the config+// ensureAuthConfig would create.+func connectMethodFor(tk sdk.Toolkit, existing authConfigRef) string {+ if existing.ID != "" && existing.Scheme != "" {+ if slices.ContainsFunc(userKeySchemes, func(s string) bool { return strings.EqualFold(s, existing.Scheme) }) {+ return ConnectKey+ }+ return ConnectOAuth+ }+ if existing.ID == "" && len(tk.ComposioManagedAuthSchemes) == 0 && userKeyScheme(tk) != "" {+ return ConnectKey+ }+ return ConnectOAuth}func toolkitLogoURL(slug, upstreamLogoURL string) string {@@ -560,14 +612,14 @@ func rowToConnection(row db.UserComposioConnection) Connection {}// ListToolkits returns only the Composio toolkits the project can actually-// connect (those with an enabled auth config). Toolkits with no enabled auth-// config are filtered out entirely (MUL-4009): a card the user can't act on is-// noise, and the old "Not configured" grey label existed only to avoid a dead-// button — dropping the entry removes the need for it. It fetches all pages-// (capped by maxToolkitPages) so the UI gets the complete connectable list in-// one call; the catalog is a few hundred entries, well within a single JSON-// response. Every returned entry has Connectable == true, preserving Composio's-// usage order.+// connect: those with an enabled auth config, a Composio-managed app, or a+// credential each member enters themselves (API key, token, Basic), for which+// ensureAuthConfig registers a config on first connect. The rest are filtered+// out entirely (MUL-4009): a card the user can't act on is noise. It fetches+// all pages (capped by maxToolkitPages) so the UI gets the complete+// connectable list in one call; the catalog is under two thousand entries,+// well within a single JSON response. Every returned entry has Connectable ==+// true, preserving Composio's usage order.//// Unlike the previous behavior, a resolver error is NOT masked into an// everything-not-connectable catalog: with filtering in place that would render@@ -582,6 +634,7 @@ func (s *Service) ListToolkits(ctx context.Context) ([]ToolkitView, error) {if err != nil {return nil, fmt.Errorf("composio: resolve connectable toolkits: %w", err)}+ _, canCreateKeyConfigs := s.sdk.(customAuthCreator)out := []ToolkitView{}seen := make(map[string]struct{})@@ -604,24 +657,26 @@ func (s *Service) ListToolkits(ctx context.Context) ([]ToolkitView, error) {continue}seen[slug] = struct{}{}- // Filter out toolkits with no enabled auth config: the user has no- // working action for them, so they are omitted from the catalog.- if _, canConnect := connectable[slug]; !canConnect && len(tk.ComposioManagedAuthSchemes) == 0 {+ // Omit toolkits nobody can connect: no enabled auth config, no+ // Composio-managed app, and no credential a member enters+ // themselves.+ existing, hasConfig := connectable[slug]+ if !hasConfig && len(tk.ComposioManagedAuthSchemes) == 0 &&+ (!canCreateKeyConfigs || userKeyScheme(tk) == "") {continue}- category := ""- if len(tk.Categories) > 0 {- category = tk.Categories[0]- }+ category := tk.PrimaryCategory()out = append(out, ToolkitView{- Slug: tk.Slug,- Name: tk.Name,- LogoURL: toolkitLogoURL(slug, tk.LogoURL),- Category: category,+ Slug: tk.Slug,+ Name: tk.Name,+ LogoURL: toolkitLogoURL(slug, tk.LogoURL),+ Category: category.Name,+ CategoryID: category.ID,// Every surfaced toolkit is connectable by construction. The// wire field is kept (see ComposioToolkitResponse) for backward// compatibility with older desktop clients that branch on it.- Connectable: true,+ Connectable: true,+ ConnectMethod: connectMethodFor(tk, existing),})}if resp.NextCursor == "" {@@ -645,16 +700,24 @@ func (s *Service) authConfigForToolkit(ctx context.Context, slug string) (stringif err != nil {return "", err}- return m[slug], nil+ return m[slug].ID, nil+}++// authConfigRef is the auth config chosen to represent a toolkit.+type authConfigRef struct {+ ID string+ // Scheme is the config's auth scheme as Composio reports it (OAUTH2,+ // API_KEY, ...); empty when unknown.+ Scheme string}-// authConfigMap returns the toolkit_slug → auth_config_id map for the project,+// authConfigMap returns the toolkit_slug → auth config map for the project,// rebuilding it from Composio when the cache is empty or expired. Concurrent// callers serialize on authCacheMu; the fetch runs under the lock, which is// acceptable for a short-TTL map that is cheap to build and read by a// low-traffic settings surface. A new map is assigned on refresh (never mutated// in place), so a reference handed to a caller stays safe to read.-func (s *Service) authConfigMap(ctx context.Context) (map[string]string, error) {+func (s *Service) authConfigMap(ctx context.Context) (map[string]authConfigRef, error) {s.authCacheMu.Lock()defer s.authCacheMu.Unlock()if s.authCache != nil && s.now().Before(s.authCacheExp) {@@ -678,15 +741,16 @@ func (s *Service) authConfigMap(ctx context.Context) (map[string]string, error)// during resolution.type authCandidate struct {id string+ scheme stringmanaged boolupdated string}// fetchAuthConfigMap pages through the project's ENABLED auth configs and-// reduces them to one chosen auth_config_id per toolkit slug. When a toolkit+// reduces them to one chosen auth config per toolkit slug. When a toolkit// has several (e.g. a Composio-managed one plus a custom white-label one),// betterAuthConfig picks the winner.-func (s *Service) fetchAuthConfigMap(ctx context.Context) (map[string]string, error) {+func (s *Service) fetchAuthConfigMap(ctx context.Context) (map[string]authConfigRef, error) {best := make(map[string]authCandidate)cursor := ""for page := 0; page < maxAuthConfigPages; page++ {@@ -706,7 +770,7 @@ func (s *Service) fetchAuthConfigMap(ctx context.Context) (map[string]string, erif slug == "" {continue}- cand := authCandidate{id: ac.ID, managed: ac.IsComposioManaged, updated: ac.LastUpdatedAt}+ cand := authCandidate{id: ac.ID, scheme: ac.AuthScheme, managed: ac.IsComposioManaged, updated: ac.LastUpdatedAt}if cur, ok := best[slug]; !ok || betterAuthConfig(cand, cur) {best[slug] = cand}@@ -716,9 +780,9 @@ func (s *Service) fetchAuthConfigMap(ctx context.Context) (map[string]string, er}cursor = resp.NextCursor}- out := make(map[string]string, len(best))+ out := make(map[string]authConfigRef, len(best))for slug, c := range best {- out[slug] = c.id+ out[slug] = authConfigRef{ID: c.id, Scheme: c.scheme}}return out, nil}diff --git a/server/internal/integrations/composio/team.go b/server/internal/integrations/composio/team.goindex 5d67b3fd40..2682ed1d00 100644--- a/server/internal/integrations/composio/team.go+++ b/server/internal/integrations/composio/team.go@@ -229,10 +229,18 @@ func (s *Service) revokeUpstream(ctx context.Context, connectedAccountID string)_ = s.sdk.DeleteConnectedAccount(ctx, connectedAccountID)}-// ensureAuthConfig returns the toolkit's auth config, creating one with-// Composio's managed app when the project has none and the toolkit offers-// managed auth. This is what lets every catalog app connect without a-// dashboard step.+// customAuthCreator is the part of *sdk.Client that registers an auth config+// whose credentials each member enters on the Connect Link page. It is+// separate from ToolSDK so fakes written before it keep working.+type customAuthCreator interface {+ CreateCustomAuthConfig(ctx context.Context, toolkitSlug, authScheme, name string) (string, error)+}++// ensureAuthConfig returns the toolkit's auth config, creating one when the+// project has none: with Composio's managed app when the toolkit offers one,+// else with no credentials for a toolkit members connect with their own API+// key, token, or Basic login. This is what lets every catalog app connect+// without a dashboard step.func (s *Service) ensureAuthConfig(ctx context.Context, slug string) (string, error) {id, err := s.authConfigForToolkit(ctx, slug)if err != nil || id != "" {@@ -249,7 +257,10 @@ func (s *Service) ensureAuthConfig(ctx context.Context, slug string) (string, er}return "", fmt.Errorf("composio: get toolkit: %w", err)}- if len(tk.ComposioManagedAuthSchemes) == 0 {+ managed := len(tk.ComposioManagedAuthSchemes) > 0+ keyScheme := userKeyScheme(*tk)+ creator, canCreateKeyConfigs := s.sdk.(customAuthCreator)+ if !managed && (keyScheme == "" || !canCreateKeyConfigs) {return "", ErrToolkitNotSupported}s.authCreateMu.Lock()@@ -259,9 +270,20 @@ func (s *Service) ensureAuthConfig(ctx context.Context, slug string) (string, erif id, err := s.authConfigForToolkit(ctx, slug); err != nil || id != "" {return id, err}- id, err = tools.CreateManagedAuthConfig(ctx, slug)- if err != nil {- return "", fmt.Errorf("composio: create managed auth config: %w", err)+ if managed {+ id, err = tools.CreateManagedAuthConfig(ctx, slug)+ if err != nil {+ return "", fmt.Errorf("composio: create managed auth config: %w", err)+ }+ } else {+ name := tk.Name+ if name == "" {+ name = slug+ }+ id, err = creator.CreateCustomAuthConfig(ctx, slug, keyScheme, name)+ if err != nil {+ return "", fmt.Errorf("composio: create %s auth config: %w", keyScheme, err)+ }}s.invalidateAuthConfigs()return id, nildiff --git a/server/pkg/composio/auth_configs.go b/server/pkg/composio/auth_configs.goindex 77a8c0dee5..ed37a544f1 100644--- a/server/pkg/composio/auth_configs.go+++ b/server/pkg/composio/auth_configs.go@@ -96,6 +96,47 @@ func (c *Client) CreateManagedAuthConfig(ctx context.Context, toolkitSlug stringreturn out.AuthConfig.ID, nil}+type createCustomAuthConfigRequest struct {+ Toolkit createAuthConfigToolkit `json:"toolkit"`+ AuthConfig customAuthConfigBody `json:"auth_config"`+}++type customAuthConfigBody struct {+ Type string `json:"type"`+ AuthScheme string `json:"authScheme"`+ Name string `json:"name,omitempty"`+ Credentials map[string]any `json:"credentials"`+}++// CreateCustomAuthConfig registers an auth config with the given scheme+// (API_KEY, BEARER_TOKEN, BASIC) and no project credentials, so each user+// enters their own on the hosted Connect Link page. It returns the new+// auth_config_id.+//+// Spec: https://docs.composio.dev/reference/v3/api-reference/auth-configs/postAuthConfigs+func (c *Client) CreateCustomAuthConfig(ctx context.Context, toolkitSlug, authScheme, name string) (string, error) {+ if toolkitSlug == "" || authScheme == "" {+ return "", errors.New("composio: CreateCustomAuthConfig: toolkitSlug and authScheme are required")+ }+ var out createAuthConfigResponse+ body := createCustomAuthConfigRequest{+ Toolkit: createAuthConfigToolkit{Slug: toolkitSlug},+ AuthConfig: customAuthConfigBody{+ Type: "use_custom_auth",+ AuthScheme: strings.ToUpper(authScheme),+ Name: name,+ Credentials: map[string]any{},+ },+ }+ if err := c.do(c.newRequest(ctx).SetBody(body), http.MethodPost, "/auth_configs", &out); err != nil {+ return "", err+ }+ if out.AuthConfig.ID == "" {+ return "", errors.New("composio: CreateCustomAuthConfig: response has no auth config id")+ }+ return out.AuthConfig.ID, nil+}+// ListAuthConfigs returns the auth configs registered in the project, with// optional filters. The project is resolved from the x-api-key (a project API// key authenticates to exactly one project), so no project id is passed.diff --git a/server/pkg/composio/client_test.go b/server/pkg/composio/client_test.goindex 1f507dadba..23b92ff635 100644--- a/server/pkg/composio/client_test.go+++ b/server/pkg/composio/client_test.go@@ -7,6 +7,7 @@ import ("io""net/http""net/http/httptest"+ "reflect""strings""sync""testing"@@ -457,6 +458,97 @@ func TestListToolkits_Success(t *testing.T) {}}+func TestToolkitPrimaryCategory(t *testing.T) {+ var listed composio.ListToolkitsResponse+ raw := `{"items":[+ {"slug":"github","meta":{"categories":[{"id":"developer-tools","name":"Developer Tools"},{"id":"productivity","name":"Productivity"}]}},+ {"slug":"legacy","categories":["email"],"meta":{"categories":[{"id":"ignored","name":"Ignored"}]}},+ {"slug":"bare"}+ ]}`+ if err := json.Unmarshal([]byte(raw), &listed); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ want := []composio.ToolkitCategory{+ {ID: "developer-tools", Name: "Developer Tools"},+ {Name: "email"},+ {},+ }+ for i, tk := range listed.Items {+ if got := tk.PrimaryCategory(); got != want[i] {+ t.Errorf("%s: PrimaryCategory = %+v, want %+v", tk.Slug, got, want[i])+ }+ }+}++// GET /toolkits/{slug} reports auth schemes only as auth_config_details.+func TestGetToolkit_AuthModesFromDetails(t *testing.T) {+ c, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Path != "/toolkits/openai" {+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ }+ w.Header().Set("Content-Type", "application/json")+ _, _ = w.Write([]byte(`{+ "slug": "openai", "name": "OpenAI", "composio_managed_auth_schemes": [],+ "meta": {"categories": [{"id": "ai-machine-learning", "name": "AI & Machine Learning"}]},+ "auth_config_details": [+ {"mode": "API_KEY", "name": "openai_api_key", "fields": {+ "auth_config_creation": {"required": [], "optional": []},+ "connected_account_initiation": {"required": [{"name": "generic_api_key", "displayName": "API Key", "type": "string", "required": true, "default": null}], "optional": []}+ }},+ {"mode": "BASIC", "fields": {+ "auth_config_creation": {"required": [{"name": "subdomain", "type": "string", "required": true, "default": null}]}+ }},+ {"mode": "BEARER_TOKEN", "fields": {+ "auth_config_creation": {"required": [{"name": "region", "type": "string", "required": true, "default": "us"}]}+ }}+ ]+ }`))+ })+ tk, err := c.GetToolkit(context.Background(), "openai")+ if err != nil {+ t.Fatalf("GetToolkit: %v", err)+ }+ if got, want := tk.AuthModes(), []string{"API_KEY", "BASIC", "BEARER_TOKEN"}; !reflect.DeepEqual(got, want) {+ t.Errorf("AuthModes = %v, want %v", got, want)+ }+ for mode, want := range map[string]bool{"api_key": false, "BASIC": true, "BEARER_TOKEN": false, "OAUTH2": false} {+ if got := tk.NeedsProjectCredentials(mode); got != want {+ t.Errorf("NeedsProjectCredentials(%s) = %v, want %v", mode, got, want)+ }+ }+ listed := composio.Toolkit{AuthSchemes: []string{"oauth2"}, AuthConfigDetails: tk.AuthConfigDetails}+ if got := listed.AuthModes(); !reflect.DeepEqual(got, []string{"oauth2"}) {+ t.Errorf("AuthModes prefers auth_schemes, got %v", got)+ }+}++func TestCreateCustomAuthConfig_Body(t *testing.T) {+ c, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {+ if r.Method != http.MethodPost || r.URL.Path != "/auth_configs" {+ t.Errorf("unexpected request: %s %s", r.Method, r.URL.Path)+ }+ var body map[string]any+ readJSON(t, r, &body)+ want := map[string]any{+ "toolkit": map[string]any{"slug": "tavily"},+ "auth_config": map[string]any{+ "type": "use_custom_auth",+ "authScheme": "API_KEY",+ "name": "Tavily",+ "credentials": map[string]any{},+ },+ }+ if !reflect.DeepEqual(body, want) {+ t.Errorf("body = %#v, want %#v", body, want)+ }+ writeJSON(t, w, http.StatusCreated, map[string]any{"auth_config": map[string]any{"id": "ac_tavily"}})+ })+ id, err := c.CreateCustomAuthConfig(context.Background(), "tavily", "api_key", "Tavily")+ if err != nil || id != "ac_tavily" {+ t.Fatalf("CreateCustomAuthConfig = %q, %v", id, err)+ }+}+func TestGetToolkit_Success(t *testing.T) {c, _ := newTestServer(t, func(w http.ResponseWriter, r *http.Request) {if r.URL.Path != "/toolkits/notion" {diff --git a/server/pkg/composio/toolkits.go b/server/pkg/composio/toolkits.goindex 3e1ee1b42c..1a961a4b5c 100644--- a/server/pkg/composio/toolkits.go+++ b/server/pkg/composio/toolkits.go@@ -6,6 +6,7 @@ import ("net/http""net/url""strconv"+ "strings")// Toolkit is the minimal toolkit descriptor used as a nested field inside@@ -25,6 +26,89 @@ type Toolkit struct {ComposioManagedAuthSchemes []string `json:"composio_managed_auth_schemes,omitempty"`// NoAuth is true for toolkits that need no credential at all.NoAuth bool `json:"no_auth,omitempty"`+ // AuthConfigDetails describes each auth scheme. GET /toolkits/{slug}+ // reports schemes only here, without auth_schemes or no_auth.+ AuthConfigDetails []ToolkitAuthConfigDetail `json:"auth_config_details,omitempty"`+}++// ToolkitAuthConfigDetail is one auth scheme of a toolkit and the fields it+// needs.+type ToolkitAuthConfigDetail struct {+ Mode string `json:"mode"`+ Fields struct {+ AuthConfigCreation struct {+ Required []ToolkitAuthField `json:"required"`+ } `json:"auth_config_creation"`+ } `json:"fields"`+}++// ToolkitAuthField is a credential field of an auth scheme.+type ToolkitAuthField struct {+ Name string `json:"name"`+ Default *string `json:"default"`+}++// AuthModes returns the auth schemes the toolkit offers, from auth_schemes+// (the list endpoint) or else auth_config_details (GET /toolkits/{slug}).+func (t Toolkit) AuthModes() []string {+ if len(t.AuthSchemes) > 0 {+ return t.AuthSchemes+ }+ modes := make([]string, 0, len(t.AuthConfigDetails))+ for _, d := range t.AuthConfigDetails {+ if d.Mode != "" {+ modes = append(modes, d.Mode)+ }+ }+ return modes+}++// NeedsProjectCredentials reports whether an auth config for mode can only be+// created with a project-level value, i.e. a required field with no default.+// It is false when the toolkit carries no details for mode.+func (t Toolkit) NeedsProjectCredentials(mode string) bool {+ for _, d := range t.AuthConfigDetails {+ if !strings.EqualFold(d.Mode, mode) {+ continue+ }+ for _, f := range d.Fields.AuthConfigCreation.Required {+ if f.Default == nil || *f.Default == "" {+ return true+ }+ }+ }+ return false+}++// ToolkitCategory is one category a toolkit is listed under.+type ToolkitCategory struct {+ ID string+ Name string+}++// PrimaryCategory returns the first category the toolkit is listed under, or+// a zero value when it has none. The v3.1 list endpoint nests categories under+// meta as {id, name} objects; a top-level list of names is read first.+func (t Toolkit) PrimaryCategory() ToolkitCategory {+ if len(t.Categories) > 0 {+ return ToolkitCategory{Name: t.Categories[0]}+ }+ list, _ := t.Meta["categories"].([]any)+ for _, item := range list {+ switch v := item.(type) {+ case string:+ if v != "" {+ return ToolkitCategory{Name: v}+ }+ case map[string]any:+ id, _ := v["id"].(string)+ name, _ := v["name"].(string)+ if id != "" || name != "" {+ return ToolkitCategory{ID: id, Name: name}+ }+ }+ }+ return ToolkitCategory{}}// ListToolkitsRequest carries the optional filters of GET /toolkits.