mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 17:14:54 +01:00
feat(telemetry): report custom connector domains and aggregator app requests
Connector telemetry reports every custom MCP connector as the literal connector_key "custom", and apps reached through Composio, Arcade and Executor are not visible at all. The team cannot see which services people connect as custom servers, or which aggregator apps people try to connect and which ones they finish. Sync the registered contract and send three additions: - server_domain on connection.created, connection.updated and connection.invoked, for custom connectors only. It is the registrable domain (ICANN public suffix plus one label, from tldts). The path, query, port, credentials and subdomains never leave the process. IPs, loopback, single-label hosts, non-ICANN and special-use suffixes, non-HTTP schemes and unparsable addresses send "private". Local stdio servers send "stdio". - connection.app_linked (provider, app) when a person's cached app observation moves to connected. Composio list checks and the Arcade/Executor inventory sync read the previous status first, so a re-sync that finds the app still connected sends nothing. - connection.app_requested (provider, app, origin, outcome) when a person starts app setup or adds an account, and when an agent calls COMPOSIO_MANAGE_CONNECTIONS with add or an Arcade tool answers with an authorization step. app is a slug from the shared aggregator catalog, or "other", the same rule as connector_key. All emitters are best-effort and never throw. Tested: vitest for connector-telemetry (domain normalization including private, IP, userinfo and token-in-path cases, no URL fragment in any payload, catalog-or-other, transition rule), composio-app-setup and aggregator-app-sync against embedded Postgres (emit once on transition, request outcomes), the shared telemetry client, and the related gateway suites. The new tests fail when the transition check or the domain reduction is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9a6e61cf36
commit
4a22251d93
14 files changed
+679
-14
No files matched your search
@@ -201,6 +201,39 @@ 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
|
||||
`needs_auth` when the provider returns a sign-in step, `succeeded` when the
|
||||
app is already connected, and `failed` otherwise.
|
||||
|
||||
## Cloud Direct Delivery
|
||||
|
||||
Self-hosted installs are unchanged. They post every batch to the collector,
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -274,6 +274,7 @@ export function trackConnectionCreated(
|
||||
setup_flow: RawDimension<EventDimensionsMap["connection.created"]["setup_flow"]>;
|
||||
status: RawDimension<EventDimensionsMap["connection.created"]["status"]>;
|
||||
enabled: boolean;
|
||||
server_domain?: string;
|
||||
},
|
||||
): void {
|
||||
client.track("connection.created", {
|
||||
@@ -296,6 +297,7 @@ export function trackConnectionUpdated(
|
||||
status: RawDimension<EventDimensionsMap["connection.updated"]["status"]>;
|
||||
previous_enabled: boolean;
|
||||
enabled: boolean;
|
||||
server_domain?: string;
|
||||
},
|
||||
): void {
|
||||
client.track("connection.updated", {
|
||||
@@ -316,6 +318,7 @@ export function trackConnectionInvoked(
|
||||
status: RawDimension<EventDimensionsMap["connection.invoked"]["status"]>;
|
||||
origin: RawDimension<EventDimensionsMap["connection.invoked"]["origin"]>;
|
||||
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<EventDimensionsMap["connection.app_linked"]["provider"]>;
|
||||
app: string;
|
||||
},
|
||||
): void {
|
||||
client.track("connection.app_linked", {
|
||||
provider: asEventDimension(dims.provider),
|
||||
app: dims.app,
|
||||
});
|
||||
}
|
||||
|
||||
export function trackConnectionAppRequested(
|
||||
client: TelemetryClient,
|
||||
dims: {
|
||||
provider: RawDimension<EventDimensionsMap["connection.app_requested"]["provider"]>;
|
||||
app: string;
|
||||
origin: RawDimension<EventDimensionsMap["connection.app_requested"]["origin"]>;
|
||||
outcome: RawDimension<EventDimensionsMap["connection.app_requested"]["outcome"]>;
|
||||
},
|
||||
): 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<EventDimensionsMap["server.started"]["os_platform"]> },
|
||||
|
||||
@@ -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.",
|
||||
|
||||
@@ -22,6 +22,8 @@ export {
|
||||
trackConnectionCreated,
|
||||
trackConnectionUpdated,
|
||||
trackConnectionInvoked,
|
||||
trackConnectionAppLinked,
|
||||
trackConnectionAppRequested,
|
||||
trackServerStarted,
|
||||
trackModelConnected,
|
||||
trackTaskCreated,
|
||||
|
||||
@@ -55,4 +55,6 @@ export const EVENT_RETENTION_CLASS: Partial<Record<string, RetentionClass>> = {
|
||||
"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",
|
||||
};
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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,36 @@ 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("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);
|
||||
|
||||
@@ -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,176 @@ 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 and ignores list-only calls and other tools", () => {
|
||||
const call = { companyId: "company-1", provider: "composio", toolName: "COMPOSIO_MANAGE_CONNECTIONS", origin: "agent" as const, pendingAuthorization: true, failed: false };
|
||||
emitAggregatorAppRequestsFromToolCall({ ...call, parameters: { toolkits: [{ name: "github", action: "add" }, { name: "gmail", action: "list" }, { name: "acme-crm", action: "add" }] } });
|
||||
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" }] } });
|
||||
emitAggregatorAppRequestsFromToolCall({ ...call, pendingAuthorization: false, failed: true, parameters: { toolkits: [{ name: "slack", action: "add" }] } });
|
||||
expect(track.mock.calls).toEqual([
|
||||
["connection.app_requested", { provider: "composio", app: "github", origin: "agent", outcome: "needs_auth" }],
|
||||
["connection.app_requested", { provider: "composio", app: "other", origin: "agent", outcome: "needs_auth" }],
|
||||
["connection.app_requested", { provider: "composio", app: "slack", origin: "agent", outcome: "failed" }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports an Arcade tool call that asks for authorization as a request for its toolkit", () => {
|
||||
const call = { companyId: "company-1", provider: "arcade", parameters: {}, origin: "agent" as const, failed: true };
|
||||
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" }],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,17 @@
|
||||
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 { logger } from "../middleware/logger.js";
|
||||
import { getTelemetryClient } from "../telemetry.js";
|
||||
import { withTelemetryCompany } from "../telemetry-company-scope.js";
|
||||
@@ -56,6 +62,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<ToolConnectionRow, "config" | "transport">,
|
||||
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<ToolConnectionRow, "config" | "transport">) {
|
||||
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 +177,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 +215,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 +296,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 +309,146 @@ 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<string, string>,
|
||||
next: Iterable<{ toolkit: string; status: string }>,
|
||||
): string[] {
|
||||
const linked = new Set<string>();
|
||||
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<string>,
|
||||
): 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<string>;
|
||||
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<string, unknown>).toolkits
|
||||
: undefined;
|
||||
if (!Array.isArray(toolkits)) return [];
|
||||
return toolkits.slice(0, 64).flatMap((item) => {
|
||||
const entry = item && typeof item === "object" ? item as Record<string, unknown> : 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, 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;
|
||||
origin: AggregatorAppRequestOrigin | null;
|
||||
pendingAuthorization: boolean;
|
||||
failed: boolean;
|
||||
}): void {
|
||||
try {
|
||||
if (!input.origin) return;
|
||||
const outcome: AggregatorAppRequestOutcome = input.pendingAuthorization
|
||||
? "needs_auth"
|
||||
: input.failed ? "failed" : "succeeded";
|
||||
if (input.provider === "composio" && input.toolName === "COMPOSIO_MANAGE_CONNECTIONS") {
|
||||
const toolkits = addedComposioToolkits(input.parameters);
|
||||
if (toolkits.length) {
|
||||
emitAggregatorAppsRequested(input.companyId, { provider: "composio", toolkits, origin: input.origin, outcome });
|
||||
}
|
||||
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 });
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn({ err, companyId: input.companyId }, "failed to emit connection.app_requested telemetry");
|
||||
}
|
||||
}
|
||||
@@ -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, "select"> = db) {
|
||||
if (toolkits && !toolkits.length) return new Map<string, string>();
|
||||
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,9 @@ 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);
|
||||
const committed: { toolkit: string; status: string }[] = [];
|
||||
for (const tool of toolkits.filter(tool => tool.action === "list")) {
|
||||
let accounts: ComposioAppAccount[];
|
||||
try {
|
||||
@@ -161,11 +175,15 @@ 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 });
|
||||
// A newer observation already won the row; this write changed nothing.
|
||||
if (written.length) committed.push({ toolkit: tool.name, status });
|
||||
}
|
||||
emitAggregatorAppsLinked(connection.companyId, "composio", newlyLinkedToolkits(previous, committed));
|
||||
return { payload, failedToolkits };
|
||||
} catch (error) { await markFailed(); throw error; }
|
||||
}
|
||||
@@ -360,12 +378,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 +398,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 +439,25 @@ export function createAggregatorAccounts(db: Db, { options, secrets, audit, cred
|
||||
syncAggregatorApps, configureArcadeDiscovery,
|
||||
async setupComposioApp(connectionId: string, toolkit: string, input: ComposioAppSetupInput, actor: ActorInfo): Promise<ComposioAppSetupResult> {
|
||||
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 +517,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<typeof composioAppSetupResult>;
|
||||
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)
|
||||
|
||||
@@ -361,8 +361,13 @@ export function projectedConnectionToolInputSchema(
|
||||
);
|
||||
}
|
||||
|
||||
/** The configured remote address, before validation: `url`, then `endpoint`, then `remoteUrl`. */
|
||||
export function remoteEndpointValue(config: Record<string, unknown>): unknown {
|
||||
return config.url ?? config.endpoint ?? config.remoteUrl;
|
||||
}
|
||||
|
||||
export function remoteEndpoint(config: Record<string, unknown>): string {
|
||||
const value = config.url ?? config.endpoint ?? config.remoteUrl;
|
||||
const value = remoteEndpointValue(config);
|
||||
const parsed = parseRemoteHttpEndpoint(value, (message, code) =>
|
||||
badRequest(message, { code }),
|
||||
);
|
||||
|
||||
@@ -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,
|
||||
origin: session.agentId ? "agent" : session.actorType === "user" ? "user" : null,
|
||||
pendingAuthorization: upstreamPending?.kind === "authorization",
|
||||
failed: payloadRecord.error !== undefined || asRecord(payloadRecord.result)?.isError === true,
|
||||
});
|
||||
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 });
|
||||
|
||||
Reference in new issue
Block a user