fix(telemetry): scope Composio add outcomes to each app and dedupe link events

Review follow-up. composioAppSetupResult falls back to the first sign-in
link anywhere in the response, so in a multi-app add a sibling's link
marked an absent or errored app as needs_auth. Add composioAddOutcomes,
which parses the response once and reads each toolkit's own result
node: connected is succeeded, its own link is needs_auth, and an error
or no node is failed. The response-wide link counts only when exactly
one app was added. An MCP-level or provider error fails every app.

The Composio list check compared every write with the status read
before the batch, so a toolkit named twice (refreshAggregatorApps passes
names through) sent two app_linked events for one change. Update the
previous status after each committed write.

Tested: connector-telemetry unit tests (sibling link, top-level link
with several apps, single-app fallback), a composio-app-setup case with
a repeated toolkit (fails without the fix), the partial-check case, and
the shared telemetry and remote MCP suites (163 pass).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-23 10:51:10 -06:00
1 parent febf2b81a1
commit d501fe5272
6 files changed
+95 -19

No files matched your search

+4 -2
View File
@@ -231,8 +231,10 @@ gateways. The server emits all of them through
the app setup screens (`origin: user`), or from the tool gateway when an
agent calls `COMPOSIO_MANAGE_CONNECTIONS` with `add`, or when an Arcade tool
call answers with an authorization step (`origin: agent`). `outcome` is
`needs_auth` when the provider returns a sign-in step, `succeeded` when the
app is already connected, and `failed` otherwise.
read from each app's own result: `needs_auth` when the provider returns a
sign-in step for that app, `succeeded` when the app is connected, and
`failed` otherwise. A sign-in link for another app in the same request
never counts.
## Cloud Direct Delivery
@@ -360,6 +360,13 @@ const support = await getEmbeddedPostgresTestSupport();
await expect(f.access.refreshComposioApps(f.connection.id, ["circleback_mcp", "notion"], f.actor)).rejects.toThrow();
expect(appEvents()).toEqual([["connection.app_linked", { provider: "composio", app: aggregatorAppTelemetrySlug("composio", "circleback_mcp") }]]);
});
it("emits app_linked once when the same app is named twice in one check", async () => {
const f = await fixture();
f.activate();
track.mockClear();
await f.access.refreshAggregatorApps(f.connection.id, ["circleback_mcp", "circleback_mcp"], f.actor);
expect(appEvents()).toEqual([["connection.app_linked", { provider: "composio", app: aggregatorAppTelemetrySlug("composio", "circleback_mcp") }]]);
});
it("reports a failed app request when Composio does not confirm the new account", async () => {
const f = await fixture();
f.setMutationStatus(500);
+50
View File
@@ -1,6 +1,7 @@
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;
@@ -76,3 +77,52 @@ export function composioAppSetupResult(response: unknown, toolkit: string): Comp
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;
}
@@ -438,7 +438,7 @@ describe("aggregator app events", () => {
expect(track.mock.calls).toEqual([
["connection.app_requested", { provider: "composio", app: "github", origin: "agent", outcome: "succeeded" }],
["connection.app_requested", { provider: "composio", app: "gmail", origin: "agent", outcome: "needs_auth" }],
["connection.app_requested", { provider: "composio", app: "other", origin: "agent", outcome: "needs_auth" }],
["connection.app_requested", { provider: "composio", app: "other", origin: "agent", outcome: "failed" }],
]);
track.mockClear();
emitAggregatorAppRequestsFromToolCall({ ...call, parameters: { toolkits: [{ name: "github", action: "list" }] } });
@@ -455,6 +455,25 @@ describe("aggregator app events", () => {
expect(track.mock.calls.map(([, dims]) => dims.outcome)).toEqual(["failed", "failed", "failed"]);
});
it("never lets a sibling's sign-in link or a top-level link mark another app as needs_auth", () => {
const link = "https://connect.composio.dev/link/abc";
const call = { companyId: "company-1", provider: "composio", toolName: "COMPOSIO_MANAGE_CONNECTIONS", origin: "agent" as const, pendingAuthorization: true };
emitAggregatorAppRequestsFromToolCall({ ...call,
parameters: { toolkits: [{ name: "gmail", action: "add" }, { name: "slack", action: "add" }] },
response: { jsonrpc: "2.0", id: "1", result: { structuredContent: { data: { results: { gmail: { redirect_url: link }, slack: { toolkit: "slack", error: "not enabled" } } } } } } });
emitAggregatorAppRequestsFromToolCall({ ...call,
parameters: { toolkits: [{ name: "gmail", action: "add" }, { name: "slack", action: "add" }] },
response: { jsonrpc: "2.0", id: "1", result: { structuredContent: { redirect_url: link } } } });
emitAggregatorAppRequestsFromToolCall({ ...call,
parameters: { toolkits: [{ name: "gmail", action: "add" }] },
response: { jsonrpc: "2.0", id: "1", result: { structuredContent: { redirect_url: link } } } });
expect(track.mock.calls.map(([, dims]) => `${dims.app}:${dims.outcome}`)).toEqual([
"gmail:needs_auth", "slack:failed",
"gmail:failed", "slack:failed",
"gmail:needs_auth",
]);
});
it("reports an Arcade tool call that asks for authorization as a request for its toolkit", () => {
const call = { companyId: "company-1", provider: "arcade", parameters: {}, response: {}, origin: "agent" as const };
emitAggregatorAppRequestsFromToolCall({ ...call, toolName: "Gmail_SendEmail", pendingAuthorization: true });
+9 -15
View File
@@ -12,7 +12,7 @@ import {
trackConnectionAppRequested,
} from "@paperclipai/shared/telemetry";
import { remoteEndpointValue } from "./tool-access/connection-methods.js";
import { composioAppSetupResult } from "./composio-app-setup.js";
import { composioAddOutcomes } from "./composio-app-setup.js";
import { logger } from "../middleware/logger.js";
import { getTelemetryClient } from "../telemetry.js";
import { withTelemetryCompany } from "../telemetry-company-scope.js";
@@ -414,21 +414,11 @@ function addedComposioToolkits(parameters: unknown): string[] {
});
}
/** Outcome of one toolkit in a `COMPOSIO_MANAGE_CONNECTIONS` add response, read from that toolkit's own result. */
function composioAddOutcome(response: unknown, toolkit: string): AggregatorAppRequestOutcome {
try {
const result = composioAppSetupResult(response, toolkit);
return result.status === "connected" ? "succeeded" : result.status === "authorization_required" ? "needs_auth" : "failed";
} catch {
// A provider or protocol error in the response.
return "failed";
}
}
/**
* Agent-side app requests seen by the tool gateway: a Composio
* `COMPOSIO_MANAGE_CONNECTIONS` call whose arguments add one or more
* toolkits, each with the outcome read from its own result in the response,
* toolkits, each with the outcome read from its own result node in the
* response (`composioAddOutcomes`),
* or an Arcade tool call that answered with an authorization step (the agent
* tried to use an app its person has not connected yet; the toolkit is the
* tool name's prefix, e.g. `Gmail` from `Gmail_SendEmail`). Other tools and
@@ -446,12 +436,16 @@ export function emitAggregatorAppRequestsFromToolCall(input: {
try {
if (!input.origin) return;
if (input.provider === "composio" && input.toolName === "COMPOSIO_MANAGE_CONNECTIONS") {
for (const toolkit of new Set(addedComposioToolkits(input.parameters))) {
const added = [...new Set(addedComposioToolkits(input.parameters))];
if (!added.length) return;
const outcomes = composioAddOutcomes(input.response, added);
for (const toolkit of added) {
const outcome = outcomes.get(toolkit);
emitAggregatorAppsRequested(input.companyId, {
provider: "composio",
toolkits: [toolkit],
origin: input.origin,
outcome: composioAddOutcome(input.response, toolkit),
outcome: outcome === "connected" ? "succeeded" : outcome === "authorization_required" ? "needs_auth" : "failed",
});
}
return;
@@ -181,7 +181,11 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred
.returning({ toolkit: toolConnectionAppSnapshots.toolkit });
// Emit per committed row: a later toolkit in this batch may still throw.
// A write that lost to a newer observation changed nothing and emits nothing.
if (written.length) emitAggregatorAppsLinked(connection.companyId, "composio", newlyLinkedToolkits(previous, [{ toolkit: tool.name, status }]));
if (written.length) {
emitAggregatorAppsLinked(connection.companyId, "composio", newlyLinkedToolkits(previous, [{ toolkit: tool.name, status }]));
// A repeated toolkit in the same batch compares against this write, not the stale read.
previous.set(tool.name, status);
}
}
return { payload, failedToolkits };
} catch (error) { await markFailed(); throw error; }