From 01451fae5b25f784956e9932f12031dc194ac247 Mon Sep 17 00:00:00 2001 From: Dotta <34892728+cryppadotta@users.noreply.github.com> Date: Tue, 17 Nov 2026 09:51:39 -0600 Subject: [PATCH] Let plugins add connector types to the Connectors catalog (#22004) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Agents use external services through connectors: a catalog of connector types, connections (accounts) per type, and per-agent installs, policies and audit in the tool gateway > - Today only core can add a connector type. Every type is a JSON definition compiled into `@paperclipai/shared` > - Plugins can add agent tools, but those tools skip connections, grants, per-agent installs and the Connectors page > - This pull request lets a plugin add connector types with the same definition schema, and makes them behave exactly like built-in connectors > - The benefit is that a connector can ship as a plugin, and an operator controls it with the same Connectors page and the same access rules ## Linked Issues or Issue Description **Subsystem affected** Plugins, Connectors (tool access), tool gateway **Problem or motivation** A plugin cannot add a connector type to the Connectors catalog. Plugin tools (`tools` in the manifest) do not use connections, credentials per account, agent installs, policies or the Connectors page. **Proposed solution** Add a manifest field `apps` (gated by a new `connectors.provide` capability). Each entry uses the built-in app-definition schema. The host namespaces the slug by plugin key and runs setup, OAuth, discovery, grants, policies and audit through the existing code. This is the first of two pull requests. The second adds a `plugin` transport so a plugin worker can serve the tools itself. **Activation rules (product requirements)** 1. Installing or enabling a plugin grants no tools. It only adds connector types to the catalog. 2. Connecting an account grants no tools. 3. An agent gets the tools only from an agent install or a company install of an active connection. Discovery and invocation both enforce this. 4. A disabled or uninstalled plugin (or an upgrade that removes the app) hides its connector types and connections from the Connectors APIs and they reach no agent. Saved setup survives disable and comes back on re-enable. Uninstall keeps rows archived for audit and revokes credentials. **Alternatives considered** Keep plugin tools (`tools`) as the only plugin path. Rejected: they bypass connections, per-account credentials, per-agent installs and the Connectors page. ## What Changed - `packages/shared`: new capability `connectors.provide`; manifest `apps` validated with `appDefinitionSchema`. The validator rejects apps without the capability, duplicate slugs, host-derived fields (`plugin`, `aiConnectionRouter`, `experimentalFeatureKey`, `availability`), and methods that need provider code in the host (REST adapters, chat channels, AI runtimes). - `packages/shared/src/plugin-apps.ts`: reversible namespaced slugs (`plugin--`), the catalog entry builder, and `reviewedToolRisk`. - `packages/shared/src/app-definitions.ts`: catalog lookups (`getConnectableAppDefinition`, `getAppStoreDefinition`, ...) also resolve the current plugin apps. The set is replaced on each read of plugin state, so a built-in app is never shadowed. - App definitions can declare `reviewedTools` (reviewed read/write/destructive names and the risk for unlisted tools). Circleback's reviewed risk moves from `server/src/services/connectors/circleback/risk.ts` into `circleback.json`, with the same classification. A copy of the definition now classifies tools the same way. - `validators/json-schema.ts`: `jsonSchemaSchema` moves to its own module to break an import cycle between the plugin and app-definition validators (still re-exported from `validators/plugin.ts`). - `server/src/services/plugin-app-catalog.ts`: reads ready plugins from the `plugins` table and answers "is this connection's connector available". It does not trust in-memory lifecycle events, because several lifecycle managers and processes can share one database. - Gateway: connected-tool discovery and `resolveConnectionGrant` drop connections from an unavailable plugin connector. Built-in connections do not read the plugins table. - Connectors APIs: the gallery lists ready plugin apps (with the same Cloud connector profile filter as core); `listConnections` and `listApplications` hide unavailable plugin connections; setup entry points refresh plugin apps first. - Plugin uninstall archives the plugin's connections through the standard connection removal (grants revoked, owned credentials deleted, rows kept). - UI: the gallery response registers plugin apps for the setup screens; `/apps/connect?source=plugin-…` loads the gallery first and shows an unavailable state when the plugin is disabled. - Docs: `doc/plugins/PLUGIN_SPEC.md` section 11A and the capability list. Design choices where the spec left room (picked to match "a plugin connector behaves like a built-in connector"): - Only `ready` plugins provide connectors. `error` and `upgrade_pending` hide them, the same as the AI connection router plugins. - `rest_api` is rejected for plugin apps in this PR. Core REST connectors need reviewed adapter code in the host, so a definition alone cannot work. The `plugin` transport in the next PR covers that case. - Disabled plugin connections are hidden from list endpoints. Reading one connection by id still works, so audit links keep resolving. ## Verification - `packages/shared`: `npx vitest run src/plugin-apps.test.ts src/validators/ src/app-definitions.test.ts` (416 passed). New tests: manifest validation, slug namespacing, no shadowing of built-in apps, reviewed risk. - `server`: `npx vitest run src/__tests__/plugin-connectors-circleback-parity.test.ts` (new). A test-only plugin (`server/src/__tests__/fixtures/plugin-connectors/circleback-parity/`) ships an unmodified copy of `circleback.json`. The same journey runs against built-in Circleback and the plugin copy with a recorded DCR OAuth + MCP fixture, and must give identical catalog risk/status, suggested defaults and per-agent tool sets. It covers each rule: - Rule 1: the gallery adds only the namespaced type; no connections exist; no agent tool changes. - Rule 2: two signed-in accounts, no agent sees a tool. - Rule 3: an install for agent A gives only A the tools of that connection; agent B is denied on invocation; each account calls the provider with its own credential. - Rule 4: disable hides the type, both connections and applications, removes tools from discovery and invocation (404) and blocks new setup, while built-in Circleback is unchanged; installs and grants are byte-identical; re-enable restores tools with the same names; an upgrade that removes the app hides it; uninstall archives both connections, revokes grants and deletes owned secrets. - Red/green: removing the gateway gate or the declared review makes the test fail. - An env-gated live check (`PAPERCLIP_CIRCLEBACK_LIVE=1`) starts the real Circleback sign-in for both connectors and compares the requests. It never runs in CI. I did not run it for this PR. - Regression: `ai-connection-router`, `connector-tool-policy`, `mcp-apps`, `plugin-lifecycle-restart`, `tool-access-service`, `braintrust-connection`, `remote-mcp-connectors`, `connection-intents-service`, `tool-gateway` (796 passed). - `ui`: `app-connect-policy.test.ts`, `AppsConnect.test.tsx` (new plugin cases) pass. - `tsc --noEmit` for shared, server, ui (only pre-existing ungenerated Storybook catalog errors), plugin SDK and CLI. - `pnpm verify --explain` selects a broad plan because a doc under `doc/plugins` changed; CI supplies that coverage. ## Risks - No migration. Built-in connectors only gain one string check per discovery; the plugins table is read only when a plugin connection is present. - Circleback's reviewed risk is now data. The behavior is the same, and the existing policy tests and new tests cover it. - Connection intents (agent connection requests in chat) still search only built-in apps. Plugin connectors can be set up from the Connectors page. This is a follow-up. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, used through Claude Code with tool use (shell, file editing, test execution). ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 --- doc/plugins/PLUGIN_SPEC.md | 43 ++ packages/shared/src/app-definitions.ts | 25 +- .../src/app-definitions/circleback.json | 30 ++ packages/shared/src/constants.ts | 2 + packages/shared/src/index.ts | 14 +- packages/shared/src/plugin-apps.test.ts | 169 ++++++++ packages/shared/src/plugin-apps.ts | 84 ++++ packages/shared/src/types/app-definition.ts | 5 +- packages/shared/src/types/plugin.ts | 8 + .../shared/src/validators/app-definition.ts | 28 +- packages/shared/src/validators/json-schema.ts | 18 + packages/shared/src/validators/plugin.ts | 76 +++- packages/shared/src/validators/tool-access.ts | 4 +- .../circleback-parity/circleback.json | 82 ++++ .../circleback-parity/manifest.json | 11 + ...lugin-connectors-circleback-parity.test.ts | 386 ++++++++++++++++++ server/src/app.ts | 4 + server/src/routes/tool-access.ts | 8 + server/src/services/connector-telemetry.ts | 6 +- .../services/connectors/circleback/risk.ts | 45 -- server/src/services/connectors/tool-policy.ts | 26 +- server/src/services/plugin-app-catalog.ts | 150 +++++++ .../services/plugin-capability-validator.ts | 1 + server/src/services/plugin-lifecycle.ts | 20 +- server/src/services/tool-access.ts | 71 +++- .../tool-access/oauth/catalog-completion.ts | 7 +- .../tool-access/token-broker/service.ts | 9 +- server/src/services/tool-gateway.ts | 13 + .../runner-e2e/source-sdk-public-inputs.json | 21 +- ui/src/api/tools.ts | 11 +- ui/src/pages/apps/AppsConnect.test.tsx | 10 +- ui/src/pages/apps/AppsConnect.tsx | 15 +- ui/src/pages/apps/app-connect-policy.test.ts | 8 +- ui/src/pages/apps/app-connect-policy.ts | 5 + 34 files changed, 1305 insertions(+), 110 deletions(-) create mode 100644 packages/shared/src/plugin-apps.test.ts create mode 100644 packages/shared/src/plugin-apps.ts create mode 100644 packages/shared/src/validators/json-schema.ts create mode 100644 server/src/__tests__/fixtures/plugin-connectors/circleback-parity/circleback.json create mode 100644 server/src/__tests__/fixtures/plugin-connectors/circleback-parity/manifest.json create mode 100644 server/src/__tests__/plugin-connectors-circleback-parity.test.ts delete mode 100644 server/src/services/connectors/circleback/risk.ts create mode 100644 server/src/services/plugin-app-catalog.ts diff --git a/doc/plugins/PLUGIN_SPEC.md b/doc/plugins/PLUGIN_SPEC.md index e6d96c59d44..4b4aa8dddc7 100644 --- a/doc/plugins/PLUGIN_SPEC.md +++ b/doc/plugins/PLUGIN_SPEC.md @@ -496,6 +496,45 @@ Plugin tools appear in the agent's tool list alongside core tools but are visual - Tool execution is subject to the same timeout and resource limits as other plugin worker calls. - Tool results are included in run logs. +## 11A. Connectors + +A plugin with the `connectors.provide` capability can add connector types to +the Connectors catalog. It declares them as `apps` in its manifest. Each entry +uses the built-in app-definition schema +(`packages/shared/src/app-definitions/*.json`, validated by +`appDefinitionSchema`), so a built-in connector can be copied into a plugin +unchanged. + +```ts +apps?: AppDefinition[]; +``` + +- The host namespaces each slug by plugin key (`pluginAppSlug(pluginKey, slug)`), + so a plugin app never shadows a built-in app or another plugin's app. +- A method can use the `mcp_remote` or `local_stdio` transport. The host then + does setup, OAuth, discovery, grants, policies, approvals and audit exactly as + for a built-in connector. Transports that need provider code in the host + (REST adapters, chat channels, AI runtimes) are rejected. +- A definition can declare `reviewedTools` (read, write and destructive tool + names, and the risk for unlisted tools). The host classifies the connector's + tools from it wherever the definition is installed. +- The manifest validator rejects apps without `connectors.provide`, duplicate + slugs, and host-derived fields (`plugin`, `aiConnectionRouter`, + `experimentalFeatureKey`, `availability`). + +Activation rules: + +1. Installing or enabling the plugin grants no tools. It only adds its connector + types to the catalog. +2. Connecting an account grants no tools. +3. An agent gets a connector's tools only from a connection installed for that + agent, or for the whole company. Discovery and invocation both enforce this. +4. While the plugin is not `ready`, or after an upgrade removes the app, its + connector types and connections are hidden from the Connectors APIs and reach + no agent. Settings, credentials, installs and grants are kept and come back + unchanged when the plugin is ready again. Uninstalling archives the + connections, revokes their grants and deletes their owned credentials. + ## 12. Runtime Model ## 12.1 Process Model @@ -936,6 +975,10 @@ The host enforces capabilities in the SDK layer and refuses calls outside the gr - `agent.tools.register` +### Connectors + +- `connectors.provide` + ### UI - `instance.settings.register` diff --git a/packages/shared/src/app-definitions.ts b/packages/shared/src/app-definitions.ts index eaadd6b7831..ba5a19cce96 100644 --- a/packages/shared/src/app-definitions.ts +++ b/packages/shared/src/app-definitions.ts @@ -91,16 +91,33 @@ export const DEFAULT_OWNERSHIP_AVAILABILITY: Record(); + +export function setPluginAppDefinitions(definitions: readonly AppDefinition[]): void { + pluginAppDefinitions = new Map(definitions.filter((app) => app.plugin).map((app) => [app.slug, app])); +} + +export function listPluginAppDefinitions(): AppDefinition[] { + return [...pluginAppDefinitions.values()]; +} + export function getConnectableAppDefinition(slug: string): AppDefinition | null { - return CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === slug) ?? null; + return CONNECTABLE_APP_DEFINITIONS.find((app) => app.slug === slug) ?? pluginAppDefinitions.get(slug) ?? null; } export function getAppStoreDefinition(slug: string): AppDefinition | null { - return APP_STORE_DEFINITIONS.find((app) => app.slug === slug) ?? null; + return APP_STORE_DEFINITIONS.find((app) => app.slug === slug) ?? pluginAppDefinitions.get(slug) ?? null; } export function isAppStoreVisibleSlug(slug: string | null | undefined): boolean { - return Boolean(slug && !APP_STORE_HIDDEN_SLUGS.has(slug) && CONNECTABLE_APP_SLUGS.has(slug)); + return Boolean(slug && ((!APP_STORE_HIDDEN_SLUGS.has(slug) && CONNECTABLE_APP_SLUGS.has(slug)) || pluginAppDefinitions.has(slug))); } function wildcardPatternToRegExp(pattern: string): RegExp { @@ -215,7 +232,7 @@ export function appSupportsCatalogSetup(app: AppDefinition | null | undefined): } export function isConnectableAppSlug(slug: string | null | undefined): boolean { - return Boolean(slug && CONNECTABLE_APP_SLUGS.has(slug)); + return Boolean(slug && (CONNECTABLE_APP_SLUGS.has(slug) || pluginAppDefinitions.has(slug))); } export function appSupportsAutomaticOAuth(app: AppDefinition | null | undefined): boolean { diff --git a/packages/shared/src/app-definitions/circleback.json b/packages/shared/src/app-definitions/circleback.json index 2b05e87c356..717d53e78a4 100644 --- a/packages/shared/src/app-definitions/circleback.json +++ b/packages/shared/src/app-definitions/circleback.json @@ -16,6 +16,36 @@ ], "docsUrl": "https://circleback.ai/docs/support/platform/circleback-mcp", "redirectConstraints": "https-or-loopback-http", + "reviewedTools": { + "reviewedAt": "2026-11-12", + "sourceUrl": "https://circleback.ai/docs/support/platform/circleback-mcp", + "read": [ + "SearchMeetings", + "ReadMeetings", + "GetTranscriptsForMeetings", + "SearchTranscripts", + "SearchActionItems", + "SearchCalendarEvents", + "SearchEmails", + "FindProfiles", + "FindCompanies", + "ListTags", + "ListFolders", + "ReadFolders", + "ListTeams", + "SearchSupportArticles", + "DisplayMeetings", + "DisplayActionItems", + "DisplayCalendarEvents" + ], + "destructive": [ + "DeleteActionItem", + "DeleteTag", + "DeleteFolder" + ], + "unlisted": "write", + "quarantineNewEntries": false + }, "methods": [ { "key": "mcp-oauth", diff --git a/packages/shared/src/constants.ts b/packages/shared/src/constants.ts index 47973de810c..698b73db166 100644 --- a/packages/shared/src/constants.ts +++ b/packages/shared/src/constants.ts @@ -1446,6 +1446,8 @@ export const PLUGIN_CAPABILITIES = [ "local.folders", // Agent Tools "agent.tools.register", + // Connectors + "connectors.provide", // UI "instance.settings.register", "ui.sidebar.register", diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 6a7bc609575..e17ff48b580 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -331,9 +331,19 @@ export { getRecommendedConnectionMethod, isConnectableAppSlug, isAppStoreVisibleSlug, + listPluginAppDefinitions, recommendedDefaultsForApp, resolveConnectionMethodServerUrl, + setPluginAppDefinitions, } from "./app-definitions.js"; +export { + connectionSourceSlug, + isPluginAppSlug, + parsePluginAppSlug, + pluginAppDefinition, + pluginAppSlug, + reviewedToolRisk, +} from "./plugin-apps.js"; export { isConnectorFeatureEnabled, nativeConnectorRequiresCustomerOAuthApp } from "./connector-availability.js"; export { getAppDefinitionForApplicationKey } from "./connector-identity.js"; export { @@ -353,7 +363,7 @@ export { SELF_SERVE_MCP_RESEARCH, } from "./self-serve-mcp-research.js"; export * from "./validators/status-card.js"; -export { appDefinitionSchema, appDefinitionsSchema, connectionMethodDefSchema } from "./validators/app-definition.js"; +export { appDefinitionSchema, appDefinitionsSchema, connectionMethodDefSchema, reviewedToolsSchema } from "./validators/app-definition.js"; export * from "./types/chat-channels.js"; export * from "./types/chat-github.js"; export * from "./validators/chat-github.js"; @@ -1685,6 +1695,8 @@ export type { PluginJobRunRecord, PluginWebhookDeliveryRecord, AppDefinition, + AppPluginSource, + AppReviewedTools, ConnectionMethodDef, FieldDef, OAuthRedirectConstraints, diff --git a/packages/shared/src/plugin-apps.test.ts b/packages/shared/src/plugin-apps.test.ts new file mode 100644 index 00000000000..5f6d2f7cd49 --- /dev/null +++ b/packages/shared/src/plugin-apps.test.ts @@ -0,0 +1,169 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { APP_DEFINITIONS } from "./app-definitions.generated.js"; +import { + getAppStoreDefinition, + getConnectableAppDefinition, + isConnectableAppSlug, + setPluginAppDefinitions, +} from "./app-definitions.js"; +import { getAppDefinitionForApplicationKey } from "./connector-identity.js"; +import { + isPluginAppSlug, + parsePluginAppSlug, + pluginAppDefinition, + pluginAppSlug, + reviewedToolRisk, +} from "./plugin-apps.js"; +import type { AppDefinition } from "./types/app-definition.js"; +import { appDefinitionSchema } from "./validators/app-definition.js"; +import { pluginManifestV1Schema } from "./validators/plugin.js"; + +const circleback = APP_DEFINITIONS.find((app) => app.slug === "circleback") as AppDefinition; +const manifest = { + id: "example.meetings", + apiVersion: 1, + version: "1.0.0", + displayName: "Meetings", + description: "Meeting connectors", + author: "Tests", + categories: ["connector"], + capabilities: ["connectors.provide"], + entrypoints: { worker: "worker.js" }, + apps: [structuredClone(circleback)], +}; + +afterEach(() => setPluginAppDefinitions([])); + +describe("plugin app manifests", () => { + it("accepts apps that use the built-in app-definition schema with connectors.provide", () => { + const parsed = pluginManifestV1Schema.parse(manifest); + expect(parsed.apps?.[0]).toMatchObject({ slug: "circleback", name: "Circleback" }); + }); + + it("requires connectors.provide for apps", () => { + const result = pluginManifestV1Schema.safeParse({ ...manifest, capabilities: ["agent.tools.register"] }); + expect(result.success).toBe(false); + expect(JSON.stringify(result.error?.issues)).toContain("connectors.provide"); + }); + + it("rejects duplicate slugs within one plugin", () => { + const result = pluginManifestV1Schema.safeParse({ ...manifest, apps: [circleback, circleback] }); + expect(result.success).toBe(false); + expect(JSON.stringify(result.error?.issues)).toContain("Duplicate app slug"); + }); + + it("validates each app with the built-in app-definition schema", () => { + const { methods: _methods, ...withoutMethods } = circleback; + expect(pluginManifestV1Schema.safeParse({ ...manifest, apps: [withoutMethods] }).success).toBe(false); + expect(pluginManifestV1Schema.safeParse({ ...manifest, apps: [{ ...circleback, slug: "Not A Slug" }] }).success).toBe(false); + }); + + it.each(["plugin", "aiConnectionRouter", "experimentalFeatureKey", "availability"])("rejects host-derived field %s", (field) => { + const values: Record = { + plugin: { pluginKey: "other.plugin", appSlug: "circleback" }, + aiConnectionRouter: { pluginKey: "example.meetings" }, + experimentalFeatureKey: "enableMemoryConnectors", + availability: { available: true }, + }; + expect(pluginManifestV1Schema.safeParse({ ...manifest, apps: [{ ...circleback, [field]: values[field] }] }).success).toBe(false); + }); + + it("limits plugin app methods to tool transports a definition can fully describe", () => { + const method = circleback.methods[0]!; + for (const changed of [ + { ...method, transport: "rest_api" }, + { ...method, transport: "chat_sdk" }, + { ...method, purpose: "channel" }, + { ...method, provider: "slack" }, + ]) { + expect(pluginManifestV1Schema.safeParse({ ...manifest, apps: [{ ...circleback, methods: [changed] }] }).success).toBe(false); + } + }); +}); + +describe("plugin app credentials", () => { + const asana = APP_DEFINITIONS.find((app) => app.slug === "asana") as AppDefinition; + const managed = asana.methods.find((method) => method.oauthStrategy === "paperclip_cloud_connector")!; + + it("allows a managed OAuth profile only with the built-in connector's endpoint", () => { + const copy = { ...structuredClone(asana), methods: [structuredClone(managed)] }; + expect(pluginManifestV1Schema.safeParse({ ...manifest, apps: [copy] }).success).toBe(true); + const redirected = structuredClone(copy); + redirected.methods[0]!.defaults = { ...redirected.methods[0]!.defaults, serverUrl: "https://plugin.example.test/mcp" }; + const result = pluginManifestV1Schema.safeParse({ ...manifest, apps: [redirected] }); + expect(result.success).toBe(false); + expect(JSON.stringify(result.error?.issues)).toContain("managed OAuth profile"); + }); + + it("rejects Vercel Connect credentials in plugin apps", () => { + const vercel = APP_DEFINITIONS.flatMap((app) => app.methods).find((method) => method.credentialSources?.vercelConnect); + expect(vercel).toBeTruthy(); + const app = { ...structuredClone(circleback), methods: [{ ...structuredClone(circleback.methods[0]!), auth: "api_key", ownershipModes: ["customer"], + keyPlacement: { location: "header", name: "Authorization", prefix: "Bearer " }, credentialSources: vercel!.credentialSources }] }; + expect(pluginManifestV1Schema.safeParse({ ...manifest, apps: [app] }).success).toBe(false); + }); + + it("rejects a plugin id and slug too long for the connect API", () => { + expect(pluginManifestV1Schema.safeParse({ ...manifest, id: `a${"b".repeat(150)}` }).success).toBe(false); + }); +}); + +describe("plugin app slugs", () => { + it("namespaces by plugin key and reads the owner back from the slug", () => { + const slug = pluginAppSlug("example.meetings", "circleback"); + expect(slug).not.toBe("circleback"); + expect(slug).toMatch(/^[a-z0-9]+(?:-[a-z0-9]+)*$/); + expect(parsePluginAppSlug(slug)).toEqual({ pluginKey: "example.meetings", appSlug: "circleback" }); + expect(isPluginAppSlug("circleback")).toBe(false); + expect(isPluginAppSlug(pluginAppSlug("other_plugin-2", "a-b"))).toBe(true); + expect(parsePluginAppSlug(`plugin-${"zz"}-x`)).toBeNull(); + }); + + it("keeps a plugin copy of a built-in app separate from the built-in one", () => { + const definition = pluginAppDefinition("example.meetings", circleback); + expect(appDefinitionSchema.parse(definition)).toMatchObject({ plugin: { pluginKey: "example.meetings", appSlug: "circleback" } }); + expect(getConnectableAppDefinition(definition.slug)).toBeNull(); + + setPluginAppDefinitions([definition]); + expect(getConnectableAppDefinition(definition.slug)).toEqual(definition); + expect(getAppStoreDefinition(definition.slug)).toEqual(definition); + expect(isConnectableAppSlug(definition.slug)).toBe(true); + expect(getAppDefinitionForApplicationKey(`app-gallery:${definition.slug}:00000000-0000-4000-8000-000000000000`)).toEqual(definition); + // The built-in app is never shadowed. + expect(getConnectableAppDefinition("circleback")).toBe(circleback); + + setPluginAppDefinitions([]); + expect(getConnectableAppDefinition(definition.slug)).toBeNull(); + }); +}); + +describe("reviewed tool risk", () => { + const review = circleback.reviewedTools!; + + it("classifies Circleback's reviewed tools from its definition", () => { + expect(reviewedToolRisk(review, { name: "SearchMeetings" })).toBe("read"); + expect(reviewedToolRisk(review, { name: "DisplayMeetings" })).toBe("read"); + // The generic classifier reads share and submit verbs as reads. + expect(reviewedToolRisk(review, { name: "ShareMeeting" })).toBe("write"); + expect(reviewedToolRisk(review, { name: "SubmitFeedback" })).toBe("write"); + expect(reviewedToolRisk(review, { name: "DeleteFolder" })).toBe("destructive"); + expect(reviewedToolRisk(review, { name: "BrandNewTool" })).toBe("write"); + }); + + it("lets provider hints raise risk but never lower it", () => { + expect(reviewedToolRisk(review, { name: "SearchMeetings", annotations: { readOnlyHint: false } })).toBe("write"); + expect(reviewedToolRisk(review, { name: "SearchMeetings", annotations: { destructiveHint: true } })).toBe("destructive"); + expect(reviewedToolRisk(review, { name: "DeleteTag", annotations: { readOnlyHint: true } })).toBe("destructive"); + expect(reviewedToolRisk(review, { name: "ShareFolder", annotations: { readOnlyHint: true } })).toBe("write"); + }); + + it("never lowers a destructive review because of a write hint", () => { + const strict = { ...review, unlisted: "destructive" as const }; + expect(reviewedToolRisk(strict, { name: "BrandNewTool", annotations: { readOnlyHint: false } })).toBe("destructive"); + expect(reviewedToolRisk(strict, { name: "BrandNewTool", annotations: { writeHint: true } })).toBe("destructive"); + }); + + it("rejects a tool listed at two risk levels", () => { + expect(appDefinitionSchema.safeParse({ ...circleback, reviewedTools: { ...review, write: ["SearchMeetings"] } }).success).toBe(false); + }); +}); diff --git a/packages/shared/src/plugin-apps.ts b/packages/shared/src/plugin-apps.ts new file mode 100644 index 00000000000..59e63a67387 --- /dev/null +++ b/packages/shared/src/plugin-apps.ts @@ -0,0 +1,84 @@ +import type { AppDefinition, AppReviewedTools } from "./types/app-definition.js"; +import type { ToolRiskLevel } from "./constants.js"; + +/** + * Plugin-provided connectors. + * + * A plugin declares connector types (`apps`) with the same schema as the + * built-in app definitions. The host namespaces each slug by plugin key so a + * plugin app can never shadow, or be shadowed by, a built-in app or another + * plugin's app. The namespace is reversible: the owning plugin can be read + * back from the slug alone, so availability checks never depend on extra + * columns on connection rows. + */ +const PLUGIN_APP_SLUG = /^plugin-((?:[0-9a-f]{2})+)-([a-z0-9]+(?:-[a-z0-9]+)*)$/; + +const PLUGIN_KEY = /^[a-z0-9][a-z0-9._-]*$/; + +/** Longest namespaced slug the connect API accepts (`galleryKey`). */ +export const PLUGIN_APP_SLUG_MAX_LENGTH = 300; + +export function pluginAppSlug(pluginKey: string, appSlug: string): string { + const encoded = Array.from(pluginKey, (character) => character.charCodeAt(0).toString(16).padStart(2, "0")).join(""); + return `plugin-${encoded}-${appSlug}`; +} + +export function parsePluginAppSlug(slug: unknown): { pluginKey: string; appSlug: string } | null { + if (typeof slug !== "string") return null; + const match = PLUGIN_APP_SLUG.exec(slug); + if (!match) return null; + const pluginKey = match[1]!.match(/../g)!.map((pair) => String.fromCharCode(parseInt(pair, 16))).join(""); + return PLUGIN_KEY.test(pluginKey) ? { pluginKey, appSlug: match[2]! } : null; +} + +export function isPluginAppSlug(slug: unknown): boolean { + return parsePluginAppSlug(slug) !== null; +} + +/** The catalog entry the host serves for one app a plugin declares. */ +export function pluginAppDefinition(pluginKey: string, app: AppDefinition): AppDefinition { + const { plugin: _plugin, aiConnectionRouter: _router, experimentalFeatureKey: _feature, ...declared } = app; + return { + ...structuredClone(declared), + slug: pluginAppSlug(pluginKey, app.slug), + plugin: { pluginKey, appSlug: app.slug }, + }; +} + +/** The connector slug a saved connection or application row was created from. */ +export function connectionSourceSlug(row: { + config?: Record | null; + transportConfig?: Record | null; + metadata?: Record | null; +}): string | null { + for (const candidate of [ + row.config?.sourceTemplateKey, + row.transportConfig?.sourceTemplateKey, + row.metadata?.sourceTemplateKey, + row.metadata?.galleryKey, + ]) { + if (typeof candidate === "string" && candidate) return candidate; + } + return null; +} + +/** + * Risk for one tool under a connector's reviewed tool list. Provider hints + * that mark a tool destructive or writable win over the list, so a provider + * can raise a tool's risk but never lower it below the review. + */ +export function reviewedToolRisk( + review: AppReviewedTools, + tool: { name: string; annotations?: Record }, +): ToolRiskLevel { + const reviewed: ToolRiskLevel = review.destructive?.includes(tool.name) ? "destructive" + : review.write?.includes(tool.name) ? "write" + : review.read?.includes(tool.name) ? "read" + : review.unlisted ?? "write"; + const annotations = tool.annotations ?? {}; + const hinted: ToolRiskLevel = annotations.destructiveHint === true || annotations.destructive === true ? "destructive" + : annotations.readOnlyHint === false || annotations.writeHint === true ? "write" + : "read"; + const rank = { read: 0, write: 1, destructive: 2 } as Record; + return (rank[hinted] ?? 0) > (rank[reviewed] ?? 0) ? hinted : reviewed; +} diff --git a/packages/shared/src/types/app-definition.ts b/packages/shared/src/types/app-definition.ts index f55fad80e9c..1a70bb5c6f6 100644 --- a/packages/shared/src/types/app-definition.ts +++ b/packages/shared/src/types/app-definition.ts @@ -3,7 +3,10 @@ export type AppCategory = "ai"|"analytics"|"commerce"|"communication"|"content"| export type OAuthRedirectConstraints = "https-or-loopback-http"; export interface FieldDef { key:string; label:string; type:"text"|"password"|"textarea"|"datetime"|"select"|"checkbox"; required?:boolean; advanced?:boolean; hidden?:boolean; placeholder?:string; helperMd?:string; secret?:boolean; prefix?:string; defaultValue?:string|boolean; validation?:{pattern?:string;maxLength?:number}; options?:Array<{value:string;label:string}>; transport?:{location:"query"|"header";name:string;format?:"string"|"csv"|"boolean";omitFalse?:boolean} } export interface ConnectionMethodDef { ai?: import("../ai-connections.js").AiConnectionMetadata; key:string; label?:string; purpose?:ToolConnectionPurpose; provider?:"slack"|"github"|"discord"|"microsoft-teams"|"telegram"|"agentmail"|"imessage-photon"|"speko"; transport:ToolConnectionTransport; auth:"oauth"|"api_key"|"none"; oauthStrategy?:"paperclip_cloud_connector"|"paperclip_id_connector"; connectorProfile?:string; oauthClientSecretRequired?:boolean; oauthClientRegistration?:"dcr"; capabilityProfile?:{key:string;label:string;description?:string}; grantKinds?:ConnectionGrantKind[]; ownershipModes:ToolConnectionOwnership[]; whenToUse:string; defaults?:{serverUrl?:string;serverUrlTemplate?:string;discoveryUrl?:string|null;serviceHost?:string;templateKey?:string;authorizationEndpoint?:string;tokenEndpoint?:string;metadataUrl?:string;scopesHint?:string[];oauthAuthorizationParams?:{access_type?:"offline";prompt?:"consent"};toolArgumentDefaults?:Record;mcpSessionRequired?:boolean}; tenantFields?:FieldDef[]; extensionFields?:FieldDef[]; configRequirements?:{atLeastOneOf?:string[]}; credentialFields?:FieldDef[]; keyPlacement?:{location:"header"|"query"|"body_json"|"env";name:string;prefix?:string|null}; credentialSources?:{vercelConnect?:{services:string[];principalModes:VercelConnectPrincipalMode[];scopes:string[];header:{name:string;prefix?:string|null}}}; guidanceMd:string; consoleLinks?:{register?:string;keys?:string;settings?:string;docs?:string}; warnings?:string[]; variants?:Array<{key:string;label:string;whenToUse:string;tenantFields?:FieldDef[]}>; riskTier:"S1"|"S2"|"S3"|"S4"; requiredResourceFilters?:string[] } -export interface AppDefinition { experimentalFeatureKey?: import("../feature-catalog.js").InstanceFeatureKey; aiConnectionRouter?: { pluginKey: string }; agentInstructions?: import("../connection-instructions.js").ConnectionInstructionTemplate; schemaVersion:1; slug:string; name:string; description:string; categories:AppCategory[]; tags?:string[]; featured?:boolean; branding:{logoUrl:string;darkLogoUrl?:string;backgroundColor?:string;accentColor?:string}; urlPatterns:string[]; docsUrl?:string; setupPrerequisite?:{title:string;description:string;steps?:string[];actionLabel:string;actionUrl:string}; redirectConstraints?:OAuthRedirectConstraints; methods:ConnectionMethodDef[]; suggestable?:boolean; availability?:{available:boolean;reason?:string;robotEmail?:string}; ownershipAvailability?:Partial> } +export interface AppReviewedTools { reviewedAt:string; sourceUrl?:string; read?:string[]; write?:string[]; destructive?:string[]; unlisted?:"read"|"write"|"destructive"; quarantineNewEntries?:boolean } +/** Present only on connectors a plugin provides; `slug` is then namespaced by plugin key. */ +export interface AppPluginSource { pluginKey:string; appSlug:string } +export interface AppDefinition { experimentalFeatureKey?: import("../feature-catalog.js").InstanceFeatureKey; aiConnectionRouter?: { pluginKey: string }; plugin?: AppPluginSource; reviewedTools?: AppReviewedTools; agentInstructions?: import("../connection-instructions.js").ConnectionInstructionTemplate; schemaVersion:1; slug:string; name:string; description:string; categories:AppCategory[]; tags?:string[]; featured?:boolean; branding:{logoUrl:string;darkLogoUrl?:string;backgroundColor?:string;accentColor?:string}; urlPatterns:string[]; docsUrl?:string; setupPrerequisite?:{title:string;description:string;steps?:string[];actionLabel:string;actionUrl:string}; redirectConstraints?:OAuthRedirectConstraints; methods:ConnectionMethodDef[]; suggestable?:boolean; availability?:{available:boolean;reason?:string;robotEmail?:string}; ownershipAvailability?:Partial> } export type SelfServeMcpAuthMode = | "dcr" diff --git a/packages/shared/src/types/plugin.ts b/packages/shared/src/types/plugin.ts index 78519a2bbda..af85e6aa845 100644 --- a/packages/shared/src/types/plugin.ts +++ b/packages/shared/src/types/plugin.ts @@ -755,6 +755,14 @@ export interface PaperclipPluginManifestV1 { webhooks?: PluginWebhookDeclaration[]; /** Agent tools this plugin contributes. Requires `agent.tools.register` capability. */ tools?: PluginToolDeclaration[]; + /** + * Connector types this plugin adds to the Connectors catalog. Each entry + * uses the built-in app-definition schema; the host namespaces its slug by + * plugin key. Declaring an app grants no tools: agents get tools only from + * a connection installed for them or for the whole company. Requires the + * `connectors.provide` capability. + */ + apps?: import("./app-definition.js").AppDefinition[]; /** Restricted plugin-owned database namespace declaration. */ database?: PluginDatabaseDeclaration; /** Scoped JSON API routes mounted under `/api/plugins/:pluginId/api/*`. */ diff --git a/packages/shared/src/validators/app-definition.ts b/packages/shared/src/validators/app-definition.ts index 9fb660249ea..ea99fb75ea9 100644 --- a/packages/shared/src/validators/app-definition.ts +++ b/packages/shared/src/validators/app-definition.ts @@ -9,7 +9,33 @@ const appBrandAssetUrlSchema=z.string().refine((value)=>{ },{message:"Brand assets must be HTTPS URLs or local /brands/apps SVG/PNG paths"}); const field=z.object({key:z.string().min(1),label:z.string().min(1),type:z.enum(["text","password","textarea","datetime","select","checkbox"]),required:z.boolean().optional(),advanced:z.boolean().optional(),hidden:z.boolean().optional(),placeholder:z.string().optional(),helperMd:z.string().optional(),secret:z.boolean().optional(),prefix:z.string().optional(),defaultValue:z.union([z.string(),z.boolean()]).optional(),validation:z.object({pattern:z.string().optional(),maxLength:z.number().int().positive().optional()}).optional(),options:z.array(z.object({value:z.string(),label:z.string()})).optional(),transport:z.object({location:z.enum(["query","header"]),name:z.string().min(1),format:z.enum(["string","csv","boolean"]).optional(),omitFalse:z.boolean().optional()}).optional()}).superRefine((v,c)=>{if(v.required&&v.type!=="checkbox"&&!v.placeholder)c.addIssue({code:"custom",message:"Required fields need placeholders",path:["placeholder"]});if(v.type==="select"&&(!v.options||v.options.length===0))c.addIssue({code:"custom",message:"Select fields need options",path:["options"]});if(v.hidden&&v.defaultValue===undefined)c.addIssue({code:"custom",message:"Hidden fields need defaults",path:["defaultValue"]})}); export const connectionMethodDefSchema=z.object({key:z.string().min(1),label:z.string().min(1).optional(),purpose:z.union([toolConnectionPurposeSchema,z.literal("ai")]).optional(),provider:z.enum(["slack","github","discord","microsoft-teams","telegram","speko","agentmail","imessage-photon"]).optional(),transport:z.union([toolConnectionTransportSchema,z.literal("runtime_auth")]),ai:aiConnectionMetadataSchema.optional(),auth:z.enum(["oauth","api_key","none"]),oauthStrategy:z.enum(["paperclip_cloud_connector","paperclip_id_connector"]).optional(),connectorProfile:z.string().regex(/^[a-z0-9]+(?:[.-][a-z0-9]+)*$/).optional(),oauthClientSecretRequired:z.boolean().optional(),oauthClientRegistration:z.literal("dcr").optional(),capabilityProfile:z.object({key:z.string().min(1),label:z.string().min(1),description:z.string().min(1).optional()}).optional(),grantKinds:z.array(connectionGrantKindSchema).min(1).optional(),ownershipModes:z.array(toolConnectionOwnershipSchema).min(1),whenToUse:z.string().min(1),defaults:z.object({serverUrl:z.string().url().optional(),serverUrlTemplate:z.string().regex(/^https:\/\//).optional(),discoveryUrl:z.string().url().nullable().optional(),serviceHost:z.string().optional(),templateKey:z.string().optional(),authorizationEndpoint:z.string().url().optional(),tokenEndpoint:z.string().url().optional(),metadataUrl:z.string().url().optional(),scopesHint:z.array(z.string()).optional(),oauthAuthorizationParams:z.object({access_type:z.literal("offline").optional(),prompt:z.literal("consent").optional()}).optional(),toolArgumentDefaults:z.record(z.string(),z.unknown()).optional(),mcpSessionRequired:z.boolean().optional()}).optional(),tenantFields:z.array(field).optional(),extensionFields:z.array(field).optional(),configRequirements:z.object({atLeastOneOf:z.array(z.string().min(1)).min(1).optional()}).optional(),credentialFields:z.array(field).optional(),keyPlacement:z.object({location:z.enum(["header","query","body_json","env"]),name:z.string().min(1),prefix:z.string().nullable().optional()}).optional(),credentialSources:z.object({vercelConnect:z.object({services:z.array(z.string().min(1)).min(1),principalModes:z.array(z.enum(["app","user"])).min(1),scopes:z.array(z.string().min(1)).min(1),header:z.object({name:z.string().min(1),prefix:z.string().nullable().optional()})}).optional()}).optional(),guidanceMd:z.string().min(1),consoleLinks:z.object({register:z.string().url().optional(),keys:z.string().url().optional(),settings:z.string().url().optional(),docs:z.string().url().optional()}).optional(),warnings:z.array(z.string()).optional(),variants:z.array(z.object({key:z.string(),label:z.string(),whenToUse:z.string(),tenantFields:z.array(field).optional()})).optional(),riskTier:z.enum(["S1","S2","S3","S4"]),requiredResourceFilters:z.array(z.string()).optional()}).superRefine((v,c)=>{if((v.transport==="runtime_auth")!==Boolean(v.ai))c.addIssue({code:"custom",message:"Runtime authentication requires AI metadata and AI metadata requires runtime_auth",path:["ai"]});if(v.ai&&!AI_CONNECTION_CAPABILITIES[v.ai.provider].methods[v.ai.method])c.addIssue({code:"custom",message:"Unsupported AI sign-in method",path:["ai","method"]});if(v.ai&&v.auth!==(v.ai.method==="subscription"?"oauth":"api_key"))c.addIssue({code:"custom",message:"AI sign-in method must match authentication",path:["auth"]});if(v.oauthClientRegistration&&(v.auth!=="oauth"||v.transport!=="mcp_remote"||!v.ownershipModes.includes("dcr")))c.addIssue({code:"custom",message:"DCR client registration requires a remote MCP OAuth method with DCR ownership",path:["oauthClientRegistration"]});if(v.defaults?.mcpSessionRequired&&v.transport!=="mcp_remote")c.addIssue({code:"custom",message:"MCP session initialization preferences require remote MCP transport",path:["defaults","mcpSessionRequired"]});const purpose=v.purpose??"tool";if((purpose==="ai")!==(v.transport==="runtime_auth"))c.addIssue({code:"custom",message:"AI methods require runtime_auth and runtime_auth requires AI purpose",path:["purpose"]});if(["chat_sdk","voice"].includes(v.transport)&&purpose!=="channel")c.addIssue({code:"custom",message:"Chat SDK methods must be channel connections",path:["purpose"]});if(purpose==="channel"&&!["chat_sdk","voice"].includes(v.transport)&&!(v.provider==="agentmail"&&v.transport==="rest_api"))c.addIssue({code:"custom",message:"Channel connections must use the Chat SDK transport",path:["transport"]});if(purpose==="channel"&&((v.provider==="speko")!==(v.transport==="voice")))c.addIssue({code:"custom",message:"Speko channels require the voice transport",path:["transport"]});if(purpose==="channel"&&!v.provider)c.addIssue({code:"custom",message:"Channel connections require a chat provider",path:["provider"]});if(v.auth==="api_key"&&!v.keyPlacement&&purpose!=="channel")c.addIssue({code:"custom",message:"API-key tool methods require keyPlacement",path:["keyPlacement"]});if(v.oauthStrategy&&v.auth!=="oauth")c.addIssue({code:"custom",message:"OAuth strategies require OAuth auth",path:["oauthStrategy"]});if(v.oauthStrategy&&!v.connectorProfile)c.addIssue({code:"custom",message:"Paperclip Cloud connector methods require connectorProfile",path:["connectorProfile"]});if(v.connectorProfile&&!v.oauthStrategy)c.addIssue({code:"custom",message:"connectorProfile requires a Paperclip Cloud OAuth strategy",path:["connectorProfile"]});if(v.credentialSources?.vercelConnect&&(v.transport!=="mcp_remote"||v.auth==="none"))c.addIssue({code:"custom",message:"Vercel Connect requires an authenticated remote MCP method",path:["credentialSources","vercelConnect"]});const keys=new Set([...(v.tenantFields??[]),...(v.extensionFields??[])].map((entry)=>entry.key));for(const key of v.configRequirements?.atLeastOneOf??[])if(!keys.has(key))c.addIssue({code:"custom",message:"Config requirement references an unknown field",path:["configRequirements","atLeastOneOf"]});if(v.defaults?.serverUrl&&v.defaults.serverUrlTemplate)c.addIssue({code:"custom",message:"Use either serverUrl or serverUrlTemplate",path:["defaults"]});for(const placeholder of v.defaults?.serverUrlTemplate?.matchAll(/\{([a-zA-Z0-9_-]+)\}/g)??[])if(!keys.has(placeholder[1]))c.addIssue({code:"custom",message:"Server URL template references an unknown field",path:["defaults","serverUrlTemplate"]})}); -export const appDefinitionSchema=z.object({experimentalFeatureKey:z.enum(INSTANCE_FEATURE_KEYS).optional(),agentInstructions:connectionInstructionTemplateSchema.optional(),aiConnectionRouter:z.object({pluginKey:z.string().min(1)}).optional(),schemaVersion:z.literal(1),slug:z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),name:z.string().min(1),description:z.string().min(1),categories:z.array(z.enum(["ai","analytics","commerce","communication","content","data","developer","productivity","other"])).min(1),tags:z.array(z.string().min(1)).optional(),featured:z.boolean().optional(),branding:z.object({logoUrl:appBrandAssetUrlSchema,darkLogoUrl:appBrandAssetUrlSchema.optional(),backgroundColor:z.string().optional(),accentColor:z.string().optional()}),urlPatterns:z.array(z.string()),docsUrl:z.string().url().optional(),setupPrerequisite:z.object({title:z.string().min(1),description:z.string().min(1),steps:z.array(z.string().min(1)).min(1).optional(),actionLabel:z.string().min(1),actionUrl:z.string().url()} ).optional(),redirectConstraints:z.enum(["https-or-loopback-http"]).optional(),methods:z.array(connectionMethodDefSchema),suggestable:z.boolean().optional(),availability:z.object({available:z.boolean(),reason:z.string().optional(),robotEmail:z.string().optional()}).optional(),ownershipAvailability:z.object({platform_shared:z.boolean().optional(),platform_provisioned:z.boolean().optional(),customer:z.boolean().optional(),dcr:z.boolean().optional()}).optional()}).superRefine((value, ctx) => { +const reviewedToolNameListSchema=z.array(z.string().min(1).max(200)).max(1000); +/** + * A connector's reviewed tool risk, declared as data so any connector (core or + * plugin-provided) gets the same classification wherever its definition goes. + * Provider hints that mark a tool destructive or writable always win; listed + * names are matched exactly, and any unlisted name gets `unlisted`. + */ +export const reviewedToolsSchema=z.object({ + reviewedAt:z.string().regex(/^\d{4}-\d{2}-\d{2}$/), + sourceUrl:z.string().url().optional(), + read:reviewedToolNameListSchema.default([]), + write:reviewedToolNameListSchema.default([]), + destructive:reviewedToolNameListSchema.default([]), + unlisted:z.enum(["read","write","destructive"]).default("write"), + quarantineNewEntries:z.boolean().default(false), +}).strict().superRefine((value,ctx)=>{ + const seen=new Map(); + for(const level of ["read","write","destructive"] as const){ + value[level].forEach((name,index)=>{ + const previous=seen.get(name); + if(previous)ctx.addIssue({code:"custom",message:`Tool ${name} is listed as both ${previous} and ${level}`,path:[level,index]}); + seen.set(name,level); + }); + } +}); +export const appDefinitionSchema=z.object({experimentalFeatureKey:z.enum(INSTANCE_FEATURE_KEYS).optional(),agentInstructions:connectionInstructionTemplateSchema.optional(),aiConnectionRouter:z.object({pluginKey:z.string().min(1)}).optional(),plugin:z.object({pluginKey:z.string().min(1),appSlug:z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/)}).strict().optional(),reviewedTools:reviewedToolsSchema.optional(),schemaVersion:z.literal(1),slug:z.string().regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/),name:z.string().min(1),description:z.string().min(1),categories:z.array(z.enum(["ai","analytics","commerce","communication","content","data","developer","productivity","other"])).min(1),tags:z.array(z.string().min(1)).optional(),featured:z.boolean().optional(),branding:z.object({logoUrl:appBrandAssetUrlSchema,darkLogoUrl:appBrandAssetUrlSchema.optional(),backgroundColor:z.string().optional(),accentColor:z.string().optional()}),urlPatterns:z.array(z.string()),docsUrl:z.string().url().optional(),setupPrerequisite:z.object({title:z.string().min(1),description:z.string().min(1),steps:z.array(z.string().min(1)).min(1).optional(),actionLabel:z.string().min(1),actionUrl:z.string().url()} ).optional(),redirectConstraints:z.enum(["https-or-loopback-http"]).optional(),methods:z.array(connectionMethodDefSchema),suggestable:z.boolean().optional(),availability:z.object({available:z.boolean(),reason:z.string().optional(),robotEmail:z.string().optional()}).optional(),ownershipAvailability:z.object({platform_shared:z.boolean().optional(),platform_provisioned:z.boolean().optional(),customer:z.boolean().optional(),dcr:z.boolean().optional()}).optional()}).superRefine((value, ctx) => { + if (value.plugin && value.aiConnectionRouter) ctx.addIssue({ code: "custom", message: "A plugin connector cannot also be a connection pool", path: ["plugin"] }); if (value.aiConnectionRouter) { if (value.methods.length !== 0) ctx.addIssue({ code: "custom", message: "Pooled connectors use existing connections, not authentication methods", path: ["methods"] }); if (!value.categories.includes("ai")) ctx.addIssue({ code: "custom", message: "Pooled connectors must use the AI category", path: ["categories"] }); diff --git a/packages/shared/src/validators/json-schema.ts b/packages/shared/src/validators/json-schema.ts new file mode 100644 index 00000000000..b6cba6a3f76 --- /dev/null +++ b/packages/shared/src/validators/json-schema.ts @@ -0,0 +1,18 @@ +import { z } from "zod"; + +/** + * Loose JSON Schema object check shared by plugin manifests and tool catalog + * validators. Accepts any object with a `type`, `$ref`, or composition keyword + * (`oneOf`/`anyOf`/`allOf`), and the empty object. Kept in its own module so + * those validators can import each other without a load-order cycle. + * + * @see PLUGIN_SPEC.md §10.1 — Manifest shape + */ +export const jsonSchemaSchema = z.record(z.string(), z.unknown()).refine( + (val) => { + // Must have a "type" field if non-empty, or be a valid JSON Schema object + if (Object.keys(val).length === 0) return true; + return typeof val.type === "string" || val.$ref !== undefined || val.oneOf !== undefined || val.anyOf !== undefined || val.allOf !== undefined; + }, + { message: "Must be a valid JSON Schema object (requires at least a 'type', '$ref', or composition keyword)" }, +); diff --git a/packages/shared/src/validators/plugin.ts b/packages/shared/src/validators/plugin.ts index 37337317b71..3af6eadb2a4 100644 --- a/packages/shared/src/validators/plugin.ts +++ b/packages/shared/src/validators/plugin.ts @@ -27,30 +27,18 @@ import { ISSUE_SURFACE_VISIBILITIES, } from "../constants.js"; import { routineVariableSchema } from "./routine.js"; +import { appDefinitionSchema } from "./app-definition.js"; +import { CONNECTABLE_APP_DEFINITIONS } from "../app-definitions.js"; +import { PLUGIN_APP_SLUG_MAX_LENGTH, pluginAppSlug } from "../plugin-apps.js"; +import { jsonSchemaSchema } from "./json-schema.js"; import { externalObjectProviderKeySchema, externalObjectTypeSchema } from "./external-object.js"; // --------------------------------------------------------------------------- // JSON Schema placeholder – a permissive validator for JSON Schema objects // --------------------------------------------------------------------------- -/** - * Permissive validator for JSON Schema objects. Accepts any `Record` - * that contains at least a `type`, `$ref`, or composition keyword (`oneOf`/`anyOf`/`allOf`). - * Empty objects are also accepted. - * - * Used to validate `instanceConfigSchema` and `parametersSchema` fields in the - * plugin manifest without fully parsing JSON Schema. - * - * @see PLUGIN_SPEC.md §10.1 — Manifest shape - */ -export const jsonSchemaSchema = z.record(z.string(), z.unknown()).refine( - (val) => { - // Must have a "type" field if non-empty, or be a valid JSON Schema object - if (Object.keys(val).length === 0) return true; - return typeof val.type === "string" || val.$ref !== undefined || val.oneOf !== undefined || val.anyOf !== undefined || val.allOf !== undefined; - }, - { message: "Must be a valid JSON Schema object (requires at least a 'type', '$ref', or composition keyword)" }, -); +/** Validates `instanceConfigSchema` and `parametersSchema` fields (see `json-schema.ts`). */ +export { jsonSchemaSchema }; // --------------------------------------------------------------------------- // Manifest sub-type schemas @@ -836,6 +824,7 @@ export const pluginManifestV1Schema = z.object({ jobs: z.array(pluginJobDeclarationSchema).optional(), webhooks: z.array(pluginWebhookDeclarationSchema).optional(), tools: z.array(pluginToolDeclarationSchema).optional(), + apps: z.array(appDefinitionSchema).max(50).optional(), database: pluginDatabaseDeclarationSchema.optional(), apiRoutes: z.array(pluginApiRouteDeclarationSchema).optional(), environmentDrivers: z.array(pluginEnvironmentDriverDeclarationSchema).optional(), @@ -903,6 +892,57 @@ export const pluginManifestV1Schema = z.object({ ctx.addIssue({ code: z.ZodIssueCode.custom, message: "ai.connections.route is required for aiConnectionRouter", path: ["capabilities"] }); } + // Connector types require connectors.provide. A plugin app only adds a + // connector type to the Connectors catalog; tool access still comes from + // a connection and its agent or company install, exactly like built-in apps. + if (manifest.apps && manifest.apps.length > 0 && !manifest.capabilities.includes("connectors.provide")) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Capability 'connectors.provide' is required when apps are declared", path: ["capabilities"] }); + } + const appSlugs = new Set(); + for (const [index, app] of (manifest.apps ?? []).entries()) { + if (pluginAppSlug(manifest.id, app.slug).length > PLUGIN_APP_SLUG_MAX_LENGTH) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Plugin id and app slug "${app.slug}" are too long together`, path: ["apps", index, "slug"] }); + } + if (appSlugs.has(app.slug)) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Duplicate app slug "${app.slug}"`, path: ["apps", index, "slug"] }); + } + appSlugs.add(app.slug); + for (const field of ["plugin", "aiConnectionRouter", "experimentalFeatureKey", "availability"] as const) { + if (app[field] !== undefined) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Plugin apps cannot set ${field}; the host derives it`, path: ["apps", index, field] }); + } + } + for (const [methodIndex, method] of app.methods.entries()) { + // A plugin contributes catalog data only. Transports that need reviewed + // host code per provider (REST adapters, chat channels, AI runtimes) + // cannot be satisfied by a definition alone. + if (method.transport !== "mcp_remote" && method.transport !== "local_stdio") { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Plugin app methods support the mcp_remote and local_stdio transports, not ${method.transport}`, path: ["apps", index, "methods", methodIndex, "transport"] }); + } + if ((method.purpose && method.purpose !== "tool") || method.provider || method.ai) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Plugin app methods provide agent tools only", path: ["apps", index, "methods", methodIndex] }); + } + // Host-managed credentials (a Paperclip-brokered OAuth token or Vercel + // Connect) must only reach the provider they were issued for. A plugin + // method may reuse a managed profile only with the exact endpoint of the + // built-in method that declares that profile. + if (method.credentialSources?.vercelConnect) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "Plugin app methods cannot use Vercel Connect credentials", path: ["apps", index, "methods", methodIndex, "credentialSources"] }); + } + if (method.oauthStrategy) { + const pinned = CONNECTABLE_APP_DEFINITIONS.some((core) => core.methods.some((coreMethod) => + coreMethod.oauthStrategy === method.oauthStrategy + && coreMethod.connectorProfile === method.connectorProfile + && Boolean(coreMethod.defaults?.serverUrl) + && coreMethod.defaults?.serverUrl === method.defaults?.serverUrl + && !method.defaults?.serverUrlTemplate)); + if (!pinned) { + ctx.addIssue({ code: z.ZodIssueCode.custom, message: "A managed OAuth profile must use the endpoint of the built-in connector that declares it", path: ["apps", index, "methods", methodIndex, "defaults", "serverUrl"] }); + } + } + } + } + // tools require agent.tools.register (PLUGIN_SPEC.md §11) if (manifest.tools && manifest.tools.length > 0) { if (!manifest.capabilities.includes("agent.tools.register")) { diff --git a/packages/shared/src/validators/tool-access.ts b/packages/shared/src/validators/tool-access.ts index f6ada4ebdc2..4cd2b549539 100644 --- a/packages/shared/src/validators/tool-access.ts +++ b/packages/shared/src/validators/tool-access.ts @@ -38,7 +38,7 @@ import { mcpRemoteHeaderNameFromConfigPath, mcpRemoteHeaderRejectionMessage, } from "../mcp-remote-headers.js"; -import { jsonSchemaSchema } from "./plugin.js"; +import { jsonSchemaSchema } from "./json-schema.js"; import { objectWithoutDefaults } from "./partial.js"; export const toolApplicationTypeSchema = z.enum(TOOL_APPLICATION_TYPES); @@ -462,7 +462,7 @@ export const googleWorkspaceServiceSelectionSchema = z.object({ export const connectToolAppSchema = z.object({ workspaceServices: googleWorkspaceServiceSelectionSchema.optional(), agentInstructions: connectionAgentInstructionsSchema.nullable().optional(), - galleryKey: z.string().trim().min(1).max(120).optional(), + galleryKey: z.string().trim().min(1).max(300).optional(), connectionMethodKey: z.string().trim().min(1).max(120).optional(), link: z.string().trim().url().max(2000).optional(), name: z.string().trim().min(1).max(160).optional(), diff --git a/server/src/__tests__/fixtures/plugin-connectors/circleback-parity/circleback.json b/server/src/__tests__/fixtures/plugin-connectors/circleback-parity/circleback.json new file mode 100644 index 00000000000..717d53e78a4 --- /dev/null +++ b/server/src/__tests__/fixtures/plugin-connectors/circleback-parity/circleback.json @@ -0,0 +1,82 @@ +{ + "schemaVersion": 1, + "slug": "circleback", + "name": "Circleback", + "description": "Search meeting notes, transcripts, action items, calendar events and emails, and show meetings as cards in chat.", + "categories": [ + "productivity" + ], + "featured": false, + "branding": { + "logoUrl": "/brands/apps/circleback.png" + }, + "urlPatterns": [ + "https://circleback.ai/*", + "https://app.circleback.ai/*" + ], + "docsUrl": "https://circleback.ai/docs/support/platform/circleback-mcp", + "redirectConstraints": "https-or-loopback-http", + "reviewedTools": { + "reviewedAt": "2026-11-12", + "sourceUrl": "https://circleback.ai/docs/support/platform/circleback-mcp", + "read": [ + "SearchMeetings", + "ReadMeetings", + "GetTranscriptsForMeetings", + "SearchTranscripts", + "SearchActionItems", + "SearchCalendarEvents", + "SearchEmails", + "FindProfiles", + "FindCompanies", + "ListTags", + "ListFolders", + "ReadFolders", + "ListTeams", + "SearchSupportArticles", + "DisplayMeetings", + "DisplayActionItems", + "DisplayCalendarEvents" + ], + "destructive": [ + "DeleteActionItem", + "DeleteTag", + "DeleteFolder" + ], + "unlisted": "write", + "quarantineNewEntries": false + }, + "methods": [ + { + "key": "mcp-oauth", + "label": "Sign in with Circleback", + "transport": "mcp_remote", + "auth": "oauth", + "ownershipModes": [ + "dcr" + ], + "whenToUse": "Use browser sign-in for Circleback's hosted MCP server.", + "defaults": { + "serverUrl": "https://circleback.ai/api/mcp", + "scopesHint": [ + "user", + "user:write" + ] + }, + "guidanceMd": "Sign in to Circleback and approve access. The connection acts as the Circleback user who signs in and sees the meetings, action items, calendar events and connected email that user can see. Write tools start enabled and remain governed by Paperclip's action policies.", + "warnings": [ + "A Circleback account. The connection reads the signed-in user's meetings, transcripts, calendar and connected email.", + "Circleback share tools can share meetings and folders with other people or anyone with the link, and delete tools cannot be undone. Set share and delete actions to Ask first before agents run unattended." + ], + "consoleLinks": { + "docs": "https://circleback.ai/docs/support/platform/circleback-mcp" + }, + "riskTier": "S3", + "capabilityProfile": { + "key": "write", + "label": "Read and write", + "description": "Search and read meetings, transcripts, action items, calendar events and email, and manage action items, tags, folders and meeting notes. Circleback share tools can share meetings and folders with other people or anyone with the link, and delete tools cannot be undone. Set share and delete actions to Ask first before agents run unattended." + } + } + ] +} diff --git a/server/src/__tests__/fixtures/plugin-connectors/circleback-parity/manifest.json b/server/src/__tests__/fixtures/plugin-connectors/circleback-parity/manifest.json new file mode 100644 index 00000000000..93f08314837 --- /dev/null +++ b/server/src/__tests__/fixtures/plugin-connectors/circleback-parity/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "paperclip.test-circleback-parity", + "apiVersion": 1, + "version": "0.0.1", + "displayName": "Circleback parity fixture", + "description": "Test-only plugin that provides a copy of the built-in Circleback connector. Never shipped.", + "author": "Paperclip tests", + "categories": ["connector"], + "capabilities": ["connectors.provide"], + "entrypoints": { "worker": "worker.js" } +} diff --git a/server/src/__tests__/plugin-connectors-circleback-parity.test.ts b/server/src/__tests__/plugin-connectors-circleback-parity.test.ts new file mode 100644 index 00000000000..f2a887d3cc6 --- /dev/null +++ b/server/src/__tests__/plugin-connectors-circleback-parity.test.ts @@ -0,0 +1,386 @@ +/** + * Plugin-provided connectors: Circleback parity. + * + * A test-only plugin provides a copy of the built-in Circleback definition. + * The same journey runs against the built-in connector and the plugin copy, + * and both must give the same results. The provider is a recorded MCP and + * OAuth fixture; no request leaves the host. Each hard rule for plugin + * connectors is asserted where it applies: + * + * 1. Enabling the plugin only adds the connector type to the catalog. + * 2. Connecting and signing in an account grants no tools. + * 3. Only an agent (or company) install gives an agent the tools, in + * discovery and in invocation. + * 4. A disabled plugin hides its connector and connections and reaches no + * agent; re-enabling restores the saved setup unchanged. Uninstalling + * retires the connections and revokes their credentials. + */ +import { randomUUID } from "node:crypto"; +import { readFileSync } from "node:fs"; +import express from "express"; +import request from "supertest"; +import { and, eq } from "drizzle-orm"; +import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; +import { + agents, companies, companyMemberships, companySecrets, connectionGrants, createDb, heartbeatRuns, + issues, plugins, toolConnectionInstalls, toolConnections, +} from "@paperclipai/db"; +import { + APP_DEFINITIONS, pluginAppSlug, pluginManifestV1Schema, type AppDefinition, type PaperclipPluginManifestV1, +} from "@paperclipai/shared"; +import { toolAccessService, type McpToolDescriptor } from "../services/tool-access.js"; +import { createToolGatewayService } from "../services/tool-gateway.js"; +import { retirePluginAppConnections } from "../services/plugin-app-catalog.js"; +import { connectorKeyForConnection } from "../services/connector-telemetry.js"; +import { toolAccessRoutes } from "../routes/tool-access.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const fixtureDir = new URL("./fixtures/plugin-connectors/circleback-parity/", import.meta.url); +const pluginCircleback = JSON.parse(readFileSync(new URL("circleback.json", fixtureDir), "utf8")) as AppDefinition; +const fixtureManifest = pluginManifestV1Schema.parse({ + ...JSON.parse(readFileSync(new URL("manifest.json", fixtureDir), "utf8")), + apps: [pluginCircleback], +}) as PaperclipPluginManifestV1; +const PLUGIN_KEY = fixtureManifest.id; +const PLUGIN_SLUG = pluginAppSlug(PLUGIN_KEY, "circleback"); + +const actor = { actorType: "user" as const, actorId: "circleback-parity-admin" }; +const redirectUri = "https://paperclip.fixture.test/api/tools/oauth/callback"; +const origin = "https://circleback.ai"; +const endpoint = `${origin}/api/mcp`; + +// Recorded shape of Circleback's hosted MCP catalog, trimmed to the tools +// whose risk differs between the reviewed list and the generic classifier. +const tools: McpToolDescriptor[] = [ + { name: "SearchMeetings", inputSchema: { type: "object", properties: { query: { type: "string" } } } }, + { name: "ReadMeetings", inputSchema: { type: "object" } }, + { name: "ShareMeeting", inputSchema: { type: "object" } }, + { name: "ShareFolder", inputSchema: { type: "object" } }, + { name: "SubmitFeedback", inputSchema: { type: "object" } }, + { name: "DeleteFolder", inputSchema: { type: "object" } }, + { name: "UpdateActionItem", inputSchema: { type: "object" } }, +]; + +/** One recorded Circleback provider: DCR OAuth plus the MCP endpoint. */ +function circlebackProvider() { + const issued = new Set(); + const calls: Array<{ tool: string; token: string }> = []; + let tokenCount = 0; + const fetchFixture = vi.fn(async (url: string, init: RequestInit) => { + expect(new URL(url).origin).toBe(origin); + const headers = new Headers(init.headers); + const body = String(init.body ?? ""); + if (url === endpoint && init.method === "POST") { + const token = headers.get("authorization")?.replace(/^Bearer /, "") ?? ""; + if (!issued.has(token)) { + return new Response(null, { status: 401, headers: { "www-authenticate": `Bearer resource_metadata="${origin}/.well-known/oauth-protected-resource/api/mcp"` } }); + } + const rpc = JSON.parse(body); + if (rpc.method === "initialize") return Response.json({ jsonrpc: "2.0", id: rpc.id, + result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "Circleback fixture", version: "1" } } }); + if (rpc.method === "notifications/initialized") return new Response(null, { status: 202 }); + if (rpc.method === "tools/list") return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { tools } }); + if (rpc.method === "tools/call") { + calls.push({ tool: rpc.params.name, token }); + return Response.json({ jsonrpc: "2.0", id: rpc.id, result: { content: [{ type: "text", text: `Circleback ran ${rpc.params.name}` }] } }); + } + } + if (url.includes("oauth-protected-resource")) return Response.json({ resource: endpoint, authorization_servers: [origin], scopes_supported: ["user", "user:write"] }); + if (url === `${origin}/.well-known/oauth-authorization-server`) return Response.json({ + issuer: origin, authorization_endpoint: `${origin}/oauth/authorize`, token_endpoint: `${origin}/oauth/token`, + registration_endpoint: `${origin}/oauth/register`, code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], scopes_supported: ["user", "user:write"], + }); + if (url === `${origin}/oauth/register`) return Response.json({ ...JSON.parse(body), client_id: "circleback-fixture-client" }); + if (url === `${origin}/oauth/token`) { + const accessToken = `circleback-account-${++tokenCount}-${randomUUID()}`; + issued.add(accessToken); + return Response.json({ access_token: accessToken, refresh_token: `refresh-${accessToken}`, expires_in: 3600, token_type: "Bearer", scope: "user user:write" }); + } + return new Response(null, { status: 404 }); + }); + return { fetchFixture, calls }; +} + +const support = await getEmbeddedPostgresTestSupport(); +(support.supported ? describe : describe.skip)("plugin-provided connectors: Circleback parity", () => { + let db: ReturnType; + let temp: Awaited>; + beforeAll(async () => { + temp = await startEmbeddedPostgresTestDatabase("paperclip-plugin-connectors-"); + db = createDb(temp.connectionString); + }, 60_000); + afterAll(async () => { await temp?.cleanup(); }); + + it("ships an unmodified copy of the built-in Circleback definition", () => { + expect(pluginCircleback).toEqual(APP_DEFINITIONS.find(app => app.slug === "circleback")); + }); + + async function setup() { + const [company] = await db.insert(companies).values({ name: "Circleback parity", issuePrefix: `CP${randomUUID().slice(0, 6)}` }).returning(); + await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: actor.actorId, status: "active", membershipRole: "admin" }); + const [agentA, agentB] = await db.insert(agents).values([ + { companyId: company.id, name: "Meeting analyst", role: "engineer", adapterType: "process" }, + { companyId: company.id, name: "Other agent", role: "engineer", adapterType: "process" }, + ]).returning(); + const provider = circlebackProvider(); + const service = toolAccessService(db, { remoteHttpRequest: provider.fetchFixture, remoteHttpEndpointLookup: async () => [{ address: "8.8.8.8", family: 4 }] }); + const gateway = createToolGatewayService(db, { remoteHttpRequest: provider.fetchFixture, toolActionSigningSecret: "circleback-parity-signing-key" }); + const app = express(); + app.use((req, _res, next) => { req.actor = { type: "board", userId: actor.actorId, source: "local_implicit", isInstanceAdmin: true }; next(); }); + app.use("/api", toolAccessRoutes(db, { paperclipCloudConnector: null })); + const session = async (agentId: string) => { + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Review meetings", assigneeAgentId: agentId }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId, issueId: issue.id, scopeKind: "issue", + invocationSource: "on_demand", status: "running", responsibleUserId: actor.actorId, contextSnapshot: { issueId: issue.id } }).returning(); + return { ...(await gateway.createSession({ companyId: company.id, agentId, runId: run.id, issueId: issue.id })), runId: run.id }; + }; + const sessions = { a: await session(agentA.id), b: await session(agentB.id) }; + const circlebackTools = async (token: string, galleryKey: string) => (await gateway.listToolsForSession(token)) + .filter(tool => tool.providerType === "mcp_remote_http") + .filter(tool => { + const connection = connectionsBySlug.get(galleryKey); + return connection?.has(tool.connectionId ?? ""); + }); + const connectionsBySlug = new Map>(); + const gallerySlugs = async () => (await request(app).get(`/api/companies/${company.id}/tools/gallery`)).body.apps.map((entry: { slug: string }) => entry.slug) as string[]; + return { company, agentA, agentB, provider, service, gateway, app, sessions, circlebackTools, connectionsBySlug, gallerySlugs }; + } + + async function connectAccount(f: Awaited>, galleryKey: string, { saveAgentSelection = true } = {}) { + const connected = await f.service.connectGalleryApp(f.company.id, { galleryKey, connectionMethodKey: "mcp-oauth" }, actor); + // The setup screen saves the operator's agent selection (none yet) before sign-in. + if (saveAgentSelection) await f.service.putConnectionInstalls(connected.connectionId, { installs: [] }); + const start = await f.service.startOAuth(f.company.id, connected.connectionId, { redirectUri, actor }); + const authorization = new URL(start.authorizationUrl); + expect(start.registrationSource).toBe("dcr"); + expect(authorization.origin).toBe(origin); + const signedIn = await f.service.completeOAuthCallback({ state: authorization.searchParams.get("state")!, code: `code-${randomUUID()}`, iss: origin, redirectUri, actor }); + const ids = f.connectionsBySlug.get(galleryKey) ?? new Set(); + ids.add(signedIn.connectionId); + f.connectionsBySlug.set(galleryKey, ids); + return signedIn; + } + + async function journey(f: Awaited>, galleryKey: string) { + const first = await connectAccount(f, galleryKey); + const second = await connectAccount(f, galleryKey); + const catalog = (await f.service.listCatalog(first.connectionId)) + .map(entry => ({ tool: entry.toolName, risk: entry.riskLevel, status: entry.status })) + .sort((left, right) => left.tool.localeCompare(right.tool)); + // Rule 2: two signed-in accounts, and still no agent has any tool. + const beforeInstall = { + a: (await f.circlebackTools(f.sessions.a.token, galleryKey)).length, + b: (await f.circlebackTools(f.sessions.b.token, galleryKey)).length, + }; + // Rule 3: enable the first account for agent A only. + await f.service.finishGalleryAppConnection(f.company.id, first.connectionId, { + enabledCatalogEntryIds: first.catalog.map(entry => entry.id), askFirstCatalogEntryIds: [], access: { agentIds: [f.agentA.id] }, + }, actor); + const toolsA = await f.circlebackTools(f.sessions.a.token, galleryKey); + const toolsB = await f.circlebackTools(f.sessions.b.token, galleryKey); + const search = toolsA.find(tool => tool.upstreamToolName === "SearchMeetings")!; + await f.gateway.executeTool({ sessionToken: f.sessions.a.token, tool: search.name, parameters: { query: "roadmap" }, idempotencyKey: randomUUID() }); + const denied = await f.gateway.executeTool({ sessionToken: f.sessions.b.token, tool: search.name, parameters: { query: "roadmap" }, idempotencyKey: randomUUID() }) + .then(() => "allowed", () => "denied"); + return { + first, second, catalog, beforeInstall, denied, searchTool: search.name, + suggestedDefaults: first.suggestedDefaults, + visibleToA: toolsA.map(tool => ({ tool: tool.upstreamToolName, risk: tool.risk, connection: tool.connectionId === first.connectionId ? "first" : "other" })) + .sort((left, right) => String(left.tool).localeCompare(String(right.tool))), + visibleToB: toolsB.length, + }; + } + + it("runs the same journey with identical results for the built-in connector and the plugin copy", async () => { + const f = await setup(); + // Rule 1: before the plugin exists only the built-in connector is listed. + expect(await f.gallerySlugs()).toContain("circleback"); + expect(await f.gallerySlugs()).not.toContain(PLUGIN_SLUG); + + const [plugin] = await db.insert(plugins).values({ pluginKey: PLUGIN_KEY, packageName: "@paperclipai/test-circleback-parity", version: fixtureManifest.version, + manifestJson: fixtureManifest, status: "ready" }).returning(); + // Rule 1: enabling the plugin adds the namespaced connector type and nothing else. + const slugs = await f.gallerySlugs(); + expect(slugs).toEqual(expect.arrayContaining(["circleback", PLUGIN_SLUG])); + // The board also gets the full definition, as it bundles built-in ones. + const gallery = await request(f.app).get(`/api/companies/${f.company.id}/tools/gallery`); + expect(gallery.body.pluginApps).toEqual([expect.objectContaining({ slug: PLUGIN_SLUG, plugin: { pluginKey: PLUGIN_KEY, appSlug: "circleback" }, + methods: pluginCircleback.methods })]); + // Telemetry never names a plugin's connector. + expect(connectorKeyForConnection({ config: { sourceTemplateKey: PLUGIN_SLUG } })).toBe("custom"); + expect(connectorKeyForConnection({ config: { sourceTemplateKey: "circleback" } })).toBe("circleback"); + expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, f.company.id))).toHaveLength(0); + expect(await f.gateway.listToolsForSession(f.sessions.a.token)).toEqual(await f.gateway.listToolsForSession(f.sessions.b.token)); + + const core = await journey(f, "circleback"); + const fromPlugin = await journey(f, PLUGIN_SLUG); + + for (const result of [core, fromPlugin]) { + expect(result.beforeInstall).toEqual({ a: 0, b: 0 }); + expect(result.visibleToB).toBe(0); + expect(result.denied).toBe("denied"); + expect(result.visibleToA.every(tool => tool.connection === "first")).toBe(true); + expect(result.catalog).toEqual(expect.arrayContaining([ + { tool: "SearchMeetings", risk: "read", status: "active" }, + { tool: "ShareMeeting", risk: "write", status: "active" }, + { tool: "ShareFolder", risk: "write", status: "active" }, + { tool: "SubmitFeedback", risk: "write", status: "active" }, + { tool: "DeleteFolder", risk: "destructive", status: "active" }, + ])); + } + expect(fromPlugin.catalog).toEqual(core.catalog); + expect(fromPlugin.suggestedDefaults).toEqual(core.suggestedDefaults); + expect(fromPlugin.visibleToA).toEqual(core.visibleToA); + expect(fromPlugin.first.connection.config).toMatchObject({ sourceTemplateKey: PLUGIN_SLUG, url: endpoint, connectionMethodKey: "mcp-oauth" }); + // Each account calls the provider with its own credential. + const tokensByTool = f.provider.calls.map(call => call.token); + expect(tokensByTool).toHaveLength(2); + expect(new Set(tokensByTool).size).toBe(2); + + // Rule 2, without the setup screen: signing in a plugin account through + // the API alone never installs it for agents. + const apiOnly = await connectAccount(f, PLUGIN_SLUG, { saveAgentSelection: false }); + expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, apiOnly.connectionId))).toEqual([]); + expect((await f.gateway.listToolsForSession(f.sessions.b.token)).some(tool => tool.connectionId === apiOnly.connectionId)).toBe(false); + + const pluginConnectionIds = [fromPlugin.first.connectionId, fromPlugin.second.connectionId, apiOnly.connectionId]; + const installsBefore = await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, fromPlugin.first.connectionId)); + const grantsBefore = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, fromPlugin.first.connectionId)); + + // Rule 4: disabling the plugin hides its connector type and connections + // and removes the tools from discovery and invocation. Built-in Circleback + // is untouched. + await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.id, plugin.id)); + expect(await f.gallerySlugs()).not.toContain(PLUGIN_SLUG); + expect(await f.gallerySlugs()).toContain("circleback"); + const listedConnections = (await f.service.listConnections(f.company.id)).map(connection => connection.id); + expect(listedConnections).toEqual(expect.arrayContaining([core.first.connectionId, core.second.connectionId])); + expect(listedConnections).not.toEqual(expect.arrayContaining([pluginConnectionIds[0]])); + expect(listedConnections.some(id => pluginConnectionIds.includes(id))).toBe(false); + const listedApplications = (await f.service.listApplications(f.company.id)).map(application => application.metadata?.sourceTemplateKey); + expect(listedApplications).toContain("circleback"); + expect(listedApplications).not.toContain(PLUGIN_SLUG); + expect(await f.circlebackTools(f.sessions.a.token, PLUGIN_SLUG)).toEqual([]); + expect((await f.circlebackTools(f.sessions.a.token, "circleback")).map(tool => tool.upstreamToolName).sort()) + .toEqual(core.visibleToA.map(tool => tool.tool)); + await expect(f.gateway.executeTool({ sessionToken: f.sessions.a.token, tool: fromPlugin.searchTool, parameters: {}, idempotencyKey: randomUUID() })) + .rejects.toMatchObject({ status: 404 }); + await expect(f.service.connectGalleryApp(f.company.id, { galleryKey: PLUGIN_SLUG, connectionMethodKey: "mcp-oauth" }, actor)) + .rejects.toMatchObject({ status: 404 }); + // Token exchange is refused too. + await expect(f.service.mintConnectionTokenForAgent({ connectionId: fromPlugin.first.connectionId, companyId: f.company.id, + agentId: f.agentA.id, runId: f.sessions.a.runId, body: {} })).rejects.toMatchObject({ status: 404 }); + // Saved setup is untouched while disabled. + expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, fromPlugin.first.connectionId))).toEqual(installsBefore); + expect(await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, fromPlugin.first.connectionId))).toEqual(grantsBefore); + + // Rule 4: re-enabling restores the connector, both accounts and agent A's tools. + await db.update(plugins).set({ status: "ready" }).where(eq(plugins.id, plugin.id)); + expect(await f.gallerySlugs()).toContain(PLUGIN_SLUG); + expect((await f.service.listConnections(f.company.id)).map(connection => connection.id)).toEqual(expect.arrayContaining(pluginConnectionIds)); + const restored = await f.circlebackTools(f.sessions.a.token, PLUGIN_SLUG); + expect(restored.map(tool => tool.upstreamToolName).sort()).toEqual(fromPlugin.visibleToA.map(tool => tool.tool)); + expect(restored.some(tool => tool.name === fromPlugin.searchTool)).toBe(true); + await f.gateway.executeTool({ sessionToken: f.sessions.a.token, tool: fromPlugin.searchTool, parameters: {}, idempotencyKey: randomUUID() }); + expect(await f.circlebackTools(f.sessions.b.token, PLUGIN_SLUG)).toEqual([]); + + // Rule 4: an upgrade that drops the app hides it the same way. + await db.update(plugins).set({ manifestJson: { ...fixtureManifest, apps: [] } }).where(eq(plugins.id, plugin.id)); + expect(await f.gallerySlugs()).not.toContain(PLUGIN_SLUG); + expect(await f.circlebackTools(f.sessions.a.token, PLUGIN_SLUG)).toEqual([]); + await db.update(plugins).set({ manifestJson: fixtureManifest }).where(eq(plugins.id, plugin.id)); + + // Rule 4: uninstalling keeps the rows for audit, archived, and revokes + // their grants and connection-owned credentials. + const secretIdsBefore = (await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, fromPlugin.first.connectionId))) + .flatMap(grant => grant.credentialSecretRefs.map(ref => ref.secretId)); + expect(secretIdsBefore.length).toBeGreaterThan(0); + await db.update(plugins).set({ status: "uninstalled" }).where(eq(plugins.id, plugin.id)); + expect(await retirePluginAppConnections(db, PLUGIN_KEY)).toBe(3); + const retired = await db.select().from(toolConnections).where(and(eq(toolConnections.companyId, f.company.id))); + for (const row of retired) { + if (pluginConnectionIds.includes(row.id)) expect(row).toMatchObject({ status: "archived", enabled: false }); + else expect(row.status).not.toBe("archived"); + } + for (const id of pluginConnectionIds) { + const grants = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, id)); + expect(grants.length).toBeGreaterThan(0); + expect(grants.every(grant => grant.status === "revoked")).toBe(true); + } + for (const secretId of secretIdsBefore) { + expect(await db.select().from(companySecrets).where(eq(companySecrets.id, secretId))).toHaveLength(0); + } + expect((await f.circlebackTools(f.sessions.a.token, "circleback")).length).toBe(core.visibleToA.length); + }); + + it("archives a connection whose plugin was disabled while its setup ran", async () => { + const f = await setup(); + const pluginKey = `${PLUGIN_KEY}-race`; + const slug = pluginAppSlug(pluginKey, "circleback"); + await db.insert(plugins).values({ pluginKey, packageName: "@paperclipai/test-circleback-race", version: fixtureManifest.version, + manifestJson: { ...fixtureManifest, id: pluginKey }, status: "ready" }); + const connected = await f.service.connectGalleryApp(f.company.id, { galleryKey: slug, connectionMethodKey: "mcp-oauth" }, actor); + await f.service.putConnectionInstalls(connected.connectionId, { installs: [] }); + const start = await f.service.startOAuth(f.company.id, connected.connectionId, { redirectUri, actor }); + await f.service.completeOAuthCallback({ state: new URL(start.authorizationUrl).searchParams.get("state")!, code: "race", iss: origin, redirectUri, actor }); + // Disabled while an account signs in: the saved setup stays, hidden. + const paused = await f.service.connectGalleryApp(f.company.id, { galleryKey: slug, connectionMethodKey: "mcp-oauth", name: "Paused account" }, actor); + await f.service.putConnectionInstalls(paused.connectionId, { installs: [] }); + const pausedStart = await f.service.startOAuth(f.company.id, paused.connectionId, { redirectUri, actor }); + const beforeDisable = f.provider.fetchFixture.getMockImplementation()!; + f.provider.fetchFixture.mockImplementation(async (url: string, init: RequestInit) => { + if (url.endsWith("/oauth/token")) await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.pluginKey, pluginKey)); + return beforeDisable(url, init); + }); + await expect(f.service.completeOAuthCallback({ state: new URL(pausedStart.authorizationUrl).searchParams.get("state")!, code: "paused", iss: origin, redirectUri, actor })) + .rejects.toMatchObject({ status: 404 }); + f.provider.fetchFixture.mockImplementation(beforeDisable); + const [pausedRow] = await db.select().from(toolConnections).where(eq(toolConnections.id, paused.connectionId)); + expect(pausedRow.status).not.toBe("archived"); + await db.update(plugins).set({ status: "ready" }).where(eq(plugins.pluginKey, pluginKey)); + expect((await f.service.listConnections(f.company.id)).map(connection => connection.id)).toContain(paused.connectionId); + await f.service.archiveConnection(paused.connectionId, f.company.id, actor); + + // The plugin goes away while a second account signs in. + const second = await f.service.connectGalleryApp(f.company.id, { galleryKey: slug, connectionMethodKey: "mcp-oauth", name: "Second account" }, actor); + await f.service.putConnectionInstalls(second.connectionId, { installs: [] }); + const secondStart = await f.service.startOAuth(f.company.id, second.connectionId, { redirectUri, actor }); + const original = f.provider.fetchFixture.getMockImplementation()!; + f.provider.fetchFixture.mockImplementation(async (url: string, init: RequestInit) => { + if (url.endsWith("/oauth/token")) await db.update(plugins).set({ status: "uninstalled" }).where(eq(plugins.pluginKey, pluginKey)); + return original(url, init); + }); + await expect(f.service.completeOAuthCallback({ state: new URL(secondStart.authorizationUrl).searchParams.get("state")!, code: "race-2", iss: origin, redirectUri, actor })) + .rejects.toMatchObject({ status: 404 }); + f.provider.fetchFixture.mockImplementation(original); + const [secondRow] = await db.select().from(toolConnections).where(eq(toolConnections.id, second.connectionId)); + expect(secondRow).toMatchObject({ status: "archived", enabled: false }); + expect((await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, second.connectionId))).every(grant => grant.status === "revoked")).toBe(true); + const rows = await db.select().from(toolConnections).where(eq(toolConnections.companyId, f.company.id)); + expect(rows.filter(row => row.config.sourceTemplateKey === slug && row.status !== "archived").map(row => row.id)).toEqual([connected.connectionId]); + await db.delete(plugins).where(eq(plugins.pluginKey, pluginKey)); + }); + + // Live check against the real Circleback service. It never runs in CI: + // set PAPERCLIP_CIRCLEBACK_LIVE=1 to run it. It registers a client with + // Circleback for both connectors and compares the sign-in requests, up to + // the point where a person would sign in. + it.skipIf(process.env.PAPERCLIP_CIRCLEBACK_LIVE !== "1")("starts the same real Circleback sign-in for both connectors", async () => { + const [company] = await db.insert(companies).values({ name: "Circleback live", issuePrefix: `CL${randomUUID().slice(0, 6)}` }).returning(); + await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: actor.actorId, status: "active", membershipRole: "admin" }); + const [row] = await db.insert(plugins).values({ pluginKey: `${PLUGIN_KEY}-live-${randomUUID().slice(0, 8)}`, packageName: "@paperclipai/test-circleback-parity", + version: fixtureManifest.version, manifestJson: fixtureManifest, status: "ready" }).returning(); + const service = toolAccessService(db); + const signIn = async (galleryKey: string) => { + const connected = await service.connectGalleryApp(company.id, { galleryKey, connectionMethodKey: "mcp-oauth" }, actor); + const start = await service.startOAuth(company.id, connected.connectionId, { redirectUri, actor }); + const url = new URL(start.authorizationUrl); + return { registrationSource: start.registrationSource, origin: url.origin, path: url.pathname, + scope: url.searchParams.get("scope"), resource: url.searchParams.get("resource"), method: url.searchParams.get("code_challenge_method") }; + }; + const core = await signIn("circleback"); + expect(core.registrationSource).toBe("dcr"); + expect(await signIn(pluginAppSlug(row!.pluginKey, "circleback"))).toEqual(core); + }, 60_000); +}); diff --git a/server/src/app.ts b/server/src/app.ts index b2b121a7830..2715922012e 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -233,6 +233,7 @@ import { chatRunMilestoneWork } from "./services/chat-run-milestone-work.js"; import { heartbeatService } from "./services/heartbeat.js"; import { registerInterruptedTurnChatRetry } from "./services/heartbeat/restart-interrupted-turn.js"; import { pluginLifecycleManager } from "./services/plugin-lifecycle.js"; +import { loadPluginAppCatalog } from "./services/plugin-app-catalog.js"; import { registerPluginLifecycleDelivery } from "./services/plugin-lifecycle-delivery.js"; import { createPluginJobCoordinator } from "./services/plugin-job-coordinator.js"; import { @@ -911,6 +912,9 @@ export async function createApp( setPluginEventBus(eventBus); const jobStore = pluginJobStore(db); const lifecycle = pluginLifecycleManager(db, { workerManager }); + // Seed the plugin-provided connector lookups; readers refresh them again + // from the plugins table whenever they need a current answer. + void loadPluginAppCatalog(db).catch((error) => logger.warn({ err: error }, "Could not load plugin connector catalog")); const scheduler = createPluginJobScheduler({ isBackgroundWorkEnabled: () => !isWarmStandby() && !isIdleTaskDrainActive(), db, diff --git a/server/src/routes/tool-access.ts b/server/src/routes/tool-access.ts index 0faa1a9836d..2dfb2a8c7e9 100644 --- a/server/src/routes/tool-access.ts +++ b/server/src/routes/tool-access.ts @@ -1,6 +1,7 @@ import { isCrossSiteOAuthCallbackNavigation, oauthCallbackInterstitialHtml } from "../lib/oauth-browser-return.js"; import { aiConnectionRouterPluginKey } from "@paperclipai/shared"; import { aiConnectionRouterService } from "../services/ai-connection-router.js"; +import { loadPluginAppCatalog } from "../services/plugin-app-catalog.js"; import { composioAppSetupSchema, composioAppsRefreshSchema, composioAppsSyncSchema, composioAppAccountSchema } from "@paperclipai/shared"; import { aggregatorAppsSyncSchema, aggregatorAppsRefreshSchema, arcadeDiscoverySetupSchema } from "@paperclipai/shared/aggregator-apps"; import { Router, type Request, type Response } from "express"; @@ -890,8 +891,13 @@ function connectorEnrollmentPrincipal(req: Request): string { : null; if (details?.code !== "oauth_redirect_origin_unsupported") throw error; } + const pluginApps = (await loadPluginAppCatalog(db)).definitions; res.json({ ...(oauthCallbackUrl ? { oauthCallbackUrl } : {}), + // Full definitions of plugin-provided connectors. Like the built-in + // definitions the board bundles, they keep methods the gallery entry + // hides until (for example) Cloud connector enrollment is active. + pluginApps, capabilities: await describeConnectionCreateCapabilities(req, companyId), credentialSources: { vercelConnect: { @@ -909,6 +915,8 @@ function connectorEnrollmentPrincipal(req: Request): string { apps: [...APP_STORE_DEFINITIONS.filter((app) => (settings.enableMemoryConnectors || !isMemoryConnectorId(app.slug)) && isConnectorFeatureEnabled(app, settings)).map((app) => appWithPaperclipCloudConnectorAvailability(app, advertisedProfiles) + ), ...pluginApps.map((app) => + appWithPaperclipCloudConnectorAvailability(app, advertisedProfiles) ), ...await aiConnectionRouterService(db).catalog()], }); }); diff --git a/server/src/services/connector-telemetry.ts b/server/src/services/connector-telemetry.ts index 66305e42bd7..c1b05b134e3 100644 --- a/server/src/services/connector-telemetry.ts +++ b/server/src/services/connector-telemetry.ts @@ -1,6 +1,6 @@ import { eq } from "drizzle-orm"; import { toolConnections, toolInvocations, type Db } from "@paperclipai/db"; -import { getConnectableAppDefinition } from "@paperclipai/shared"; +import { getConnectableAppDefinition, isPluginAppSlug } from "@paperclipai/shared"; import { trackConnectionCreated, trackConnectionUpdated, @@ -50,7 +50,9 @@ export function connectorKeyForConnection( ): string { const raw = connection.config?.sourceTemplateKey; const key = typeof raw === "string" ? raw : null; - return key && getConnectableAppDefinition(key) ? key : "custom"; + // Only built-in connector keys leave the instance; a plugin's connector + // names its (possibly private) plugin, so it is reported as custom. + return key && !isPluginAppSlug(key) && getConnectableAppDefinition(key) ? key : "custom"; } /** diff --git a/server/src/services/connectors/circleback/risk.ts b/server/src/services/connectors/circleback/risk.ts deleted file mode 100644 index cf56c252a3c..00000000000 --- a/server/src/services/connectors/circleback/risk.ts +++ /dev/null @@ -1,45 +0,0 @@ -import type { ToolRiskLevel } from "@paperclipai/shared"; - -// Reviewed against Circleback's hosted MCP tool reference on 2026-11-12: -// https://circleback.ai/docs/support/platform/circleback-mcp -// The generic classifier reads ShareMeeting, ShareFolder and SubmitFeedback as -// reads because "share" and "submit" are not write verbs. Exact names make -// additions and renames default to write until they are reviewed. -const READ_TOOLS = new Set([ - "SearchMeetings", - "ReadMeetings", - "GetTranscriptsForMeetings", - "SearchTranscripts", - "SearchActionItems", - "SearchCalendarEvents", - "SearchEmails", - "FindProfiles", - "FindCompanies", - "ListTags", - "ListFolders", - "ReadFolders", - "ListTeams", - "SearchSupportArticles", - // MCP Apps views: they render records the agent already selected. Changes - // made from a card go through the write tools below. - "DisplayMeetings", - "DisplayActionItems", - "DisplayCalendarEvents", -]); - -const DESTRUCTIVE_TOOLS = new Set([ - "DeleteActionItem", - "DeleteTag", - "DeleteFolder", -]); - -export function circlebackRisk(tool: { - name: string; - annotations?: Record; -}): ToolRiskLevel { - const annotations = tool.annotations ?? {}; - if (annotations.destructiveHint === true || annotations.destructive === true - || DESTRUCTIVE_TOOLS.has(tool.name)) return "destructive"; - if (annotations.readOnlyHint === false || annotations.writeHint === true) return "write"; - return READ_TOOLS.has(tool.name) ? "read" : "write"; -} diff --git a/server/src/services/connectors/tool-policy.ts b/server/src/services/connectors/tool-policy.ts index 4dd42854704..37cf6df0ea6 100644 --- a/server/src/services/connectors/tool-policy.ts +++ b/server/src/services/connectors/tool-policy.ts @@ -1,9 +1,8 @@ import { REST_CONNECTORS } from "./rest-registry.js"; -import type { ToolRiskLevel } from "@paperclipai/shared"; +import { getConnectableAppDefinition, reviewedToolRisk, type ToolRiskLevel } from "@paperclipai/shared"; import { NATIVE_PROVIDER_CATALOGS } from "../native-provider-catalogs.js"; import { classifyRailwayToolRisk, isRailwayEndpoint } from "../railway.js"; import { braintrustRisk } from "./braintrust/risk.js"; -import { circlebackRisk } from "./circleback/risk.js"; import { enterpretRisk } from "./enterpret/risk.js"; interface ToolDescriptor { @@ -51,11 +50,25 @@ const reviewedPolicies: ReviewedToolPolicy[] = [ })), { sourceTemplateKey: "enterpret", quarantineNewEntries: true, classifyRisk: enterpretRisk }, { sourceTemplateKey: "braintrust", quarantineNewEntries: true, classifyRisk: braintrustRisk }, - // Circleback adds tools to its hosted server over time; unreviewed names are - // writes, but stay available like other MCP-direct catalog connections. - { sourceTemplateKey: "circleback", quarantineNewEntries: false, classifyRisk: circlebackRisk }, ]; +/** + * A reviewed tool list declared in the connector's own definition. This is + * how a connector without provider code (including one a plugin provides) + * gets the same reviewed risk wherever its definition is installed. + */ +function declaredPolicy(sourceTemplateKey: string | null | undefined): ReviewedToolPolicy | null { + if (!sourceTemplateKey) return null; + const app = getConnectableAppDefinition(sourceTemplateKey); + const review = app?.reviewedTools; + if (!review) return null; + return { + sourceTemplateKey, + quarantineNewEntries: review.quarantineNewEntries ?? false, + classifyRisk: tool => reviewedToolRisk(review, tool), + }; +} + const bySource = new Map(reviewedPolicies.map(policy => [policy.sourceTemplateKey, policy])); export function connectorToolPolicy(sourceTemplateKey?: string | null, connection?: ConnectionIdentity): { @@ -64,7 +77,8 @@ export function connectorToolPolicy(sourceTemplateKey?: string | null, connectio quarantineNewEntries: boolean; } { const policy = (connection && reviewedPolicies.find(candidate => candidate.matchesEndpoint?.(connection))) - || bySource.get(sourceTemplateKey ?? ""); + || bySource.get(sourceTemplateKey ?? "") + || declaredPolicy(sourceTemplateKey); return { sourceTemplateKey: policy?.sourceTemplateKey ?? sourceTemplateKey ?? null, classifyRisk: policy?.classifyRisk, diff --git a/server/src/services/plugin-app-catalog.ts b/server/src/services/plugin-app-catalog.ts new file mode 100644 index 00000000000..16d8410997b --- /dev/null +++ b/server/src/services/plugin-app-catalog.ts @@ -0,0 +1,150 @@ +/** + * Connector types provided by plugins. + * + * A plugin with the `connectors.provide` capability declares `apps` in its + * manifest using the built-in app-definition schema. This module turns the + * apps of every *ready* plugin into namespaced catalog entries and answers one + * question for the Connectors APIs and the tool gateway: is the connector a + * connection was made from still available? + * + * The plugins table is the source of truth. Several plugin lifecycle managers + * can exist in one process (and several processes can share one database), so + * no in-memory event is relied on: every reader that needs an answer reads the + * plugin rows, and the shared lookup table used by synchronous helpers such as + * `getConnectableAppDefinition` is replaced from that same read. + * + * Disabling a plugin (or removing an app in an upgrade) only hides its apps + * and connections. Nothing is deleted, so settings, credentials, installs and + * grants come back unchanged when the plugin is enabled again. Uninstalling + * retires the connections through the normal connection removal path. + */ +import { createHash } from "node:crypto"; +import { and, eq, like, or, sql } from "drizzle-orm"; +import { plugins, toolConnections, type Db } from "@paperclipai/db"; +import { + appDefinitionSchema, + connectionSourceSlug, + isPluginAppSlug, + parsePluginAppSlug, + pluginAppDefinition, + pluginAppSlug, + setPluginAppDefinitions, + type AppDefinition, +} from "@paperclipai/shared"; +import { logger } from "../middleware/logger.js"; + +export interface PluginAppCatalog { + /** Catalog entries for every app of every ready plugin, namespaced. */ + definitions: AppDefinition[]; + /** False only for a plugin connector whose plugin or app is not available. */ + isAvailable(sourceSlug: string | null | undefined): boolean; +} + +const parsedDefinitions = new Map(); + +const ALL_AVAILABLE: PluginAppCatalog = { definitions: [], isAvailable: () => true }; + +/** The apps a ready plugin row contributes. Invalid entries are skipped. */ +export function pluginRowAppDefinitions(row: { + pluginKey: string; + status: string; + manifestJson: { capabilities?: readonly string[]; apps?: readonly unknown[] } | null; +}): AppDefinition[] { + const manifest = row.manifestJson; + if (row.status !== "ready" || !manifest?.capabilities?.includes("connectors.provide")) return []; + const definitions: AppDefinition[] = []; + for (const declared of manifest.apps ?? []) { + // Manifests are validated at install and upgrade; parse again so a row + // written by an older host can never put a malformed entry in the catalog. + const parsed = appDefinitionSchema.safeParse(declared); + if (!parsed.success) { + logger.warn({ pluginKey: row.pluginKey }, "Skipping an invalid plugin connector definition"); + continue; + } + definitions.push(pluginAppDefinition(row.pluginKey, parsed.data as AppDefinition)); + } + return definitions; +} + +/** Read every ready plugin's apps and refresh the shared catalog lookups. */ +export async function loadPluginAppCatalog(db: Db): Promise { + const rows = await db + .select({ pluginKey: plugins.pluginKey, status: plugins.status, manifestJson: plugins.manifestJson }) + .from(plugins) + .where(and( + eq(plugins.status, "ready"), + sql`${plugins.manifestJson}->'capabilities' @> '["connectors.provide"]'::jsonb`, + )); + const definitions = rows.flatMap((row) => { + // Parsing is the costly part; reuse it while the manifest is unchanged. + const key = `${row.pluginKey}\u0000${createHash("sha256").update(JSON.stringify(row.manifestJson)).digest("hex")}`; + let cached = parsedDefinitions.get(key); + if (!cached) { + cached = pluginRowAppDefinitions(row); + if (parsedDefinitions.size > 500) parsedDefinitions.clear(); + parsedDefinitions.set(key, cached); + } + return cached; + }); + setPluginAppDefinitions(definitions); + const available = new Set(definitions.map((app) => app.slug)); + return { + definitions, + isAvailable: (sourceSlug) => !isPluginAppSlug(sourceSlug) || available.has(sourceSlug!), + }; +} + +/** + * The availability check for a set of saved rows. Rows that were not made + * from a plugin connector need no plugin read, so built-in connections pay + * nothing for this check. + */ +export async function pluginAppCatalogFor( + db: Db, + rows: Iterable[0]>, +): Promise { + for (const row of rows) { + if (isPluginAppSlug(connectionSourceSlug(row))) return loadPluginAppCatalog(db); + } + return ALL_AVAILABLE; +} + +export function pluginKeyForConnectionSource(sourceSlug: string | null | undefined): string | null { + return parsePluginAppSlug(sourceSlug)?.pluginKey ?? null; +} + +/** + * Retire every connection made from a plugin's apps when it is uninstalled. + * Uses the standard connection removal, so rows stay (archived) for audit + * while grants are revoked and connection-owned credentials are deleted. + * Removal is idempotent, so archived rows are retried too: a removal that + * failed part-way finishes on the next attempt. Any failure is thrown, so + * the uninstall is not reported as done while credentials remain. + */ +export async function retirePluginAppConnections(db: Db, pluginKey: string): Promise { + const prefix = `${pluginAppSlug(pluginKey, "x").slice(0, -1)}%`; + const rows = await db + .select({ id: toolConnections.id, companyId: toolConnections.companyId, config: toolConnections.config, transportConfig: toolConnections.transportConfig }) + .from(toolConnections) + .where(or( + like(sql`${toolConnections.config}->>'sourceTemplateKey'`, prefix), + like(sql`${toolConnections.transportConfig}->>'sourceTemplateKey'`, prefix), + )); + const owned = rows.filter((row) => pluginKeyForConnectionSource(connectionSourceSlug(row)) === pluginKey); + if (owned.length === 0) return 0; + const { toolAccessService } = await import("./tool-access.js"); + const access = toolAccessService(db); + const failures: unknown[] = []; + for (const row of owned) { + try { + await access.archiveConnection(row.id, row.companyId); + } catch (error) { + logger.warn({ err: error, pluginKey, connectionId: row.id }, "Could not retire a plugin connector connection"); + failures.push(error); + } + } + if (failures.length > 0) { + throw new Error(`Could not remove ${failures.length} connection(s) of this plugin's connectors. Try uninstalling again.`); + } + return owned.length; +} diff --git a/server/src/services/plugin-capability-validator.ts b/server/src/services/plugin-capability-validator.ts index fa2b8915931..20819b57925 100644 --- a/server/src/services/plugin-capability-validator.ts +++ b/server/src/services/plugin-capability-validator.ts @@ -205,6 +205,7 @@ const LAUNCHER_PLACEMENT_CAPABILITIES: Record< */ const FEATURE_CAPABILITIES: Record = { tools: "agent.tools.register", + apps: "connectors.provide", jobs: "jobs.schedule", webhooks: "webhooks.receive", database: "database.namespace.migrate", diff --git a/server/src/services/plugin-lifecycle.ts b/server/src/services/plugin-lifecycle.ts index 24fa13e772a..9b32403b6f0 100644 --- a/server/src/services/plugin-lifecycle.ts +++ b/server/src/services/plugin-lifecycle.ts @@ -301,6 +301,11 @@ export interface PluginLifecycleManagerOptions { * @see PLUGIN_SPEC.md §21.3 — `plugins.status` column * @see PLUGIN_SPEC.md §12 — Process Model */ +async function retireConnectorConnectionsFor(db: Db, pluginKey: string): Promise { + const { retirePluginAppConnections } = await import("./plugin-app-catalog.js"); + await retirePluginAppConnections(db, pluginKey); +} + export function pluginLifecycleManager( db: Db, options?: PluginLoader | PluginLifecycleManagerOptions, @@ -320,6 +325,7 @@ export function pluginLifecycleManager( } const registry = pluginRegistryService(db); + const retireConnectorConnections = (pluginKey: string) => retireConnectorConnectionsFor(db, pluginKey); const pluginLoaderInstance = loaderArg ?? pluginLoader(db); const emitter = new EventEmitter(); emitter.setMaxListeners(100); // plugins may have many listeners; 100 is a safe upper bound @@ -540,6 +546,8 @@ export function pluginLifecycleManager( // If already uninstalled and removeData, hard-delete if (plugin.status === "uninstalled") { + // Finish any connector cleanup an earlier uninstall could not complete. + await retireConnectorConnections(plugin.pluginKey); if (removeData) { await pluginLoaderInstance.cleanupInstallArtifacts(plugin); const deleted = await registry.uninstall(pluginId, true); @@ -563,8 +571,16 @@ export function pluginLifecycleManager( await deactivatePluginRuntime(pluginId, plugin.pluginKey); await pluginLoaderInstance.cleanupInstallArtifacts(plugin); - // Perform the uninstall via registry (handles soft/hard delete) - const result = await registry.uninstall(pluginId, removeData); + // Mark the plugin uninstalled first, so no new connector setup can + // start. Then retire the connections made from its connector types: + // rows stay for audit, archived, with grants revoked and owned + // credentials deleted. A setup already in flight archives its own + // connection (see tool-access). A failure is reported, and uninstalling + // again finishes the cleanup; a hard delete happens only after it. + let result = await registry.uninstall(pluginId, false); + await retireConnectorConnections(plugin.pluginKey); + if (removeData) result = await registry.uninstall(pluginId, true); + log.info( { pluginId, pluginKey: plugin.pluginKey, removeData }, diff --git a/server/src/services/tool-access.ts b/server/src/services/tool-access.ts index f11b63d9c2b..38a905d4b90 100644 --- a/server/src/services/tool-access.ts +++ b/server/src/services/tool-access.ts @@ -84,6 +84,7 @@ import { stableHash } from "./tool-catalog-hash.js"; import { NATIVE_PROVIDER_SLUGS, nativeProviderCatalogFor } from "./native-provider-catalogs.js"; import { connectorToolPolicy } from "./connectors/tool-policy.js"; +import { loadPluginAppCatalog, pluginAppCatalogFor } from "./plugin-app-catalog.js"; import { notifyChatEndpointWork } from "./chat-work-notifications.js"; @@ -110,7 +111,7 @@ import { and, asc, desc, eq, inArray, max, ne, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { agents, connectionGrantMembers, connectionGrants, companyMemberships, principalPermissionGrants, userSecretDefinitions, plugins, toolAccessAuditEvents, toolApplications, toolCatalogEntries, toolConnectionInstalls, toolConnections, toolStdioCommandTemplates, toolCallEvents, toolPolicies, toolProfileBindings, toolProfileEntries, toolProfiles } from "@paperclipai/db"; import type { AppDefinition, ConnectionGrantKind, CreateToolApplication, CreateToolConnection, ConnectToolApp, ConnectToolAppResult, CreateToolStdioCommandTemplate, FinishToolApp, FinishToolAppResult, CreateToolProfileBindingForProfile, CreateToolProfileEntryForProfile, DeploymentExposure, DeploymentMode, ImportMcpJson, McpConnectionCredentialRef, McpJsonImportPreview, ToolApplication, ToolCatalogEntry, ToolCatalogRefreshResult, ToolConnection, ToolConnectionInstall, ToolConnectionHealthCheckResult, ToolConnectionAuthKind, ToolConnectionCredentialPolicy, ToolConnectionCredentialSource, ToolConnectionTransport, ToolAppMetadataPreflightResult, ToolExampleInstallResult, ToolExampleSmokeCheck, ToolExampleSmokeResult, ToolExampleSummary, ToolProfileBinding, ToolProfileEntry, ToolPolicyDecision, ToolStdioCommandTemplate, UpdateToolApplication, UpdateToolConnection, VercelConnectCredentialReference } from "@paperclipai/shared"; -import { getAppDefinitionForUrl, getAvailableConnectionMethods, getConnectableAppDefinition, recommendedDefaultsForApp } from "@paperclipai/shared"; +import { connectionSourceSlug, isPluginAppSlug, parsePluginAppSlug, getAppDefinitionForUrl, getAvailableConnectionMethods, getConnectableAppDefinition, recommendedDefaultsForApp } from "@paperclipai/shared"; import { checkMcpRemoteHeaderName, checkMcpRemoteHeaderValue, @@ -785,6 +786,40 @@ export function toolAccessService( const runtimeSupervisor = createToolRuntimeSupervisor(db, options); const connectionGrantsService = createConnectionGrants(db, { getConnectionRow, assertSecretRefs, vercelConnect }); const removeConnection = createConnectionRemoval(db, { options, secrets, runtimeSupervisor, vercelConnect, getConnectionRow }); + /** + * Connection setup resolves connector definitions synchronously. Refresh the + * plugin-provided part of the catalog from the plugins table first, so a + * plugin enabled or disabled through another process is seen here too. + */ + /** + * A setup step that finishes after its plugin became unavailable reports the + * connector as gone. If the plugin was uninstalled, its cleanup may already + * have run, so this connection (and the credential just stored) is removed + * through the normal removal too. + */ + async function retireIfPluginAppUnavailable | null } }>( + result: Result, + actor?: ActorInfo, + ): Promise { + const source = result.connection.config?.sourceTemplateKey; + const pluginKey = parsePluginAppSlug(source)?.pluginKey; + if (!pluginKey || (await loadPluginAppCatalog(db)).isAvailable(source as string)) return result; + // Disabled: keep the saved setup (hidden) so re-enabling restores it. + // Uninstalled (or deleted): its cleanup may already have passed, so + // remove this connection the same way. + const [plugin] = await db.select({ status: plugins.status }).from(plugins).where(eq(plugins.pluginKey, pluginKey)); + if (!plugin || plugin.status === "uninstalled") { + await removeConnection(result.connectionId, result.connection.companyId, actor); + } + throw notFound("Tool app gallery entry not found"); + } + + function withPluginApps(fn: (...args: Args) => Promise) { + return async (...args: Args): Promise => { + await loadPluginAppCatalog(db); + return fn(...args); + }; + } const credentialStore = createOAuthCredentialStore(db, secrets); const { syncCredentialBindings, annotateSavedOAuthClientSecret, oauthClientForConnection, createOrRotateOAuthSecret, getOAuthGrantRow, resolveOAuthGrantSecret } = credentialStore; const ensureOAuthClient = createOAuthClientRegistration(db, { now, options, store: credentialStore, getConnectionRow, requestOAuthClientRegistration }); @@ -817,7 +852,14 @@ export function toolAccessService( const catalogDiscovery = createToolCatalogDiscovery(db, { now, audit, secrets, credentials: credentialAccess, vercel: vercelCredentials, vercelConnect, setupPolicy, requestRemoteHttpEndpoint, resolveOAuthGrantSecret, discoverOAuthEndpoints, localTools }); const connectionHealth = createConnectionHealth(db, { now, audit, getConnectionRow, discovery: catalogDiscovery, setupPolicy, resolveCredentialHeaders, vaultGrantForConnection, refreshManagedGitHubGrantAccess, ensureRuntimeSlot, stdioTemplateId }); const { updateConnectionHealth, checkConnectionHealth, sweepConnectionHealth } = connectionHealth; - const refreshCatalog = createToolCatalogPublication(db, { now, audit, getConnectionRow, discoverTools: catalogDiscovery.discoverTools, discoverSkills: catalogDiscovery.discoverSkills, assertConnectorConnectionSetupEnabled, updateConnectionHealth, vaultGrantForConnection, ensureRuntimeSlot, enableCatalogEntriesByDefault }); + const publishCatalog = createToolCatalogPublication(db, { now, audit, getConnectionRow, discoverTools: catalogDiscovery.discoverTools, discoverSkills: catalogDiscovery.discoverSkills, assertConnectorConnectionSetupEnabled, updateConnectionHealth, vaultGrantForConnection, ensureRuntimeSlot, enableCatalogEntriesByDefault }); + // Every catalog refresh (setup, scheduled discovery, or a read that + // refreshes) classifies tools from the connector definition, so make sure + // plugin-provided definitions are current first. + const refreshCatalog: typeof publishCatalog = async (...args) => { + await loadPluginAppCatalog(db); + return publishCatalog(...args); + }; const catalogReader = createToolCatalogReader(db, options, now, getConnectionRow, refreshCatalog, toCatalogEntryForConnection); const listAppsNeedingAttention = createToolAppAttention(db, now); const aggregatorAccounts = createAggregatorAccounts(db, { options, secrets, audit, credentials: credentialAccess, getConnectionRow, requestRemoteHttpEndpoint, remoteTools: catalogDiscovery.remoteTools }); @@ -3823,7 +3865,7 @@ export function toolAccessService( if (!current) throw forbidden("Your GitHub connection was revoked. Connect it again."); return { githubUserId: String(identity.id), login: identity.login, avatarUrl: identity.avatar_url ?? null, connectionId, grantId: grant.id }; }, - preflightGalleryAppMetadata, + preflightGalleryAppMetadata: withPluginApps(preflightGalleryAppMetadata), approvedStdioTemplates: async ( companyId: string, ): Promise => { @@ -3903,9 +3945,10 @@ export function toolAccessService( }, ...aggregatorAccounts, - connectGalleryApp, + connectGalleryApp: withPluginApps(async (companyId: string, input: ConnectToolApp, actor?: ActorInfo) => + retireIfPluginAppUnavailable(await connectGalleryApp(companyId, input, actor), actor)), - finishGalleryAppConnection, + finishGalleryAppConnection: withPluginApps(finishGalleryAppConnection), createMachineSignIn: clientCredentials.createMachineSignIn, testMachineSignIn: clientCredentials.testMachineSignIn, @@ -3913,11 +3956,11 @@ export function toolAccessService( completeMachineSignInRotation: clientCredentials.completeMachineSignInRotation, getMachineSignIn: clientCredentials.getMachineSignIn, - reconnectGalleryApp, + reconnectGalleryApp: withPluginApps(reconnectGalleryApp), storeConnectorOAuthSecret: createOrRotateOAuthSecret, resolveConnectorOAuthGrantSecret: resolveOAuthGrantSecret, - startOAuth, + startOAuth: withPluginApps(startOAuth), startAuthorizationForAgent: async (input: { companyId: string; @@ -3962,11 +4005,12 @@ export function toolAccessService( peekOAuthState, - completePaperclipCloudConnectorCallback, + completePaperclipCloudConnectorCallback: withPluginApps(completePaperclipCloudConnectorCallback), completeVercelConnectCallback, - completeOAuthCallback, + completeOAuthCallback: withPluginApps(async (...args: Parameters) => + retireIfPluginAppUnavailable(await completeOAuthCallback(...args), args[0].actor)), refreshOAuthGrantCredentials, finalizeOAuthAccess, @@ -4150,7 +4194,10 @@ export function toolAccessService( .from(toolApplications) .where(eq(toolApplications.companyId, companyId)) .orderBy(desc(toolApplications.updatedAt)); - return rows.map(toApplication); + // A disabled plugin's connectors leave the Connectors page; their rows + // stay so re-enabling restores them unchanged. + const pluginApps = await pluginAppCatalogFor(db, rows); + return rows.filter((row) => pluginApps.isAvailable(connectionSourceSlug(row))).map(toApplication); }, createApplication: async ( @@ -4496,11 +4543,13 @@ export function toolAccessService( companyId: string, viewerUserId?: string, ): Promise => { - const rows = await db + const allRows = await db .select() .from(toolConnections) .where(eq(toolConnections.companyId, companyId)) .orderBy(desc(toolConnections.updatedAt)); + const pluginApps = await pluginAppCatalogFor(db, allRows); + const rows = allRows.filter((row) => pluginApps.isAvailable(connectionSourceSlug(row))); const connections = rows.map(toConnection); if (connections.length === 0) return connections; const installRows = await db diff --git a/server/src/services/tool-access/oauth/catalog-completion.ts b/server/src/services/tool-access/oauth/catalog-completion.ts index b655c764915..5e090ec3462 100644 --- a/server/src/services/tool-access/oauth/catalog-completion.ts +++ b/server/src/services/tool-access/oauth/catalog-completion.ts @@ -1,6 +1,6 @@ import { connectionActorUserId } from "../actor.js"; import type { ActorInfo } from "../types.js"; -import { isRemoteMcpConnectorMethod } from "@paperclipai/shared"; +import { isPluginAppSlug, isRemoteMcpConnectorMethod } from "@paperclipai/shared"; import { and, eq } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { issueThreadInteractions, toolConnectionInstalls, toolConnections } from "@paperclipai/db"; @@ -69,7 +69,10 @@ export function createOAuthCatalogCompletion(db: Db, finishGalleryAppConnection: // Workspace setup saves the operator's install selection before OAuth too. // An empty selection means no agents, not permission to apply all-agent // defaults after the user returns from Google. - const preserveEmptyInstalls = input.connection.config.sourceTemplateKey === "google-workspace" + // A plugin connector never gets agent access from signing in: an agent or + // company install is always an explicit operator choice. + const preserveEmptyInstalls = isPluginAppSlug(input.connection.config.sourceTemplateKey) + || input.connection.config.sourceTemplateKey === "google-workspace" || isRemoteMcpConnectorMethod( input.connection.config.sourceTemplateKey, input.connection.config.connectionMethodKey, diff --git a/server/src/services/tool-access/token-broker/service.ts b/server/src/services/tool-access/token-broker/service.ts index 3b2db3b1780..eb75322472c 100644 --- a/server/src/services/tool-access/token-broker/service.ts +++ b/server/src/services/tool-access/token-broker/service.ts @@ -5,7 +5,9 @@ import { and, eq, sql } from "drizzle-orm"; import type { Db } from "@paperclipai/db"; import { connectionGrantMembers, connectionGrantDelegations, connectionGrants, companyMemberships, toolApplications, toolConnectionInstalls, toolConnections } from "@paperclipai/db"; import type { ConnectionTokenIssuanceOutcome, ConnectionTokenRequest, ConnectionTokenResponse } from "@paperclipai/shared"; -import { forbidden, HttpError, unprocessable } from "../../../errors.js"; +import { forbidden, HttpError, notFound, unprocessable } from "../../../errors.js"; +import { connectionSourceSlug } from "@paperclipai/shared"; +import { pluginAppCatalogFor } from "../../plugin-app-catalog.js"; import { secretService } from "../../secrets.js"; import { toolAccessPolicyService } from "../../tool-access-policy.js"; import type { ToolAccessAudit } from "../audit.js"; @@ -59,6 +61,11 @@ export function createConnectionTokenBroker(db: Db, { now, secrets, policySvc, a input.connectionId, input.companyId, ); + // A plugin connector's connections reach no agent while its plugin is + // not ready or no longer provides it, token exchange included. + if (!(await pluginAppCatalogFor(db, [connection])).isAvailable(connectionSourceSlug(connection))) { + throw notFound("This connector is not available. Its plugin is disabled or no longer provides it."); + } const nativeProvider = nativeProviderCatalogFor(connection); if (nativeProvider) throw forbidden(`${nativeProvider.name} credentials stay in the governed tool gateway and cannot be exported.`); if (restConnectorFor(connection)) throw forbidden("Deployment connection credentials stay in the governed tool gateway and cannot be exported."); diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 86c2c0b0f17..5cbf7d9c426 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -76,6 +76,8 @@ import { } from "./mcp-tasks.js"; import { logger } from "../middleware/logger.js"; import { getAppDefinitionForApplicationKey, isConnectorFeatureEnabled } from "@paperclipai/shared"; +import { connectionSourceSlug } from "@paperclipai/shared"; +import { pluginAppCatalogFor } from "./plugin-app-catalog.js"; import { requestConfirmationPayloadSchema } from "@paperclipai/shared"; import { instanceSettingsService } from "./instance-settings.js"; import { redactSensitiveText } from "../redaction.js"; @@ -1748,10 +1750,14 @@ export function createToolGatewayService( return connectionRow ? [{ catalogEntry, ...connectionRow }] : []; }); + // A plugin connector's tools reach agents only while its plugin is ready + // and still declares the app. Disabled plugins keep their saved setup. + const pluginApps = await pluginAppCatalogFor(db, connectionRows.map(({ connection }) => connection)); const featureSettings = connectionRows.some(({ application }) => getAppDefinitionForApplicationKey(application.applicationKey)?.experimentalFeatureKey) ? await instanceSettingsService(db).getExperimental() : undefined; const eligibleRows = rows.filter( ({ catalogEntry, connection, application }) => + pluginApps.isAvailable(connectionSourceSlug(connection)) && (!featureSettings || isConnectorFeatureEnabled(getAppDefinitionForApplicationKey(application.applicationKey), featureSettings)) && !isRetiredComposioConnection(connection) && !(nativeProviderCatalogFor(connection) && !nativeProviderCatalogFor(connection)!.isCurrentEntry(catalogEntry)) && @@ -4883,6 +4889,13 @@ export function createToolGatewayService( connection: typeof toolConnections.$inferSelect, allowInteraction = true, ): Promise { + if (!(await pluginAppCatalogFor(db, [connection])).isAvailable(connectionSourceSlug(connection))) { + throw new ToolGatewayHttpError( + 404, + "This connector is not available. Its plugin is disabled or no longer provides it.", + "connector_unavailable", + ); + } const [run] = session.runId && !session.identityContextId ? await db diff --git a/tests/runner-e2e/source-sdk-public-inputs.json b/tests/runner-e2e/source-sdk-public-inputs.json index 82cd2919267..241595beb28 100644 --- a/tests/runner-e2e/source-sdk-public-inputs.json +++ b/tests/runner-e2e/source-sdk-public-inputs.json @@ -73,7 +73,7 @@ "packages/shared/src/app-definitions.generated.ts": "e314e97d3b535c8d3942052240f794049bb9f44a", "packages/shared/src/app-definitions.ingestion-report.json": "a7b60c7c16a484a411989315e9f08d48258fa647", "packages/shared/src/app-definitions.test.ts": "54cf668cf97cf1b57e8af631beeb2828e9730558", - "packages/shared/src/app-definitions.ts": "eaadd6b7831cc23998a1a3ec6fd1d3a5032a503b", + "packages/shared/src/app-definitions.ts": "ba5a19cce9697110e60a36aaf018d3d2ef0ba4b3", "packages/shared/src/app-definitions/1password.json": "c11a4777de2c78805b2d391da5eb075a9511e0f8", "packages/shared/src/app-definitions/agentmail.json": "edd0799b1980d0f5f43b89c8f7a1173dc623f7fa", "packages/shared/src/app-definitions/airtable.json": "c9b216a2bbe693bc6167413255d41c33512d418d", @@ -91,7 +91,7 @@ "packages/shared/src/app-definitions/calendly.json": "cdedf7bed6940ec375042b6e1982b7af6e2d7284", "packages/shared/src/app-definitions/candid.json": "7d9668da949918163ef3d4b4be85bf7b559613d5", "packages/shared/src/app-definitions/chat-completions-api.json": "021e0df41be5bdc3801f33586adf91c22bb080ae", - "packages/shared/src/app-definitions/circleback.json": "2b05e87c3569738ff3ea7820a02f4483b11df0ab", + "packages/shared/src/app-definitions/circleback.json": "717d53e78a405902a5ea52bc1f734ec67e171d69", "packages/shared/src/app-definitions/clickhouse.json": "f7ede2aa309c5607b008309ba32397924c73950d", "packages/shared/src/app-definitions/clickup.json": "2367ba3afc2f22bd49572467643bd81620b3f350", "packages/shared/src/app-definitions/cloudflare.json": "693237c0a9b09b66c4fc3b265efb17520b40df31", @@ -229,7 +229,7 @@ "packages/shared/src/connector-availability.ts": "82aec0dfb2e9b8cb04e21c4bcd9aab74b087c76a", "packages/shared/src/connector-identity.test.ts": "d58357707faefa7c98bb906cdaeb4db39d31081a", "packages/shared/src/connector-identity.ts": "5ede83c9c5225dbe8af9cf3a49c74e477ef5b955", - "packages/shared/src/constants.ts": "47973de810c0dfac21625e2687af80b37e8da00c", + "packages/shared/src/constants.ts": "698b73db1661e18bd435a9dfef5f3804fcf0612a", "packages/shared/src/crash-point-registry.ts": "3cbf2d290bc111061376b43020848623e493737c", "packages/shared/src/crash-points.test.ts": "3564a1f62d22f54a3c2fb0a72b3a6cde17c957d2", "packages/shared/src/crash-points.ts": "c15259f39610e352eac5423a491548ec1bae94fe", @@ -268,7 +268,7 @@ "packages/shared/src/home-paths.ts": "fa4f1c440653b76b3dbb7a51026d557287deb45d", "packages/shared/src/humanize-connection.test.ts": "ba9e90a44c63452b0bf9f733adb90241921e8eca", "packages/shared/src/humanize-connection.ts": "fbd414476a0ef7106a7c80d8572208781b091699", - "packages/shared/src/index.ts": "6a7bc6095752c6e6f7602fdccd889cdb8bafeb57", + "packages/shared/src/index.ts": "e17ff48b5807bf070dcacec86c2edcab48b341f9", "packages/shared/src/issue-activity-identity.test.ts": "3dc294640f54c2be67943e3e0149cf4eff2c95ca", "packages/shared/src/issue-activity-identity.ts": "1b0f07ec3fe0506aaaf80a4fa9893f3baf8f0075", "packages/shared/src/issue-attribution.test.ts": "84563685e7f3c48029243cf1cc24a3a09ee3cde9", @@ -305,6 +305,8 @@ "packages/shared/src/oauth-endpoint-url.ts": "5ea73648dc5df103881e40e8ed920e38d901760a", "packages/shared/src/openrouter-attribution.test.ts": "ddc980f9d06fac708d02dcef8a8962e9887d6854", "packages/shared/src/openrouter-attribution.ts": "b77e887721cbf6bd882004f07df2405b6e58e52c", + "packages/shared/src/plugin-apps.test.ts": "5f6d2f7cd49085c8ead90647c4ee63c050a0fc46", + "packages/shared/src/plugin-apps.ts": "59e63a673878e460d4fedebca576eef091dff9b6", "packages/shared/src/portability-fidelity.test.ts": "3cb1d7740cd016d8f2000cf400b87971c571e5ed", "packages/shared/src/portability-fidelity.ts": "3465dc57777f0f74bcc018ecc9fa955d3c92f4a3", "packages/shared/src/portability-hash.ts": "4465c125a08bef6cd78ac4fdff7062989a2d8a25", @@ -375,7 +377,7 @@ "packages/shared/src/types/agent-lifecycle.ts": "dcc5105d57856cc8ca34a122cf54117c950184ea", "packages/shared/src/types/agent.adapter-auth-session.test.ts": "d651511d78cb44b29940252df6138cd202e0ab45", "packages/shared/src/types/agent.ts": "11f5dbdf5b4c16271b5d79e22b159f97be68e896", - "packages/shared/src/types/app-definition.ts": "f55fad80e9c765e16a3a59f694bdb0764940d968", + "packages/shared/src/types/app-definition.ts": "1a70bb5c6f6bc816982a336eca7a94ee97570951", "packages/shared/src/types/approval.ts": "4554d36f804cb74b825b29711ed4c622df07ff6d", "packages/shared/src/types/artifact.ts": "6d022d34a718196df5c109a6164e7a70ede287e8", "packages/shared/src/types/asset.ts": "d148d6cba0e9a8d2e3aa6cb9182df6f59f909fba", @@ -414,7 +416,7 @@ "packages/shared/src/types/issue.ts": "7183a5a11238c297e43917dc66897cbe73703835", "packages/shared/src/types/live.ts": "b90e55e4de8600c6fc17d7fa8d89079d4ae655ec", "packages/shared/src/types/native-finalization.ts": "c026a73003ae232fea4f7624d561493b383df358", - "packages/shared/src/types/plugin.ts": "78519a2bbda1c9b465fbd73699ae77e9be577bfb", + "packages/shared/src/types/plugin.ts": "af85e6aa845c2ef6956d0151ff11332947bf3949", "packages/shared/src/types/project.ts": "50b9d9c51cb38d5862e287c1a47726716603f21c", "packages/shared/src/types/quota.ts": "a0686a9afb3111a4de093f66200dc0c9152e883e", "packages/shared/src/types/resource-memberships.ts": "9eab6fad50facf3e489f8c40e5bedd92e1d1faf8", @@ -450,7 +452,7 @@ "packages/shared/src/validators/agent-commentary.ts": "8242c5b28a77131aefdc00c873ad84c6c6736e4b", "packages/shared/src/validators/agent.test.ts": "d38767b0c1fc1439871855ed55dca3c8c7b645c6", "packages/shared/src/validators/agent.ts": "13ba04317b11c4281b7a2133a34630b4ad446dfd", - "packages/shared/src/validators/app-definition.ts": "9fb660249eaf49a71adeab222cdb29a6db41ce28", + "packages/shared/src/validators/app-definition.ts": "ea99fb75ea9e04b2e65459551d2fd4ac4a43be19", "packages/shared/src/validators/approval.test.ts": "051d29b27400fdd1e311466587b276264cf072e4", "packages/shared/src/validators/approval.ts": "b8fd4da39568e3b70b767266196ea5303efeef25", "packages/shared/src/validators/artifact.test.ts": "2f0c138a6fa46d68507515d3932e9bc4cef44374", @@ -492,12 +494,13 @@ "packages/shared/src/validators/issue-tree-control.ts": "7144ef86a83e008ac0626e1d62a1d6164c46f438", "packages/shared/src/validators/issue.test.ts": "9a10bf1112d7c85f80cc1fd5db9920dda8974643", "packages/shared/src/validators/issue.ts": "9877f071ad93952070507a79aec91fbf312d9a84", + "packages/shared/src/validators/json-schema.ts": "b6cba6a3f76b49afce1c7dc1c2f086ab946c6133", "packages/shared/src/validators/native-finalization.test.ts": "40c68bdd1d0e8a77cd70c4576fae53334fe5be0d", "packages/shared/src/validators/native-finalization.ts": "d4e674de6ac7d36385e6f6c2172fa16ffc9b1830", "packages/shared/src/validators/onboarding-seed.ts": "de302a8400d4199053f379d9ed853522a3ac6d32", "packages/shared/src/validators/partial.ts": "fa60ec7481fc14175365e9e500c814b159f1ab53", "packages/shared/src/validators/plugin.test.ts": "467df457aa12a29d42f0e2c90f0debfc39da2c83", - "packages/shared/src/validators/plugin.ts": "37337317b7174103afafbbbf2ef73c5191f66a97", + "packages/shared/src/validators/plugin.ts": "3af6eadb2a4068a6d3b58d7c4d462f62265e84bd", "packages/shared/src/validators/project.ts": "6ea168f5faf3161e6004ea47274f60634c77b219", "packages/shared/src/validators/provider-trace.ts": "b38b6200a2e51513f5dca0f8b008f2fe68175e82", "packages/shared/src/validators/resource-memberships.ts": "b124ac8a8f24b4dbb03ae82bcc87541f6b4ecdfd", @@ -520,7 +523,7 @@ "packages/shared/src/validators/teams-catalog.ts": "7bddf40c091a52aaa54e79de784bea5ae496f9aa", "packages/shared/src/validators/text.ts": "74c430fe17cdcfd4b56dd08a4c57cd3d567670a8", "packages/shared/src/validators/tool-access.test.ts": "b5838320115946a936b256919a5bd3a2294c6070", - "packages/shared/src/validators/tool-access.ts": "f6ada4ebdc2d318c0bd50a82dac0692082e03468", + "packages/shared/src/validators/tool-access.ts": "4cd2b5495391c1f2f85295449ad5b04843203559", "packages/shared/src/validators/trust-policy.test.ts": "1fc4818984eb0e14f034d56ad147600224496d4e", "packages/shared/src/validators/trust-policy.ts": "f16b002db940b06bd882d51df8b5712c576e1d7b", "packages/shared/src/validators/voice-sessions.ts": "018a71f9ac544645041ac3cc9919e59c95fbe998", diff --git a/ui/src/api/tools.ts b/ui/src/api/tools.ts index bfa359b1fc4..302ca96951b 100644 --- a/ui/src/api/tools.ts +++ b/ui/src/api/tools.ts @@ -1,5 +1,6 @@ import type { AggregatorAppsResponse, ArcadeDiscoverySetupInput } from "@paperclipai/shared/aggregator-apps"; import type { ProviderToolIconsResponse } from "@paperclipai/shared"; +import { setPluginAppDefinitions } from "@paperclipai/shared"; import type { ComposioAppAccountInput, ComposioAppSetupInput, ComposioAppSetupResult, ComposioAppSnapshot, ComposioAppsResponse } from "@paperclipai/shared"; import type { ToolApplication, @@ -92,6 +93,8 @@ export type ToolPoliciesResponse = { policies: ToolPolicy[] }; export type ToolProfilesResponse = { profiles: ToolProfileWithDetails[] }; export type ToolGalleryResponse = { apps: AppDefinition[]; + /** Full definitions of plugin-provided connectors (gallery entries may hide methods). */ + pluginApps?: AppDefinition[]; /** Server-authoritative OAuth callback URI, omitted when this deployment has no supported browser origin. */ oauthCallbackUrl?: string; capabilities: ToolConnectionCreateCapabilities; @@ -299,7 +302,13 @@ export const toolsApi = { api.post("/tools/oauth/cloud-connector/enrollment", { companyId, label, returnTo }), // --- Applications --- listGallery: (companyId: string) => - api.get(`/companies/${companyId}/tools/gallery`), + api.get(`/companies/${companyId}/tools/gallery`).then((gallery) => { + // Plugin-provided connectors are known only from the host. Make them + // resolvable by the same catalog lookups the setup screens use; apps of + // a plugin that was disabled since the last response drop out here. + setPluginAppDefinitions(gallery.pluginApps ?? gallery.apps.filter((app) => app.plugin)); + return gallery; + }), preflightAppMetadata: (companyId: string, galleryKey: string, methodKey?: string | null) => { const query = methodKey ? `?methodKey=${encodeURIComponent(methodKey)}` : ""; return api.get( diff --git a/ui/src/pages/apps/AppsConnect.test.tsx b/ui/src/pages/apps/AppsConnect.test.tsx index 9dde59aaea1..746c2af2c0e 100644 --- a/ui/src/pages/apps/AppsConnect.test.tsx +++ b/ui/src/pages/apps/AppsConnect.test.tsx @@ -3,7 +3,7 @@ import { act, type ReactNode } from "react"; import { createRoot, type Root } from "react-dom/client"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { CONNECTABLE_APP_DEFINITIONS, GOOGLE_WORKSPACE_CONNECTOR_PROFILES, getAppStoreDefinition } from "@paperclipai/shared"; +import { CONNECTABLE_APP_DEFINITIONS, GOOGLE_WORKSPACE_CONNECTOR_PROFILES, getAppStoreDefinition, pluginAppSlug } from "@paperclipai/shared"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { ApiError, type RequestOptions } from "@/api/client"; import { aiConnectionsApi } from "@/api/ai-connections"; @@ -473,6 +473,14 @@ describe("AppsConnect — Connect with a link (M4 frame)", () => { expect(mockNavigate).toHaveBeenCalledWith("/apps/saved-account/permissions"); }); + it("shows an unavailable state for a plugin connector the host no longer provides", async () => { + mockSearch.value = `source=${pluginAppSlug("example.meetings", "circleback")}`; + listGalleryMock.mockResolvedValue({ apps: [] }); + await render(); + expect(container.querySelector('[role="alert"]')?.textContent).toBe("This connector is unavailable. Ask an instance admin to enable its plugin."); + expect(connectAppMock).not.toHaveBeenCalled(); + }); + it("shows an unavailable saved sign-in without creating a replacement", async () => { mockSearch.value = "aiLogin=another-users-login"; vi.spyOn(aiConnectionsApi, "loginSetup").mockRejectedValue(new Error("Sign-in attempt not found")); diff --git a/ui/src/pages/apps/AppsConnect.tsx b/ui/src/pages/apps/AppsConnect.tsx index d1001430f0a..4ca07a1ddab 100644 --- a/ui/src/pages/apps/AppsConnect.tsx +++ b/ui/src/pages/apps/AppsConnect.tsx @@ -5,7 +5,7 @@ import { AiConnectionCredentialStep } from "@/components/ai-connections/AiConnec import { AiProviderSetup } from "@/components/ai-connections/AiProviderSetup"; import { AiConnectionPoolConnector } from "@/components/ai-connections/AiConnectionPoolConnector"; import { useEffect } from "react"; -import { isRetiredComposioConnection } from "@paperclipai/shared"; +import { isPluginAppSlug, isRetiredComposioConnection } from "@paperclipai/shared"; import { findComposioCatalogApp } from "@paperclipai/shared/aggregator-app-catalog"; import { toolsApi } from "@/api/tools"; import { queryKeys } from "@/lib/queryKeys"; @@ -39,7 +39,8 @@ export function AppsConnect({ byoOnly = false, credentialSource = "paperclip_vau const aiAccounts = useQuery({ queryKey: ["ai-connections", selectedCompanyId], queryFn: () => aiConnectionsApi.list(selectedCompanyId!), enabled: Boolean(selectedCompanyId && aiReconnectRequested) }); const aiAccountsView = useQueryView(aiAccounts); const aiReconnect = aiAccounts.data?.connections.find(c => c.id === reconnectId); - const gallery = useQuery({ queryKey: queryKeys.apps.gallery(selectedCompanyId ?? "__none__"), queryFn: () => toolsApi.listGallery(selectedCompanyId!), enabled: !!selectedCompanyId && !!source?.startsWith("ai-router-") }); + const pluginApp = isPluginAppSlug(source); + const gallery = useQuery({ queryKey: queryKeys.apps.gallery(selectedCompanyId ?? "__none__"), queryFn: () => toolsApi.listGallery(selectedCompanyId!), enabled: !!selectedCompanyId && (!!source?.startsWith("ai-router-") || pluginApp) }); const galleryView = useQueryView(gallery); const router = gallery.data?.apps.find(app => app.slug === source)?.aiConnectionRouter; const toolkit = searchParams.get("targetToolkit"); @@ -96,6 +97,16 @@ export function AppsConnect({ byoOnly = false, credentialSource = "paperclip_vau if (!router) return

This connection pool plugin is unavailable. Enable it in Plugins.

; return ; } + // A plugin-provided connector is known only from the host gallery, which + // also registers it for the setup flow's catalog lookups. + if (pluginApp) { + if (gallery.isPending || galleryView.kind === "reconnecting") return

Loading connector…

; + if (galleryView.kind === "error") return ; + if (!gallery.data?.apps.some(app => app.slug === source)) return
+

This connector is unavailable. Ask an instance admin to enable its plugin.

+ +
; + } return ; diff --git a/ui/src/pages/apps/app-connect-policy.test.ts b/ui/src/pages/apps/app-connect-policy.test.ts index 7baa492a09d..d8b2d8ac048 100644 --- a/ui/src/pages/apps/app-connect-policy.test.ts +++ b/ui/src/pages/apps/app-connect-policy.test.ts @@ -1,4 +1,4 @@ -import { APP_STORE_DEFINITIONS, aiConnectionRouterAppDefinition, appSupportsCatalogSetup } from "@paperclipai/shared"; +import { APP_STORE_DEFINITIONS, aiConnectionRouterAppDefinition, appSupportsCatalogSetup, pluginAppSlug } from "@paperclipai/shared"; import { describe, expect, it } from "vitest"; import { MCP_DIRECT_OAUTH_CONNECT_SLUGS, @@ -88,6 +88,12 @@ describe("app connect policy", () => { expect(canEnterAppsConnect(new URLSearchParams("source=ai-router-1"))).toBe(false); }); + it("lets plugin-provided connectors reach host catalog validation", () => { + const slug = pluginAppSlug("example.meetings", "circleback"); + expect(canEnterAppsConnect(new URL(appSourceConnectHref(slug), "http://paperclip.test").searchParams)).toBe(true); + expect(canEnterAppsConnect(new URLSearchParams("source=plugin-zz-circleback"))).toBe(false); + }); + it("routes every capability-backed catalog definition through its source deep link", () => { const connectableApps = APP_STORE_DEFINITIONS.filter(appSupportsCatalogSetup); diff --git a/ui/src/pages/apps/app-connect-policy.ts b/ui/src/pages/apps/app-connect-policy.ts index ba96b4ab09b..425809d8e04 100644 --- a/ui/src/pages/apps/app-connect-policy.ts +++ b/ui/src/pages/apps/app-connect-policy.ts @@ -5,6 +5,7 @@ import { getAvailableConnectionMethods, getAppStoreDefinition, getConnectableAppDefinition, + isPluginAppSlug, type AppDefinition, } from "@paperclipai/shared"; @@ -74,6 +75,10 @@ export function canEnterAppsConnect( // before rendering the pool wizard; unknown/uninstalled routers show its // actionable unavailable state rather than bouncing back to the catalog. if (/^ai-router-(?:[a-f0-9]{2})+$/.test(source)) return true; + // Plugin-provided connectors are resolved the same way: AppsConnect loads + // the host gallery first and shows an unavailable state for a disabled + // plugin instead of bouncing back to the catalog. + if (isPluginAppSlug(source)) return true; const entry = getAppStoreDefinition(source); const channelEnabled = source === "github-code-review-bot" ? githubReviewBotsEnabled : chatConnectorsEnabled; if (