Files
PaperClipAI/server/src/services/composio-app-setup.ts
T
marshallandDotta 68e92bcd5d fix(composio): return the sign-in link when adding a second account (#19408)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A Composio gateway lets one person connect several accounts of the
same app, for example 3 Gmail accounts, through the Connectors "Add
account" action
> - `POST /api/tool-connections/{id}/composio/apps/{toolkit}/accounts`
with `{"action":"add"}` must return a hosted sign-in link for the new
account
> - When the app already has an active account, the call always fails
with "Composio did not return a sign-in link. Check the app in
Composio."
> - The add reply lists the app's existing accounts beside the new link.
The shared setup parser sees an active account, returns `connected`, and
drops the link
> - This pull request reads the new link directly for an add, after the
same provider-error check
> - The benefit is that people can add a second or third account to a
Composio app from Paperclip

## Linked Issues or Issue Description

**What happened?**
On a managed instance, a Composio gateway had Gmail and Google Calendar
connected for one Google account. "Add account" for a second account
returned HTTP 422 with "Composio did not return a sign-in link. Check
the app in Composio." The setup `start` action returns only
`{"status":"connected"}` for an app that has an account, so no Paperclip
path gave a link for another account.

**Expected behavior**
"Add account" returns a `connect.composio.dev/link/...` sign-in link for
a new account, also when the app already has an active account.

**Steps to reproduce**
1. Connect a Composio gateway and connect one Gmail account.
2. Call `POST /api/tool-connections/{id}/composio/apps/gmail/accounts`
with `{"action":"add"}`, or use "Add account" on the Connectors page.
3. The response is 422 "Composio did not return a sign-in link".

**Root cause**
`manageComposioAppAccount` used `composioAppSetupResult` for the add
reply. That function returns `{ status: "connected" }` as soon as any
entry for the toolkit has status `ACTIVE`, before it looks for a link.
The existing test fixture returned only `{ redirect_url }` for an add,
so it did not include the existing accounts that the live gateway
returns.

Related: #19380 (Connectors page CPU fix). That PR fixes the page that
holds the "Add account" button. This PR fixes the API call behind the
button.

## What Changed

- `server/src/services/composio-app-setup.ts`: add
`composioAddAccountLink(response)`. It runs the same provider-error
check as the other parsers, then returns the first trusted
`connect.composio.dev/link/` URL from the reply.
- `server/src/services/tool-access/catalog/aggregator-accounts.ts`: for
`action: "add"`, use `composioAddAccountLink` and return `{ status:
"authorization_required", authorizationUrl }`. Rename and remove do not
change.
- `server/src/__tests__/composio-add-account-link.test.ts`: new tests
for a reply with an active account plus a new link, a reply without a
trusted link, and a provider failure.

## Verification

- `cd server && npx vitest run
src/__tests__/composio-add-account-link.test.ts
src/__tests__/composio-app-setup.test.ts
src/__tests__/aggregator-app-discovery.test.ts`: all pass.
- Red before the fix: I changed the add reply in the `direct Composio
setup` fixture so it lists the toolkit's accounts beside the link, as
the live gateway does. On the unchanged service, "adds another account
without a task or an agent grant, even when an account is already
active" failed with `Error: Composio did not return a sign-in link.
Check the app in Composio.` With the fix, it passed. That fixture change
is not in this PR, to keep the diff small. The new unit test covers the
same reply shape.
- I did not get a live link from Composio with this change, because it
is not deployed. Before the fix, the live API call returned the 422
above.
- I could not run a full server `tsc` in my sandbox (out of memory). CI
runs it.

## Risks

- Low. Only the `add` action changes. It still rejects provider errors
first, and it accepts only trusted Composio hosted links
(`extractRemoteMcpPending`).
- An add reply that has no link still returns the same 422 as before.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use (shell, file editing, test execution).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Dotta <bippadotta@protonmail.com>
2026-11-25 15:31:27 -06:00

134 lines
7.1 KiB
TypeScript

import type { ComposioAppAccount, ComposioAppSetupResult } from "@paperclipai/shared";
import { extractRemoteMcpPending } from "./remote-mcp-pending.js";
import { unprocessable } from "../errors.js";
import { checkOAuthEndpointUrl } from "@paperclipai/shared";
function record(value: unknown): Record<string, unknown> | null {
return value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : null;
}
function payloadsFrom(response: unknown) {
const root = record(response);
const result = record(root?.result) ?? root;
const payloads = [result, record(result?.structuredContent)];
if (Array.isArray(result?.content)) {
for (const item of result.content) {
const block = record(item);
if (block?.type !== "text" || typeof block.text !== "string") continue;
try { payloads.push(record(JSON.parse(block.text))); } catch { /* Plain text is not proof. */ }
}
}
if (root?.error || result?.isError === true || payloads.some(p => p?.successful === false || p?.success === false || p?.error)) {
throw unprocessable("Composio could not configure this app. Check the app in Composio and try again.");
}
return payloads;
}
/** Retain only account identity and status, never raw provider results or credentials. */
export function composioAppAccounts(response: unknown, toolkit: string): ComposioAppAccount[] | undefined {
const accounts = new Map<string, ComposioAppAccount>();
let observed = false;
let incomplete = false;
let visited = 0;
function visit(value: unknown, matched: boolean, depth: number) {
if (++visited > 20_000 || depth > 12) { incomplete = true; return; }
if (Array.isArray(value)) { value.forEach(item => visit(item, matched, depth + 1)); return; }
const entry = record(value);
if (!entry) return;
const named = entry.toolkit ?? entry.toolkit_name ?? entry.toolkit_slug;
const selected = matched || named === toolkit || record(named)?.slug === toolkit;
if (selected && (entry.error || entry.success === false || entry.successful === false)) {
throw unprocessable("Composio could not check this app. Refresh its accounts before trying again.");
}
if (selected && Array.isArray(entry.accounts)) {
observed = true;
for (const item of entry.accounts) {
const account = record(item);
const id = account?.id ?? account?.account_id ?? account?.connected_account_id;
if (typeof id !== "string" || !id || id.length > 200) { incomplete = true; continue; }
accounts.set(id, { id, alias: typeof account?.alias === "string" ? account.alias.slice(0, 100) : null,
status: typeof account?.status === "string" ? account.status.toUpperCase().slice(0, 40) : "UNKNOWN",
isDefault: account?.is_default === true || account?.isDefault === true });
}
}
for (const [key, child] of Object.entries(entry)) visit(child, selected || key === toolkit, depth + 1);
}
payloadsFrom(response).forEach(payload => visit(payload, false, 0));
return observed && !incomplete ? [...accounts.values()] : undefined;
}
export function composioAddAccountLink(response: unknown): string | null {
payloadsFrom(response);
return extractRemoteMcpPending(response, "composio", "COMPOSIO_MANAGE_CONNECTIONS")?.links[0]?.url ?? null;
}
/** Only the requested toolkit can establish success; other accounts are unrelated. */
export function composioAppSetupResult(response: unknown, toolkit: string): ComposioAppSetupResult {
const payloads = payloadsFrom(response);
let connected = false;
let visited = 0;
const visit = (value: unknown, matched: boolean, depth: number) => {
if (++visited > 20_000 || depth > 12) return;
if (Array.isArray(value)) { value.forEach(item => visit(item, matched, depth + 1)); return; }
const entry = record(value);
if (!entry) return;
const named = entry.toolkit ?? entry.toolkit_name ?? entry.toolkit_slug ?? entry.name;
const selected = matched || named === toolkit || record(named)?.slug === toolkit;
if (selected && (typeof entry.status === "string" && entry.status.toUpperCase() === "ACTIVE" || entry.connected === true)) connected = true;
for (const [key, child] of Object.entries(entry)) visit(child, selected || key === toolkit, depth + 1);
};
payloads.forEach(payload => visit(payload, false, 0));
if (connected) return { status: "connected" };
const url = extractRemoteMcpPending(response, "composio", "COMPOSIO_MANAGE_CONNECTIONS")?.links[0]?.url;
return url ? { status: "authorization_required", authorizationUrl: url } : { status: "not_connected" };
}
export type ComposioAddOutcome = "connected" | "authorization_required" | "failed";
function isComposioLink(value: unknown) {
const checked = checkOAuthEndpointUrl(value);
return checked.ok && checked.host === "connect.composio.dev" && new URL(checked.url).pathname.startsWith("/link/");
}
/**
* Outcome of each toolkit in one `COMPOSIO_MANAGE_CONNECTIONS` add response,
* read from that toolkit's own result node: an active account is connected,
* its own sign-in link is authorization_required, and an error or no node is
* failed. A sibling's link never counts. Only when exactly one toolkit was
* added does a link elsewhere in the response count for it, as in
* `composioAppSetupResult`. A protocol or provider error fails every toolkit.
*/
export function composioAddOutcomes(response: unknown, toolkits: readonly string[]): Map<string, ComposioAddOutcome> {
const outcomes = new Map<string, ComposioAddOutcome>();
let payloads: (Record<string, unknown> | null)[];
try { payloads = payloadsFrom(response); } catch {
for (const toolkit of toolkits) outcomes.set(toolkit, "failed");
return outcomes;
}
for (const toolkit of new Set(toolkits)) {
let connected = false;
let link = false;
let failed = false;
let visited = 0;
const visit = (value: unknown, matched: boolean, depth: number) => {
if (++visited > 20_000 || depth > 12) return;
if (Array.isArray(value)) { value.forEach(item => visit(item, matched, depth + 1)); return; }
const entry = record(value);
if (!entry) return;
const named = entry.toolkit ?? entry.toolkit_name ?? entry.toolkit_slug ?? entry.name;
const selected = matched || named === toolkit || record(named)?.slug === toolkit;
if (selected) {
if (entry.error || entry.success === false || entry.successful === false) failed = true;
if (typeof entry.status === "string" && entry.status.toUpperCase() === "ACTIVE" || entry.connected === true) connected = true;
if (isComposioLink(entry.redirect_url)) link = true;
}
for (const [key, child] of Object.entries(entry)) visit(child, selected || key === toolkit, depth + 1);
};
payloads.forEach(payload => visit(payload, false, 0));
const fallbackLink = !failed && !connected && !link && toolkits.length === 1
&& Boolean(extractRemoteMcpPending(response, "composio", "COMPOSIO_MANAGE_CONNECTIONS")?.links.length);
outcomes.set(toolkit, failed ? "failed" : connected ? "connected" : link || fallbackLink ? "authorization_required" : "failed");
}
return outcomes;
}