diff --git a/packages/shared/src/telemetry/README.md b/packages/shared/src/telemetry/README.md index 04a42702f05..0774d0bfb61 100644 --- a/packages/shared/src/telemetry/README.md +++ b/packages/shared/src/telemetry/README.md @@ -201,6 +201,41 @@ creator, else the task's responsible user, else the run owner (the acting person, the plan author, or the user who owns the model connection). A live request still wins. The self-hosted collector envelope does not change. +## Connector Events + +`connection.created`, `connection.updated`, and `connection.invoked` describe +tool connectors. `connection.app_linked` and `connection.app_requested` +describe apps reached through the Composio, Arcade, and Executor aggregator +gateways. The server emits all of them through +`server/src/services/connector-telemetry.ts`. + +- `connector_key` is a slug from the shared connector catalog. Every other + connection, including custom MCP servers and plugin connectors, sends the + literal `custom`. +- `server_domain` is sent only when `connector_key` is `custom`. It is the + registrable domain of the remote server (the ICANN public suffix plus one + label, from `tldts`), so `mcp.example.com/sse?token=...` sends `example.com`. + The path, query, port, credentials, and subdomains are never sent. IP + addresses, loopback, single-label hosts, non-ICANN or special-use suffixes + (such as `.local`, `.internal`, `.home.arpa`, `.onion`), non-HTTP schemes, + and unparsable addresses send `private`. Local stdio servers send `stdio`. A + remote connection with no address yet omits the field. +- `app` is a slug from the shared aggregator app catalog + (`aggregator-app-catalog.ts`), resolved from the provider's toolkit name. + Every other toolkit, including Executor custom integrations, sends `other`. + The provider's own app name or account name is never sent. +- `connection.app_linked` is sent when a person's cached app observation + changes to `connected` from any other status or from no observation. A + re-sync that finds the app still connected sends nothing. +- `connection.app_requested` is sent once per request to add an app: from + 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 + 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 Self-hosted installs are unchanged. They post every batch to the collector, diff --git a/packages/shared/src/telemetry/connector-events.test.ts b/packages/shared/src/telemetry/connector-events.test.ts index c060017c7a6..17509f4726c 100644 --- a/packages/shared/src/telemetry/connector-events.test.ts +++ b/packages/shared/src/telemetry/connector-events.test.ts @@ -5,6 +5,8 @@ import { trackConnectionCreated, trackConnectionUpdated, trackConnectionInvoked, + trackConnectionAppLinked, + trackConnectionAppRequested, } from "./events.js"; import type { TelemetryState } from "./types.js"; @@ -106,6 +108,31 @@ describe("registered connector events against the real TelemetryClient", () => { expect(client.isRegisteredEventName("project.created")).toBe(true); }); + it("sends server_domain and the aggregator app events as registered events", async () => { + vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true })); + const { client } = makeClient(); + expect(client.isRegisteredEventName("connection.app_linked")).toBe(true); + expect(client.isRegisteredEventName("connection.app_requested")).toBe(true); + + trackConnectionInvoked(client, { + connector_key: "custom", + transport: "mcp_remote", + status: "succeeded", + origin: "agent", + server_domain: "smithery.ai", + }); + trackConnectionAppLinked(client, { provider: "composio", app: "github" }); + trackConnectionAppRequested(client, { provider: "arcade", app: "other", origin: "agent", outcome: "needs_auth" }); + await client.flush(); + + const body = JSON.parse(String(vi.mocked(fetch).mock.calls[0]?.[1]?.body)); + expect(body.events.map((event: { name: string; dimensions: unknown }) => [event.name, event.dimensions])).toEqual([ + ["connection.invoked", { connector_key: "custom", transport: "mcp_remote", status: "succeeded", origin: "agent", server_domain: "smithery.ai" }], + ["connection.app_linked", { provider: "composio", app: "github" }], + ["connection.app_requested", { provider: "arcade", app: "other", origin: "agent", outcome: "needs_auth" }], + ]); + }); + it("a disabled client drops even registered events", async () => { vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true })); const { client, stateFactory } = makeClient({ enabled: false }); diff --git a/packages/shared/src/telemetry/events.ts b/packages/shared/src/telemetry/events.ts index b7c7fa27da4..0988441d90a 100644 --- a/packages/shared/src/telemetry/events.ts +++ b/packages/shared/src/telemetry/events.ts @@ -274,6 +274,7 @@ export function trackConnectionCreated( setup_flow: RawDimension; status: RawDimension; enabled: boolean; + server_domain?: string; }, ): void { client.track("connection.created", { @@ -296,6 +297,7 @@ export function trackConnectionUpdated( status: RawDimension; previous_enabled: boolean; enabled: boolean; + server_domain?: string; }, ): void { client.track("connection.updated", { @@ -316,6 +318,7 @@ export function trackConnectionInvoked( status: RawDimension; origin: RawDimension; duration_seconds?: number; + server_domain?: string; }, ): void { client.track("connection.invoked", { @@ -326,6 +329,36 @@ export function trackConnectionInvoked( }); } +export function trackConnectionAppLinked( + client: TelemetryClient, + dims: { + provider: RawDimension; + app: string; + }, +): void { + client.track("connection.app_linked", { + provider: asEventDimension(dims.provider), + app: dims.app, + }); +} + +export function trackConnectionAppRequested( + client: TelemetryClient, + dims: { + provider: RawDimension; + app: string; + origin: RawDimension; + outcome: RawDimension; + }, +): void { + client.track("connection.app_requested", { + provider: asEventDimension(dims.provider), + app: dims.app, + origin: asEventDimension(dims.origin), + outcome: asEventDimension(dims.outcome), + }); +} + export function trackServerStarted( client: TelemetryClient, dims: { os_platform: RawDimension }, diff --git a/packages/shared/src/telemetry/generated/paperclip-telemetry.ts b/packages/shared/src/telemetry/generated/paperclip-telemetry.ts index 033fd3d295e..c1a5e4e7679 100644 --- a/packages/shared/src/telemetry/generated/paperclip-telemetry.ts +++ b/packages/shared/src/telemetry/generated/paperclip-telemetry.ts @@ -44,10 +44,23 @@ source_ref?: string source_ref_hashed?: boolean } +export interface PaperclipConnectionAppLinkedDimensions { +app: string +provider: ("composio" | "arcade" | "executor") +} + +export interface PaperclipConnectionAppRequestedDimensions { +app: string +origin: ("user" | "agent") +outcome: ("succeeded" | "failed" | "needs_auth") +provider: ("composio" | "arcade" | "executor") +} + export interface PaperclipConnectionCreatedDimensions { auth_kind: ("oauth" | "api_key" | "none") connector_key: string enabled: boolean +server_domain?: string setup_flow: ("gallery" | "api" | "example") status: ("draft" | "active" | "disabled" | "archived") transport: ("mcp_remote" | "rest_api" | "local_stdio") @@ -57,6 +70,7 @@ export interface PaperclipConnectionInvokedDimensions { connector_key: string duration_seconds?: number origin: ("setup_test" | "agent" | "user" | "system" | "plugin") +server_domain?: string status: ("succeeded" | "failed" | "denied" | "cancelled" | "timed_out" | "rate_limited") transport: ("mcp_remote" | "rest_api" | "local_stdio") } @@ -68,6 +82,7 @@ connector_key: string enabled: boolean previous_enabled: boolean previous_status: ("draft" | "active" | "disabled" | "archived") +server_domain?: string status: ("draft" | "active" | "disabled" | "archived") transport: ("mcp_remote" | "rest_api" | "local_stdio") } @@ -178,6 +193,8 @@ export type PaperclipEventName = | "agent.task_run" | "artifact.created" | "company.imported" + | "connection.app_linked" + | "connection.app_requested" | "connection.created" | "connection.invoked" | "connection.updated" @@ -206,6 +223,8 @@ export interface EventDimensionsMap { "agent.task_run": PaperclipAgentTaskRunDimensions; "artifact.created": PaperclipArtifactCreatedDimensions; "company.imported": PaperclipCompanyImportedDimensions; + "connection.app_linked": PaperclipConnectionAppLinkedDimensions; + "connection.app_requested": PaperclipConnectionAppRequestedDimensions; "connection.created": PaperclipConnectionCreatedDimensions; "connection.invoked": PaperclipConnectionInvokedDimensions; "connection.updated": PaperclipConnectionUpdatedDimensions; @@ -235,6 +254,8 @@ export const PAPERCLIP_EVENTS = { "agent.task_run": "agent.task_run", "artifact.created": "artifact.created", "company.imported": "company.imported", + "connection.app_linked": "connection.app_linked", + "connection.app_requested": "connection.app_requested", "connection.created": "connection.created", "connection.invoked": "connection.invoked", "connection.updated": "connection.updated", @@ -429,6 +450,29 @@ export const PAPERCLIP_ENUM_DESCRIPTIONS = { "unknown": "Source type could not be classified." } }, + "connection.app_linked": { + "provider": { + "composio": "The app is reached through a Composio gateway.", + "arcade": "The app is reached through an Arcade gateway.", + "executor": "The app is reached through an Executor gateway." + } + }, + "connection.app_requested": { + "origin": { + "user": "A person asked from the app setup screens.", + "agent": "An agent asked through the gateway's connection-management tool." + }, + "outcome": { + "succeeded": "The app is connected without a further sign-in.", + "failed": "The aggregator rejected the request or did not confirm it.", + "needs_auth": "The aggregator returned a sign-in step the person must finish." + }, + "provider": { + "composio": "The app is reached through a Composio gateway.", + "arcade": "The app is reached through an Arcade gateway.", + "executor": "The app is reached through an Executor gateway." + } + }, "connection.created": { "auth_kind": { "oauth": "Connection authenticates with an OAuth flow.", diff --git a/packages/shared/src/telemetry/index.ts b/packages/shared/src/telemetry/index.ts index 69e507a3d17..6e609229bc9 100644 --- a/packages/shared/src/telemetry/index.ts +++ b/packages/shared/src/telemetry/index.ts @@ -22,6 +22,8 @@ export { trackConnectionCreated, trackConnectionUpdated, trackConnectionInvoked, + trackConnectionAppLinked, + trackConnectionAppRequested, trackServerStarted, trackModelConnected, trackTaskCreated, diff --git a/packages/shared/src/telemetry/retention.ts b/packages/shared/src/telemetry/retention.ts index d82be134d62..838957cb8f9 100644 --- a/packages/shared/src/telemetry/retention.ts +++ b/packages/shared/src/telemetry/retention.ts @@ -55,4 +55,6 @@ export const EVENT_RETENTION_CLASS: Partial> = { "plan.created": "operational_enum_count", "plan.approved": "operational_enum_count", "artifact.created": "operational_enum_count", + "connection.app_linked": "operational_enum_count", + "connection.app_requested": "operational_enum_count", }; diff --git a/server/package.json b/server/package.json index 83e3c1564b6..d87eaaedfe8 100644 --- a/server/package.json +++ b/server/package.json @@ -121,6 +121,7 @@ "ssh2": "^1.17.0", "svix": "1.76.1", "tar-stream": "3.2.0", + "tldts": "7.4.10", "ws": "^8.22.0", "zod": "^4.6.6" }, diff --git a/server/src/__tests__/aggregator-app-sync.test.ts b/server/src/__tests__/aggregator-app-sync.test.ts index 0c218c87620..13c0cb40a94 100644 --- a/server/src/__tests__/aggregator-app-sync.test.ts +++ b/server/src/__tests__/aggregator-app-sync.test.ts @@ -11,6 +11,11 @@ import { toolAccessRoutes } from "../routes/tool-access.js"; import { errorHandler } from "../middleware/error-handler.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +const track = vi.fn(); +vi.mock("../telemetry.js", () => ({ + getTelemetryClient: () => ({ track, isRegisteredEventName: () => true, hashPrivateRef: (value: string) => value, trackDynamic: vi.fn() }), +})); + // Optional reuse of the explicitly disposable browser-test cluster on hosts with limited PostgreSQL startup resources. const acceptanceDatabaseUrl = process.env.PAPERCLIP_AGGREGATOR_TEST_DATABASE_URL; if (acceptanceDatabaseUrl && !["127.0.0.1", "localhost"].includes(new URL(acceptanceDatabaseUrl).hostname)) throw new Error("The acceptance database must be local and disposable"); @@ -87,6 +92,18 @@ if (!support.supported) console.warn(`Managed-account database tests unavailable await db.update(toolConnections).set({ config: { ...f.connection.config, url: "https://executor.example/rotated" } }).where(eq(toolConnections.id, f.connection.id)); expect((await f.access.listAggregatorApps(f.connection.id, f.actor)).apps).toHaveLength(0); }); + it("emits app_linked once when a synced account first becomes connected, not on every re-sync", async () => { + const f = await fixture(); + const linked = () => track.mock.calls.filter(([name]) => name === "connection.app_linked"); + track.mockClear(); + await sync(f); + await sync(f); + expect(linked()).toEqual([["connection.app_linked", { provider: "executor", app: "notion" }]]); + f.disconnect(); + await sync(f); + expect(linked()).toHaveLength(1); + expect(JSON.stringify(track.mock.calls)).not.toMatch(/executor\.example|Work/); + }); it("reports unsupported Executor inventory without trying arbitrary tools", async () => { const f = await fixture(); await sync(f); f.calls.length = 0; await db.update(toolCatalogEntries).set({ status: "disabled" }).where(eq(toolCatalogEntries.connectionId, f.connection.id)); expect((await f.access.syncAggregatorApps(f.connection.id, true, f.actor)).discovery.availability).toBe("unsupported"); diff --git a/server/src/__tests__/composio-app-setup.test.ts b/server/src/__tests__/composio-app-setup.test.ts index 134c85bb664..4ef21b4d070 100644 --- a/server/src/__tests__/composio-app-setup.test.ts +++ b/server/src/__tests__/composio-app-setup.test.ts @@ -11,6 +11,13 @@ import { toolAccessPolicyService } from "../services/tool-access-policy.js"; import { toolAccessRoutes } from "../routes/tool-access.js"; import { errorHandler } from "../middleware/error-handler.js"; import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; +import { aggregatorAppTelemetrySlug } from "../services/connector-telemetry.js"; + +const track = vi.fn(); +vi.mock("../telemetry.js", () => ({ + getTelemetryClient: () => ({ track, isRegisteredEventName: () => true, hashPrivateRef: (value: string) => value, trackDynamic: vi.fn() }), +})); +const appEvents = () => track.mock.calls.filter(([name]) => String(name).startsWith("connection.app_")); describe("Composio app authorization evidence", () => { it("completes app setup without an agent selection", () => { @@ -322,6 +329,51 @@ const support = await getEmbeddedPostgresTestSupport(); expect(await db.select().from(issues).where(eq(issues.companyId, f.company.id))).toHaveLength(0); expect((await f.access.getEffectiveProfilesForAgent(f.company.id, f.agent.id)).allowedTools).toEqual([]); }); + it("reports each user app request and emits app_linked only when an app becomes connected", async () => { + const f = await fixture(); + const app = aggregatorAppTelemetrySlug("composio", "circleback_mcp"); + expect(app).not.toBe("other"); + track.mockClear(); + await f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "start" }, f.actor); + expect(appEvents()).toEqual([["connection.app_requested", { provider: "composio", app, origin: "user", outcome: "needs_auth" }]]); + track.mockClear(); + await f.access.refreshComposioApps(f.connection.id, ["circleback_mcp"], f.actor); + expect(appEvents()).toEqual([]); + f.activate(); + await f.access.refreshComposioApps(f.connection.id, ["circleback_mcp"], f.actor); + await f.access.refreshComposioApps(f.connection.id, ["circleback_mcp"], f.actor); + await f.access.setupComposioApp(f.connection.id, "circleback_mcp", { action: "complete" }, f.actor); + expect(appEvents()).toEqual([["connection.app_linked", { provider: "composio", app }]]); + track.mockClear(); + f.disconnect(); + await f.access.refreshComposioApps(f.connection.id, ["circleback_mcp"], f.actor); + f.activate(); + await f.access.refreshComposioApps(f.connection.id, ["circleback_mcp"], f.actor); + expect(appEvents()).toEqual([]); + expect(JSON.stringify(track.mock.calls)).not.toContain("never-store-this-token"); + }); + it("keeps app_linked for apps saved before a later app in the same check fails", async () => { + const f = await fixture(); + f.activate(); + f.failToolkit("notion"); + track.mockClear(); + 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); + track.mockClear(); + await expect(f.access.manageComposioAppAccount(f.connection.id, "circleback_mcp", { action: "add" }, f.actor)).rejects.toThrow(); + expect(appEvents()).toEqual([["connection.app_requested", { provider: "composio", app: aggregatorAppTelemetrySlug("composio", "circleback_mcp"), origin: "user", outcome: "failed" }]]); + }); it("retains previous observations when a list result is incomplete or fails", async () => { const f = await fixture(); f.activate(); await f.access.refreshComposioApps(f.connection.id, ["circleback_mcp"], f.actor); diff --git a/server/src/services/composio-app-setup.ts b/server/src/services/composio-app-setup.ts index bbb91409ab5..96bae4f8c60 100644 --- a/server/src/services/composio-app-setup.ts +++ b/server/src/services/composio-app-setup.ts @@ -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 | null { return value && typeof value === "object" && !Array.isArray(value) ? value as Record : 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 { + const outcomes = new Map(); + let payloads: (Record | 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; +} diff --git a/server/src/services/connector-telemetry.test.ts b/server/src/services/connector-telemetry.test.ts index 2fef1f55cce..96e48dac747 100644 --- a/server/src/services/connector-telemetry.test.ts +++ b/server/src/services/connector-telemetry.test.ts @@ -13,12 +13,20 @@ vi.mock("../telemetry.js", () => ({ })); const { + aggregatorAppTelemetrySlug, connectorKeyForConnection, + emitAggregatorAppRequestsFromToolCall, + emitAggregatorAppsLinked, + emitAggregatorAppsRequested, emitConnectionCreated, emitConnectionUpdated, emitConnectionInvoked, invocationOrigin, + newlyLinkedToolkits, + serverDomainForConnection, + serverDomainForUrl, } = await import("./connector-telemetry.js"); +const { AGGREGATOR_APP_CATALOG } = await import("@paperclipai/shared/aggregator-app-catalog"); type ToolConnectionRow = typeof toolConnections.$inferSelect; type ToolInvocationRow = typeof toolInvocations.$inferSelect; @@ -267,3 +275,211 @@ describe("emitConnectionInvoked", () => { expect(track).toHaveBeenCalledTimes(1); }); }); + +describe("serverDomainForUrl", () => { + it.each([ + ["https://mcp.smithery.ai/sse", "smithery.ai"], + ["https://server.smithery.ai/@acme/tools/mcp?api_key=sk-live-123&profile=acme", "smithery.ai"], + ["https://alice:hunter2@mcp.example.com:8443/v1/sse/3f9c2b7e-token?x=1#frag", "example.com"], + ["http://acme-corp.mcp.example.co.uk/mcp", "example.co.uk"], + ["https://MCP.Example.COM./sse", "example.com"], + ["https://bücher.example.de/mcp", "example.de"], + ["https://acme-tenant.github.io/mcp", "github.io"], + ["https://my-app.vercel.app/api/mcp", "vercel.app"], + ])("reduces %s to its registrable domain", (url, expected) => { + expect(serverDomainForUrl(url)).toBe(expected); + }); + + it.each([ + "http://10.0.0.5:3000/mcp", + "http://192.168.1.20/mcp", + "http://127.0.0.1:8080/sse", + "http://[::1]:8080/mcp", + "http://[fd00::1]/mcp", + "http://localhost:3000/mcp", + "http://mcp.localhost/mcp", + "http://printer.local/mcp", + "https://tools.svc.internal/mcp", + "https://nas.home.arpa/mcp", + "http://abcdefghijklmnop.onion/mcp", + "https://mcp.corp/mcp", + "https://intranet/mcp", + "https://foo.unknowntld/mcp", + "ftp://files.example.com/mcp", + "not a url", + "", + " ", + null, + 42, + { url: "https://mcp.smithery.ai" }, + ])("reports %s as private", (value) => { + expect(serverDomainForUrl(value)).toBe("private"); + }); +}); + +describe("serverDomainForConnection", () => { + it("omits the domain for catalog connectors, which already name their service", () => { + expect(serverDomainForConnection(connectionRow({ config: { sourceTemplateKey: "github", url: "https://api.githubcopilot.com/mcp" } }))).toBeUndefined(); + }); + + it("reports stdio for local servers and omits it for a remote server without an address", () => { + expect(serverDomainForConnection(connectionRow({ transport: "local_stdio", config: { command: "npx" } }))).toBe("stdio"); + expect(serverDomainForConnection(connectionRow({ config: {} }))).toBeUndefined(); + }); + + it("reads the remote address with the same precedence as the connection runtime", () => { + expect(serverDomainForConnection(connectionRow({ config: { url: "https://a.example.com/x", endpoint: "https://b.example.org/y" } }))).toBe("example.com"); + expect(serverDomainForConnection(connectionRow({ config: { endpoint: "https://b.example.org/y", remoteUrl: "https://c.example.net/z" } }))).toBe("example.org"); + expect(serverDomainForConnection(connectionRow({ config: { remoteUrl: "https://c.example.net/z" } }))).toBe("example.net"); + }); +}); + +describe("custom connector server_domain on connection events", () => { + const secretUrl = "https://alice:hunter2@tenant-acme.mcp.smithery.ai:8443/v1/sse/tok_9f8e7d?api_key=sk-live-123"; + const custom = connectionRow({ config: { sourceTemplateKey: "my-internal-server", url: secretUrl } }); + + it("adds only the registrable domain to created, updated, and invoked events", async () => { + emitConnectionCreated(custom, "api"); + emitConnectionUpdated(custom, { status: "draft", enabled: true }, "api"); + await emitConnectionInvoked(fakeDb(invocationRow(), custom), "inv-1"); + expect(track.mock.calls.map(([name]) => name)).toEqual(["connection.created", "connection.updated", "connection.invoked"]); + for (const [, dims] of track.mock.calls) { + expect(dims).toMatchObject({ connector_key: "custom", server_domain: "smithery.ai" }); + } + const payload = JSON.stringify(track.mock.calls); + for (const leaked of ["https:", "//", "alice", "hunter2", "tenant-acme", "mcp.smithery", "8443", "/v1", "sse", "tok_9f8e7d", "api_key", "sk-live-123", "my-internal-server"]) { + expect(payload).not.toContain(leaked); + } + }); + + it("never adds server_domain to catalog connector events", () => { + emitConnectionCreated(connectionRow({ config: { sourceTemplateKey: "github", url: secretUrl } }), "gallery"); + expect(track.mock.calls[0]?.[1]).not.toHaveProperty("server_domain"); + }); + + it("reports private and stdio markers instead of local addresses", () => { + emitConnectionCreated(connectionRow({ config: { url: "http://192.168.1.20:3000/mcp?token=abc" } }), "api"); + emitConnectionCreated(connectionRow({ transport: "local_stdio", config: { command: "/Users/alice/bin/mcp-server" } }), "api"); + expect(track.mock.calls.map(([, dims]) => dims.server_domain)).toEqual(["private", "stdio"]); + expect(JSON.stringify(track.mock.calls)).not.toMatch(/192\.168|token|alice/); + }); +}); + +describe("aggregatorAppTelemetrySlug", () => { + it("keeps reviewed catalog slugs for every provider", () => { + expect(aggregatorAppTelemetrySlug("composio", "github")).toBe("github"); + expect(aggregatorAppTelemetrySlug("arcade", "Gmail")).toBe("gmail"); + expect(aggregatorAppTelemetrySlug("executor", "notion")).toBe("notion"); + }); + + it("reports other for toolkits outside the catalog and provider-supplied names", () => { + for (const toolkit of ["acme-internal-crm", "Alice's Private Integration", "https://acme.example/app", "", " ", null, 7]) { + expect(aggregatorAppTelemetrySlug("composio", toolkit)).toBe("other"); + expect(aggregatorAppTelemetrySlug("arcade", toolkit)).toBe("other"); + expect(aggregatorAppTelemetrySlug("executor", toolkit)).toBe("other"); + } + }); + + it("only ever returns values the registered app pattern accepts", () => { + for (const app of AGGREGATOR_APP_CATALOG) { + for (const route of app.routes) { + expect(aggregatorAppTelemetrySlug(route.provider, route.toolkit)).toMatch(/^[a-z0-9][a-z0-9._:-]{0,63}$/); + } + } + }); +}); + +describe("newlyLinkedToolkits", () => { + it("emits once on the transition to connected and never on a re-sync", () => { + const previous = new Map([["github", "connected"], ["gmail", "not_connected"]]); + expect(newlyLinkedToolkits(previous, [ + { toolkit: "github", status: "connected" }, + { toolkit: "gmail", status: "connected" }, + { toolkit: "notion", status: "connected" }, + { toolkit: "notion", status: "connected" }, + { toolkit: "slack", status: "not_connected" }, + ])).toEqual(["gmail", "notion"]); + expect(newlyLinkedToolkits(new Map([["gmail", "connected"], ["notion", "connected"]]), [ + { toolkit: "gmail", status: "connected" }, + { toolkit: "notion", status: "connected" }, + ])).toEqual([]); + }); +}); + +describe("aggregator app events", () => { + it("sends provider and catalog-or-other app only", () => { + emitAggregatorAppsLinked("company-1", "composio", ["github", "acme-internal-crm"]); + emitAggregatorAppsRequested("company-1", { provider: "arcade", toolkits: ["Gmail", "Gmail"], origin: "user", outcome: "needs_auth" }); + expect(track.mock.calls).toEqual([ + ["connection.app_linked", { provider: "composio", app: "github" }], + ["connection.app_linked", { provider: "composio", app: "other" }], + ["connection.app_requested", { provider: "arcade", app: "gmail", origin: "user", outcome: "needs_auth" }], + ]); + }); + + it("never throws from telemetry", () => { + track.mockImplementation(() => { throw new Error("sink offline"); }); + expect(() => emitAggregatorAppsLinked("company-1", "composio", ["github"])).not.toThrow(); + expect(() => emitAggregatorAppsRequested("company-1", { provider: "composio", toolkits: ["github"], origin: "agent", outcome: "failed" })).not.toThrow(); + telemetryClient = null; + expect(() => emitAggregatorAppsLinked("company-1", "composio", ["github"])).not.toThrow(); + }); + + it("reports agent Composio add requests with each app's own outcome and ignores other calls", () => { + const response = { jsonrpc: "2.0", id: "1", result: { structuredContent: { data: { results: { + github: { toolkit: "github", status: "ACTIVE" }, + gmail: { redirect_url: "https://connect.composio.dev/link/abc" }, + slack: { toolkit: "slack", status: "INITIATED" }, + } } } } }; + const call = { companyId: "company-1", provider: "composio", toolName: "COMPOSIO_MANAGE_CONNECTIONS", origin: "agent" as const, pendingAuthorization: true, response }; + emitAggregatorAppRequestsFromToolCall({ ...call, parameters: { toolkits: [ + { name: "github", action: "add" }, { name: "gmail", action: "add" }, { name: "notion", action: "list" }, { name: "acme-crm", action: "add" }, + ] } }); + 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: "failed" }], + ]); + track.mockClear(); + emitAggregatorAppRequestsFromToolCall({ ...call, parameters: { toolkits: [{ name: "github", action: "list" }] } }); + emitAggregatorAppRequestsFromToolCall({ ...call, toolName: "COMPOSIO_MULTI_EXECUTE_TOOL", parameters: { toolkits: [{ name: "github", action: "add" }] } }); + emitAggregatorAppRequestsFromToolCall({ ...call, origin: null, parameters: { toolkits: [{ name: "github", action: "add" }] } }); + expect(track).not.toHaveBeenCalled(); + }); + + it("reports failed when the Composio response is an error or has no result for the app", () => { + const call = { companyId: "company-1", provider: "composio", toolName: "COMPOSIO_MANAGE_CONNECTIONS", origin: "agent" as const, pendingAuthorization: false, parameters: { toolkits: [{ name: "slack", action: "add" }] } }; + emitAggregatorAppRequestsFromToolCall({ ...call, response: { jsonrpc: "2.0", id: "1", error: { code: -32000, message: "upstream failed" } } }); + emitAggregatorAppRequestsFromToolCall({ ...call, response: { jsonrpc: "2.0", id: "1", result: { isError: true, content: [] } } }); + emitAggregatorAppRequestsFromToolCall({ ...call, response: { jsonrpc: "2.0", id: "1", result: { structuredContent: { data: { results: {} } } } } }); + 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 }); + emitAggregatorAppRequestsFromToolCall({ ...call, toolName: "Gmail_SendEmail", pendingAuthorization: false }); + expect(track.mock.calls).toEqual([ + ["connection.app_requested", { provider: "arcade", app: "gmail", origin: "agent", outcome: "needs_auth" }], + ]); + }); +}); diff --git a/server/src/services/connector-telemetry.ts b/server/src/services/connector-telemetry.ts index 0f314aa7ba1..77ed8f7fb40 100644 --- a/server/src/services/connector-telemetry.ts +++ b/server/src/services/connector-telemetry.ts @@ -1,11 +1,18 @@ import { eq } from "drizzle-orm"; import { toolConnections, toolInvocations, type Db } from "@paperclipai/db"; +import { isIP } from "node:net"; +import { parse as parseHostname } from "tldts"; import { getConnectableAppDefinition, isPluginAppSlug } from "@paperclipai/shared"; +import { resolveAggregatorApp, type AppCatalogAggregator } from "@paperclipai/shared/aggregator-app-catalog"; import { trackConnectionCreated, trackConnectionUpdated, trackConnectionInvoked, + trackConnectionAppLinked, + trackConnectionAppRequested, } from "@paperclipai/shared/telemetry"; +import { remoteEndpointValue } from "./tool-access/connection-methods.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"; @@ -56,6 +63,82 @@ export function connectorKeyForConnection( return key && !isPluginAppSlug(key) && getConnectableAppDefinition(key) ? key : "custom"; } +/** Same bound as the registered `connector_key` and `app` dimensions. */ +const TELEMETRY_SLUG_PATTERN = /^[a-z0-9][a-z0-9._:-]{0,63}$/; + +/** + * Lowercase dot-separated DNS labels (punycode for IDNs), at most 253 + * characters: the registered `server_domain` pattern. A final guard so a + * parser surprise can never emit anything shaped like a URL. + */ +const REGISTRABLE_DOMAIN_PATTERN = + /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; + +/** + * Special-use suffixes that the public suffix list treats as ordinary ICANN + * suffixes but that only ever name private or overlay hosts. + */ +const SPECIAL_USE_SUFFIXES = ["arpa", "onion"]; + +/** + * Reduces a configured remote server address to what telemetry may send for + * a custom connector: the registrable domain only (ICANN public suffix plus + * one label, e.g. `mcp.smithery.ai` reports `smithery.ai`). Path, query, + * port, credentials, and subdomains never leave the process: subdomains can + * name a customer or tenant, and paths and queries can carry tokens. Private + * entries of the public suffix list (e.g. `*.github.io`) are not honored, so + * a user-named subdomain under them is dropped too. + * + * Anything that does not name a public internet service reports the literal + * `private`: IP addresses, loopback, single-label hosts, non-ICANN suffixes + * such as `.local`, `.internal`, `.lan` or `.corp`, special-use suffixes + * such as `.home.arpa` or `.onion`, non-HTTP schemes, and unparsable values. + */ +export function serverDomainForUrl(value: unknown): string { + if (typeof value !== "string" || !value.trim()) return "private"; + let hostname: string; + try { + const url = new URL(value.trim()); + if (url.protocol !== "https:" && url.protocol !== "http:") return "private"; + hostname = url.hostname.toLowerCase().replace(/\.$/, ""); + } catch { + return "private"; + } + if (!hostname || hostname.startsWith("[") || isIP(hostname)) return "private"; + const parsed = parseHostname(hostname, { allowPrivateDomains: false }); + if (parsed.isIp || !parsed.isIcann || !parsed.domain || !parsed.publicSuffix) return "private"; + const suffixTld = parsed.publicSuffix.split(".").pop(); + if (suffixTld && SPECIAL_USE_SUFFIXES.includes(suffixTld)) return "private"; + const domain = parsed.domain.toLowerCase(); + return domain.length <= 253 && REGISTRABLE_DOMAIN_PATTERN.test(domain) ? domain : "private"; +} + +/** + * `server_domain` for a connection event. Only custom connectors carry it, + * since a catalog `connector_key` already names the service. Local stdio + * servers report `stdio`; a remote connection with no configured address yet + * (e.g. a draft) omits it. + */ +export function serverDomainForConnection( + connection: Pick, + connectorKey: string = connectorKeyForConnection(connection), +): string | undefined { + if (connectorKey !== "custom") return undefined; + if (connection.transport === "local_stdio") return "stdio"; + const value = remoteEndpointValue(connection.config ?? {}); + if (value === undefined || value === null || value === "") return undefined; + return serverDomainForUrl(value); +} + +function connectionIdentityDims(connection: Pick) { + const connectorKey = connectorKeyForConnection(connection); + const serverDomain = serverDomainForConnection(connection, connectorKey); + return { + connector_key: connectorKey, + ...(serverDomain === undefined ? {} : { server_domain: serverDomain }), + }; +} + /** * Setup-test invocations (Apps → Test tab) are separated from agent usage on * durable invocation columns, mirroring the gateway's own test-origin @@ -95,7 +178,7 @@ export function emitConnectionCreated( if (!client) return; if (!isToolPurpose(connection)) return; withTelemetryCompany(connection.companyId, () => trackConnectionCreated(client, { - connector_key: connectorKeyForConnection(connection), + ...connectionIdentityDims(connection), transport: connection.transport, auth_kind: connection.authKind, setup_flow: setupFlow, @@ -133,7 +216,7 @@ export function emitConnectionUpdated( return; } withTelemetryCompany(connection.companyId, () => trackConnectionUpdated(client, { - connector_key: connectorKeyForConnection(connection), + ...connectionIdentityDims(connection), transport: connection.transport, auth_kind: connection.authKind, change_source: changeSource, @@ -214,7 +297,7 @@ export async function emitConnectionInvoked( : undefined; withTelemetryCompany(connection.companyId, () => trackConnectionInvoked(client, { - connector_key: connectorKeyForConnection(connection), + ...connectionIdentityDims(connection), transport: connection.transport, status: invocation.status, origin: invocationOrigin(invocation), @@ -227,3 +310,153 @@ export async function emitConnectionInvoked( ); } } + +export type AggregatorAppRequestOrigin = "user" | "agent"; +export type AggregatorAppRequestOutcome = "succeeded" | "failed" | "needs_auth"; + +/** + * App identity for aggregator telemetry is the reviewed slug from the shared + * aggregator app catalog only, resolved from the provider's toolkit name. + * Anything else — Executor custom integrations, toolkits missing from the + * catalog, provider-supplied names — reports the literal `other`, the same + * rule as `connector_key`, so no user- or provider-controlled string leaves + * the process. + */ +export function aggregatorAppTelemetrySlug(provider: AppCatalogAggregator, toolkit: unknown): string { + if (typeof toolkit !== "string" || !toolkit.trim()) return "other"; + const { slug } = resolveAggregatorApp(provider, toolkit); + return !slug.startsWith(`${provider}:`) && TELEMETRY_SLUG_PATTERN.test(slug) ? slug : "other"; +} + +/** + * Toolkits whose cached app observation for one person moved to `connected` + * from anything else, including no observation at all. `previous` maps each + * toolkit to its stored status before the write; `next` lists the statuses + * the write committed. A re-sync that finds the app still connected is not a + * transition, so it never repeats `connection.app_linked`. + */ +export function newlyLinkedToolkits( + previous: ReadonlyMap, + next: Iterable<{ toolkit: string; status: string }>, +): string[] { + const linked = new Set(); + for (const { toolkit, status } of next) { + if (status === "connected" && previous.get(toolkit) !== "connected") linked.add(toolkit); + } + return [...linked]; +} + +/** + * Emits one `connection.app_linked` per toolkit whose snapshot a caller + * already committed as newly connected (see `newlyLinkedToolkits`). Delivery + * is best-effort: two concurrent syncs that both read the old status can each + * emit once. This function never throws; a telemetry failure must never fail + * an app sync. + */ +export function emitAggregatorAppsLinked( + companyId: string, + provider: AppCatalogAggregator, + toolkits: Iterable, +): void { + try { + const client = getTelemetryClient(); + if (!client) return; + for (const toolkit of toolkits) { + withTelemetryCompany(companyId, () => trackConnectionAppLinked(client, { + provider, + app: aggregatorAppTelemetrySlug(provider, toolkit), + })); + } + } catch (err) { + logger.warn({ err, companyId, provider }, "failed to emit connection.app_linked telemetry"); + } +} + +/** + * Emits one `connection.app_requested` per toolkit a person or agent asked an + * aggregator to add, with the aggregator's answer. A later completed sign-in + * is recorded separately by `connection.app_linked`. This function never + * throws; a telemetry failure must never fail an app setup or a tool call. + */ +export function emitAggregatorAppsRequested( + companyId: string, + input: { + provider: AppCatalogAggregator; + toolkits: Iterable; + origin: AggregatorAppRequestOrigin; + outcome: AggregatorAppRequestOutcome; + }, +): void { + try { + const client = getTelemetryClient(); + if (!client) return; + for (const toolkit of new Set(input.toolkits)) { + withTelemetryCompany(companyId, () => trackConnectionAppRequested(client, { + provider: input.provider, + app: aggregatorAppTelemetrySlug(input.provider, toolkit), + origin: input.origin, + outcome: input.outcome, + })); + } + } catch (err) { + logger.warn({ err, companyId, provider: input.provider }, "failed to emit connection.app_requested telemetry"); + } +} + +function addedComposioToolkits(parameters: unknown): string[] { + const toolkits = parameters && typeof parameters === "object" && !Array.isArray(parameters) + ? (parameters as Record).toolkits + : undefined; + if (!Array.isArray(toolkits)) return []; + return toolkits.slice(0, 64).flatMap((item) => { + const entry = item && typeof item === "object" ? item as Record : null; + return entry?.action === "add" && typeof entry.name === "string" ? [entry.name] : []; + }); +} + +/** + * 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 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 + * providers return without emitting. Never throws. + */ +export function emitAggregatorAppRequestsFromToolCall(input: { + companyId: string; + provider: unknown; + toolName: string; + parameters: unknown; + response: unknown; + origin: AggregatorAppRequestOrigin | null; + pendingAuthorization: boolean; +}): void { + try { + if (!input.origin) return; + if (input.provider === "composio" && input.toolName === "COMPOSIO_MANAGE_CONNECTIONS") { + 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: outcome === "connected" ? "succeeded" : outcome === "authorization_required" ? "needs_auth" : "failed", + }); + } + return; + } + if (input.provider === "arcade" && input.pendingAuthorization) { + const toolkit = input.toolName.split(/[._]/)[0]; + if (toolkit) { + emitAggregatorAppsRequested(input.companyId, { provider: "arcade", toolkits: [toolkit], origin: input.origin, outcome: "needs_auth" }); + } + } + } catch (err) { + logger.warn({ err, companyId: input.companyId }, "failed to emit connection.app_requested telemetry"); + } +} diff --git a/server/src/services/tool-access/catalog/aggregator-accounts.ts b/server/src/services/tool-access/catalog/aggregator-accounts.ts index 03511db58c0..4b2beef17ed 100644 --- a/server/src/services/tool-access/catalog/aggregator-accounts.ts +++ b/server/src/services/tool-access/catalog/aggregator-accounts.ts @@ -17,6 +17,7 @@ import { logActivity } from "../../activity-log.js"; import { initializeMcpHttpSession, getMcpHttpSession, isModernMcpProtocolVersion, readMcpHttpResponse, mcpHttpRequestInit } from "../../mcp-http.js"; import { secretService } from "../../secrets.js"; import { writeConnectionCredential } from "../../connection-credentials.js"; +import { emitAggregatorAppsLinked, emitAggregatorAppsRequested, newlyLinkedToolkits } from "../../connector-telemetry.js"; import type { ToolAccessAudit } from "../audit.js"; import type { ConnectionCredentialAccess } from "../credential-access.js"; @@ -53,6 +54,16 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred const composioSyncLeaseMs = 4 * 60_000; + /** Stored app status per toolkit for one person, before a write replaces it (any credential key). */ + async function snapshotStatuses(companyId: string, connectionId: string, userId: string, toolkits?: string[], executor: Pick = db) { + if (toolkits && !toolkits.length) return new Map(); + const rows = await executor.select({ toolkit: toolConnectionAppSnapshots.toolkit, status: toolConnectionAppSnapshots.status }).from(toolConnectionAppSnapshots).where(and( + eq(toolConnectionAppSnapshots.companyId, companyId), eq(toolConnectionAppSnapshots.connectionId, connectionId), eq(toolConnectionAppSnapshots.userId, userId), + ...(toolkits ? [inArray(toolConnectionAppSnapshots.toolkit, toolkits)] : []), + )); + return new Map(rows.map(row => [row.toolkit, row.status])); + } + async function composioCredentialKey(connection: typeof toolConnections.$inferSelect, actor: ActorInfo) { const usesConnectionRefs = ["arcade", "executor"].includes(String(connection.config.sourceTemplateKey)) && connection.authKind !== "oauth" && connection.credentialPolicy === "shared"; const grant = usesConnectionRefs ? null : await vaultGrantForConnection(connection, actor); @@ -143,6 +154,8 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred throw conflict("The Composio account changed while checking apps. Refresh to check the current account."); } const failedToolkits: string[] = []; + const listed = toolkits.filter(tool => tool.action === "list").map(tool => tool.name); + const previous = await snapshotStatuses(connection.companyId, connectionId, aggregatorUserId(actor), listed); for (const tool of toolkits.filter(tool => tool.action === "list")) { let accounts: ComposioAppAccount[]; try { @@ -161,10 +174,18 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred continue; } const status = accounts.some(account => account.status === "ACTIVE") ? "connected" as const : "not_connected" as const; - await db.insert(toolConnectionAppSnapshots).values({ companyId: connection.companyId, connectionId, userId: aggregatorUserId(actor), + const written = await db.insert(toolConnectionAppSnapshots).values({ companyId: connection.companyId, connectionId, userId: aggregatorUserId(actor), credentialKey, toolkit: tool.name, accounts, status, checkedAt, errorAt: null, }).onConflictDoUpdate({ target: [toolConnectionAppSnapshots.companyId, toolConnectionAppSnapshots.connectionId, toolConnectionAppSnapshots.userId, toolConnectionAppSnapshots.toolkit], - set: { accounts, status, checkedAt, credentialKey, errorAt: null }, setWhere: lte(toolConnectionAppSnapshots.checkedAt, checkedAt) }); + set: { accounts, status, checkedAt, credentialKey, errorAt: null }, setWhere: lte(toolConnectionAppSnapshots.checkedAt, checkedAt) }) + .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 }])); + // 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; } @@ -360,12 +381,15 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred const job = (async () => { try { const apps = await discoverAggregatorInventory(connection, actor); + let linked: string[] = []; await db.transaction(async tx => { const [current] = await tx.select().from(toolConnections).where(and(eq(toolConnections.id, connectionId), eq(toolConnections.companyId, connection.companyId))).for("update"); const [active] = await tx.select().from(toolConnectionAppSyncs).where(and(eq(toolConnectionAppSyncs.id, lease.id), eq(toolConnectionAppSyncs.leaseId, leaseId))).for("update"); if (!current || !active || current.status !== "active" || !current.enabled || Date.now() - startedAt.getTime() > composioSyncLeaseMs || await composioCredentialKey(current, actor) !== credentialKey) throw conflict("The gateway changed during account discovery"); const checkedAt = new Date(); + const previous = await snapshotStatuses(connection.companyId, connectionId, aggregatorUserId(actor), undefined, tx); + linked = newlyLinkedToolkits(previous, apps.map(app => ({ toolkit: app.toolkit, status: app.accounts.some(account => account.status === "ACTIVE") ? "connected" : "not_connected" }))); // Commit the entire enumeration at once; a failed later page cannot delete accounts. await tx.update(toolConnectionAppSnapshots).set({ accounts: [], status: "not_connected", checkedAt, errorAt: null }).where(and( eq(toolConnectionAppSnapshots.companyId, connection.companyId), eq(toolConnectionAppSnapshots.connectionId, connectionId), eq(toolConnectionAppSnapshots.userId, aggregatorUserId(actor)), eq(toolConnectionAppSnapshots.credentialKey, credentialKey), @@ -377,6 +401,7 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred }); await tx.update(toolConnectionAppSyncs).set({ status: "ready", checked: apps.length, total: apps.length, failed: 0, updatedAt: checkedAt, lastCompletedAt: checkedAt }).where(eq(toolConnectionAppSyncs.id, lease.id)); }); + emitAggregatorAppsLinked(connection.companyId, provider, linked); } catch (error) { await db.transaction(async tx => { const [active] = await tx.select().from(toolConnectionAppSyncs).where(and(eq(toolConnectionAppSyncs.id, lease.id), eq(toolConnectionAppSyncs.leaseId, leaseId))).for("update"); @@ -417,12 +442,25 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred syncAggregatorApps, configureArcadeDiscovery, async setupComposioApp(connectionId: string, toolkit: string, input: ComposioAppSetupInput, actor: ActorInfo): Promise { if (!findComposioCatalogApp(toolkit)) throw notFound("This Composio app is not in the catalog"); - const { connection, manage } = await openComposioGateway(connectionId, actor); - let result = composioAppSetupResult(await manage([{ name: toolkit, action: "list" }]), toolkit); - if (input.action === "start" && result.status !== "connected") { - result = composioAppSetupResult(await manage([{ name: toolkit, action: "add" }]), toolkit); - if (result.status === "not_connected") throw unprocessable("Composio did not return a sign-in link for this app. Manage it in Composio to check its setup requirements."); + const companyId = input.action === "start" ? (await getConnectionRow(connectionId)).companyId : null; + const requested = (outcome: "succeeded" | "failed" | "needs_auth") => { + if (companyId) emitAggregatorAppsRequested(companyId, { provider: "composio", toolkits: [toolkit], origin: "user", outcome }); + }; + let connection: typeof toolConnections.$inferSelect; + let result: ComposioAppSetupResult; + try { + const opened = await openComposioGateway(connectionId, actor); + connection = opened.connection; + result = composioAppSetupResult(await opened.manage([{ name: toolkit, action: "list" }]), toolkit); + if (input.action === "start" && result.status !== "connected") { + result = composioAppSetupResult(await opened.manage([{ name: toolkit, action: "add" }]), toolkit); + if (result.status === "not_connected") throw unprocessable("Composio did not return a sign-in link for this app. Manage it in Composio to check its setup requirements."); + } + } catch (error) { + requested("failed"); + throw error; } + requested(result.status === "connected" ? "succeeded" : "needs_auth"); if (input.action === "complete") { if (result.status !== "connected") throw conflict("Finish connecting this app in Composio, then check again"); const currentConnection = await getConnectionRow(connectionId); @@ -482,17 +520,31 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred const details = { toolkit, ...(input.action !== "add" ? { accountId: input.accountId } : {}) }; await logActivity(db, { companyId: connection.companyId, ...(actor.managementContext?.audit ?? { actorType: "user" as const, actorId: actor.actorId! }), action: `tool_connection.upstream_account_${input.action}_requested`, entityType: "tool_connection", entityId: connectionId, details }); + const requested = (outcome: "failed" | "needs_auth") => { + if (input.action === "add") emitAggregatorAppsRequested(connection.companyId, { provider: "composio", toolkits: [toolkit], origin: "user", outcome }); + }; let payload: unknown; try { payload = await manage([{ name: toolkit, action: input.action, ...(input.action !== "add" ? { account_id: input.accountId } : {}), ...(input.action === "rename" ? { alias: input.alias } : {}) }]); } catch (error) { + requested("failed"); await audit({ companyId: connection.companyId, connectionId, actor, action: `tool_connection.upstream_account_${input.action}`, outcome: "failure", reasonCode: "provider_unconfirmed", details }); throw error; } - const result = composioAppSetupResult(payload, toolkit); // Reject provider errors before reporting success. - if (input.action === "add" && !result.authorizationUrl) throw unprocessable("Composio did not return a sign-in link. Check the app in Composio."); + let result: ReturnType; + try { + result = composioAppSetupResult(payload, toolkit); // Reject provider errors before reporting success. + } catch (error) { + requested("failed"); + throw error; + } + if (input.action === "add" && !result.authorizationUrl) { + requested("failed"); + throw unprocessable("Composio did not return a sign-in link. Check the app in Composio."); + } + requested("needs_auth"); if (input.action !== "add") { const after = composioAppAccounts(await manage([{ name: toolkit, action: "list" }]), toolkit); if (!after || (input.action === "remove" ? after.some(account => account.id === input.accountId) diff --git a/server/src/services/tool-access/connection-methods.ts b/server/src/services/tool-access/connection-methods.ts index a659a4dee9f..93b46930a0e 100644 --- a/server/src/services/tool-access/connection-methods.ts +++ b/server/src/services/tool-access/connection-methods.ts @@ -361,8 +361,13 @@ export function projectedConnectionToolInputSchema( ); } +/** The configured remote address, before validation: `url`, then `endpoint`, then `remoteUrl`. */ +export function remoteEndpointValue(config: Record): unknown { + return config.url ?? config.endpoint ?? config.remoteUrl; +} + export function remoteEndpoint(config: Record): string { - const value = config.url ?? config.endpoint ?? config.remoteUrl; + const value = remoteEndpointValue(config); const parsed = parseRemoteHttpEndpoint(value, (message, code) => badRequest(message, { code }), ); diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 534062f2c44..89c40afd7fc 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -60,7 +60,7 @@ import { githubChatReviewService } from "./chat-github-reviews.js"; import { runIdentityContexts } from "@paperclipai/db"; import { executeSpekoVoiceTool, spekoToolsForSession } from "./voice/speko-agent-tools.js"; import { captureRunIdentity } from "./run-identity.js"; -import { emitConnectionInvoked } from "./connector-telemetry.js"; +import { emitAggregatorAppRequestsFromToolCall, emitConnectionInvoked } from "./connector-telemetry.js"; import { resolveManagedGitHubIdentitySelection } from "./git-credentials.js"; import { extractRemoteMcpPending } from "./remote-mcp-pending.js"; import { @@ -8784,6 +8784,15 @@ export function createToolGatewayService( // The older app finished the call: the answers it used are spent. for (const used of legacyAnswered.splice(0)) await settleElicitationRound(used.row, elicitationCall!, used.responses, invocationId); const upstreamPending = extractRemoteMcpPending(payloadRecord, String(connection.config.sourceTemplateKey ?? ""), entry.toolName); + emitAggregatorAppRequestsFromToolCall({ + companyId: session.companyId, + provider: connection.config.sourceTemplateKey, + toolName: entry.toolName, + parameters, + response: payloadRecord, + origin: session.agentId ? "agent" : session.actorType === "user" ? "user" : null, + pendingAuthorization: upstreamPending?.kind === "authorization", + }); if (upstreamPending) { await retainUpstreamHandoff(invocationId, upstreamPending); throw new ToolGatewayHttpError(409, "Complete the provider's authorization or approval before continuing. The original call has not been replayed.", "provider_interaction_required", { upstreamPending, invocationId }); diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index bc540a0de1a..b84eec20032 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -374,19 +374,19 @@ "packages/shared/src/standing-checks.ts": "7ab71e4b6984e41e1c1dfd1bddf0116041d5abf1", "packages/shared/src/subscriptions.ts": "ef70e63395ca967bbc30776b71560e96eb354a75", "packages/shared/src/summary-slot.test.ts": "5f8e222dea425f0d5bff0adb5c683087bd7cf7fb", - "packages/shared/src/telemetry/README.md": "04a42702f053688a41bcea09a93f8f33d2c9aa5d", + "packages/shared/src/telemetry/README.md": "0774d0bfb61e66b65219d7950b634b06e40e5390", "packages/shared/src/telemetry/client-types.test.ts": "3b630edda4972b929ba4decd7457f226eb9cfc5b", "packages/shared/src/telemetry/client.test.ts": "5a95f2305a393c5b2e7750b10e0ed65da0f30cf8", "packages/shared/src/telemetry/client.ts": "d6534ce8aaa6f69fb2dd03e12487db024e250a96", "packages/shared/src/telemetry/config.ts": "dfcd4d692cc06e71cb77f70b44fc05721eb330d1", - "packages/shared/src/telemetry/connector-events.test.ts": "c060017c7a6a26e67aea56e5c9e36059be527070", - "packages/shared/src/telemetry/events.ts": "b7c7fa27da4bec5e207785bfa6793d9ceffaf4db", - "packages/shared/src/telemetry/generated/paperclip-telemetry.ts": "033fd3d295ebf5fbed2938f58b4e04e7f4a110fb", - "packages/shared/src/telemetry/index.ts": "69e507a3d178c2daaa609f75b79f4cadfdc720af", + "packages/shared/src/telemetry/connector-events.test.ts": "17509f4726c84589533a57afd58f3e81fc09f09f", + "packages/shared/src/telemetry/events.ts": "0988441d90a9d4534a06b76af6545a80362511b0", + "packages/shared/src/telemetry/generated/paperclip-telemetry.ts": "c1a5e4e7679d9a4a1d2e420a1c65be608874b518", + "packages/shared/src/telemetry/index.ts": "6e609229bc9e37feb231fb13d8bc39fc3697d35f", "packages/shared/src/telemetry/product-events.test.ts": "d3182c7e18fbe9c2915497fc1e2048fb2a250a04", "packages/shared/src/telemetry/readme-contract.test.ts": "eec9d4511ddc3085a9af1a2dab6bf8487e49dfd7", "packages/shared/src/telemetry/retention.test.ts": "9d54db1371bf20f22b8d2f8373f84433107a7408", - "packages/shared/src/telemetry/retention.ts": "d82be134d62e0afbbde84b9a9851180a4b0bb694", + "packages/shared/src/telemetry/retention.ts": "838957cb8f9812d7d75680fbf42173d425d12006", "packages/shared/src/telemetry/server-started-event.test.ts": "3d0e0e2289badb41c92ba0d69e3668d00b3b5fdb", "packages/shared/src/telemetry/state.ts": "a060af26a8e9a82a8afb0e2fccbfe6a59e9d0a8a", "packages/shared/src/telemetry/types.ts": "083d4341a72ac47bc1a3bbff163965de8b06f90a",