diff --git a/server/src/__tests__/plugin-connector-tool-definitions.test.ts b/server/src/__tests__/plugin-connector-tool-definitions.test.ts new file mode 100644 index 00000000000..d76926676a7 --- /dev/null +++ b/server/src/__tests__/plugin-connector-tool-definitions.test.ts @@ -0,0 +1,104 @@ +import { randomUUID } from "node:crypto"; +import { mkdtemp, rm } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest"; +import { eq } from "drizzle-orm"; +import { agents, companies, companyMemberships, createDb, heartbeatRuns, issues, plugins, toolCatalogEntries, toolConnections } from "@paperclipai/db"; +import { pluginAppSlug, pluginManifestV1Schema, type PaperclipPluginManifestV1 } from "@paperclipai/shared"; +import { toolAccessService } from "../services/tool-access.js"; +import { createToolGatewayService } from "../services/tool-gateway.js"; +import { setPluginConnectorWorkers } from "../services/plugin-connector-runtime.js"; +import { paperclipDefinedTool } from "../services/connectors/paperclip-defined-tools.js"; +import type { PluginWorkerManager } from "../services/plugin-worker-manager.js"; +import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; + +const actor = { actorType: "user" as const, actorId: "plugin-definitions-admin" }; +const PLUGIN_KEY = "example.reports"; +const APP = "reports"; +const SLUG = pluginAppSlug(PLUGIN_KEY, APP); + +function reportsManifest(buildReportSchema: Record = { type: "object" }, description = "Build a report.") { + return pluginManifestV1Schema.parse({ + id: PLUGIN_KEY, apiVersion: 1, version: "1.0.0", displayName: "Reports", description: "Reports connector", + author: "Tests", categories: ["connector"], capabilities: ["connectors.provide"], entrypoints: { worker: "worker.js" }, + apps: [{ + schemaVersion: 1, slug: APP, name: "Reports", description: "Build reports", categories: ["data"], + branding: { logoUrl: "/brands/apps/api-key-generic.svg" }, urlPatterns: [], + methods: [{ + key: "none", transport: "plugin", auth: "none", ownershipModes: ["customer"], whenToUse: "No sign-in.", + guidanceMd: "Nothing to set up.", riskTier: "S1", + tools: { kind: "static", list: [{ name: "build_report", description, risk: "read", parametersSchema: buildReportSchema }] }, + }], + }], + }) as PaperclipPluginManifestV1; +} + +const UPGRADED_SCHEMA = { type: "object", properties: { order: { type: "string", enum: ["newest", "oldest"] } } }; + +const support = await getEmbeddedPostgresTestSupport(); +(support.supported ? describe : describe.skip)("plugin connector tool definitions", () => { + let db: ReturnType; + let temp: Awaited>; + let keyDir: string; + beforeAll(async () => { + keyDir = await mkdtemp(join(tmpdir(), "plugin-definitions-secrets-")); + vi.stubEnv("PAPERCLIP_SECRETS_MASTER_KEY_FILE", join(keyDir, "key")); + temp = await startEmbeddedPostgresTestDatabase("paperclip-plugin-definitions-"); + db = createDb(temp.connectionString); + }, 60_000); + afterAll(async () => { await temp?.cleanup(); vi.unstubAllEnvs(); if (keyDir) await rm(keyDir, { recursive: true, force: true }); }); + afterEach(async () => { setPluginConnectorWorkers(null); await db.delete(plugins); }); + + async function connectedReports() { + const [company] = await db.insert(companies).values({ name: "Plugin definitions", issuePrefix: `PD${randomUUID().slice(0, 6)}` }).returning(); + await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", principalId: actor.actorId, status: "active", membershipRole: "admin" }); + const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Reporter", role: "engineer", adapterType: "process" }).returning(); + await db.insert(plugins).values({ pluginKey: PLUGIN_KEY, packageName: `@test/${PLUGIN_KEY}`, version: "1.0.0", manifestJson: reportsManifest(), status: "ready" }); + setPluginConnectorWorkers({ isRunning: () => true, getWorker: () => ({ status: "running" }), call: vi.fn() } as unknown as PluginWorkerManager); + const service = toolAccessService(db); + const gateway = createToolGatewayService(db, { toolActionSigningSecret: "plugin-definitions-signing" }); + const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Report", assigneeAgentId: agent.id }).returning(); + const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent.id, issueId: issue.id, scopeKind: "issue", + invocationSource: "on_demand", status: "running", responsibleUserId: actor.actorId, contextSnapshot: { issueId: issue.id } }).returning(); + const session = await gateway.createSession({ companyId: company.id, agentId: agent.id, runId: run.id, issueId: issue.id }); + const connected = await service.connectGalleryApp(company.id, { galleryKey: SLUG, connectionMethodKey: "none" }, actor); + await service.finishGalleryAppConnection(company.id, connected.connectionId, { + enabledCatalogEntryIds: connected.catalog.map(entry => entry.id), askFirstCatalogEntryIds: [], access: { agentIds: [agent.id] } }, actor); + const buildReport = async () => (await gateway.listToolsForSession(session.token)) + .find(tool => tool.providerType === "paperclip_plugin_connection" && tool.upstreamToolName === "build_report")!; + return { connectionId: connected.connectionId, buildReport, service }; + } + + async function upgradePlugin() { + await db.update(plugins).set({ version: "1.1.0", manifestJson: reportsManifest(UPGRADED_SCHEMA, "Build a report, newest first.") as never }); + } + + it("gives agents the installed plugin's current tool schema after an upgrade, without a catalog refresh", async () => { + const reports = await connectedReports(); + expect((await reports.buildReport()).parametersSchema).toEqual({ type: "object" }); + await upgradePlugin(); + const current = await reports.buildReport(); + expect(current.parametersSchema).toMatchObject({ properties: { order: { enum: ["newest", "oldest"] } } }); + expect(current.description).toContain("newest first"); + }); + + it("keeps the reviewed schema while changed tools await review, and the catalog refresh quarantines them", async () => { + const reports = await connectedReports(); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, reports.connectionId)); + await db.update(toolConnections).set({ config: { ...connection.config, quarantineNewEntries: true } }) + .where(eq(toolConnections.id, reports.connectionId)); + await upgradePlugin(); + expect((await reports.buildReport()).parametersSchema).toEqual({ type: "object" }); + await reports.service.refreshCatalog(reports.connectionId, actor); + const [entry] = await db.select().from(toolCatalogEntries).where(eq(toolCatalogEntries.connectionId, reports.connectionId)); + expect(entry.status).toBe("quarantined"); + expect(await reports.buildReport()).toBeUndefined(); + }); + + it("never treats a plugin's tools as Paperclip-trusted for catalog review", async () => { + const reports = await connectedReports(); + const [connection] = await db.select().from(toolConnections).where(eq(toolConnections.id, reports.connectionId)); + expect(paperclipDefinedTool(connection, "build_report")).toBeNull(); + }); +}); diff --git a/server/src/services/connectors/paperclip-defined-tools.ts b/server/src/services/connectors/paperclip-defined-tools.ts index 673c5d4c408..e8dca24d85d 100644 --- a/server/src/services/connectors/paperclip-defined-tools.ts +++ b/server/src/services/connectors/paperclip-defined-tools.ts @@ -1,16 +1,34 @@ -import { googleWorkspaceRestToolDefinition, type GoogleWorkspaceRestToolDefinition } from "../google-workspace-rest-dispatch.js"; +import { googleWorkspaceRestToolDefinition } from "../google-workspace-rest-dispatch.js"; +import type { toolConnections } from "@paperclipai/db"; +import { pluginConnectionMethod, pluginConnectionToolDefinition } from "../plugin-connector-runtime.js"; +import { shouldQuarantineNewEntries } from "../tool-access/catalog/descriptors.js"; -export type PaperclipDefinedTool = GoogleWorkspaceRestToolDefinition; +export interface PaperclipDefinedToolDefinition { + name: string; + title: string | null; + description: string | null; + inputSchema: Record; + outputSchema: Record | null; + annotations: Record; +} type Connection = { config: Record }; const PAPERCLIP_DEFINED_TOOL_SOURCES: ReadonlyArray<{ matches: (connection: Connection) => boolean; - definition: (toolName: string) => PaperclipDefinedTool | null; + definition: (toolName: string) => PaperclipDefinedToolDefinition | null; }> = [ { matches: (connection) => connection.config.sourceTemplateKey === "google-workspace", definition: googleWorkspaceRestToolDefinition }, ]; -export function paperclipDefinedTool(connection: Connection, toolName: string): PaperclipDefinedTool | null { +export function paperclipDefinedTool(connection: Connection, toolName: string): PaperclipDefinedToolDefinition | null { return PAPERCLIP_DEFINED_TOOL_SOURCES.find((source) => source.matches(connection))?.definition(toolName) ?? null; } + +export function currentConnectionToolDefinition(connection: typeof toolConnections.$inferSelect, toolName: string): PaperclipDefinedToolDefinition | null { + const trusted = paperclipDefinedTool(connection, toolName); + if (trusted) return trusted; + if (shouldQuarantineNewEntries(connection)) return null; + if (pluginConnectionMethod(connection)?.method.tools?.kind !== "static") return null; + return pluginConnectionToolDefinition(connection, toolName); +} diff --git a/server/src/services/plugin-connector-runtime.ts b/server/src/services/plugin-connector-runtime.ts index 563f3c34a69..dc3f86c0826 100644 --- a/server/src/services/plugin-connector-runtime.ts +++ b/server/src/services/plugin-connector-runtime.ts @@ -23,6 +23,7 @@ import type { ToolResult, ToolRunContext, } from "@paperclipai/plugin-sdk"; +import type { PaperclipDefinedToolDefinition } from "./connectors/paperclip-defined-tools.js"; import type { PluginWorkerManager } from "./plugin-worker-manager.js"; import { PluginWorkerUnavailableError } from "./plugin-worker-unavailable-error.js"; @@ -131,12 +132,13 @@ export async function assertPluginConnectionWorker( await runningWorker(db, identity.pluginKey); } -function toolDescriptor(tool: ConnectorToolDescriptor | PluginConnectorToolDef) { +function toolDescriptor(tool: ConnectorToolDescriptor | PluginConnectorToolDef): PaperclipDefinedToolDefinition { return { name: tool.name, - ...(tool.displayName ? { title: tool.displayName } : {}), + title: tool.displayName ?? null, description: tool.description ?? tool.displayName ?? tool.name, inputSchema: tool.parametersSchema, + outputSchema: null, // The declared risk travels with the catalog entry; the connector tool // policy reads it (see `connectors/tool-policy.ts`). annotations: { @@ -147,6 +149,16 @@ function toolDescriptor(tool: ConnectorToolDescriptor | PluginConnectorToolDef) }; } +export function pluginConnectionToolDefinition( + connection: { config: Record }, + toolName: string, +): PaperclipDefinedToolDefinition | null { + const tools = pluginConnectionMethod(connection)?.method.tools; + if (tools?.kind !== "static") return null; + const tool = tools.list.find((candidate) => candidate.name === toolName); + return tool ? toolDescriptor(tool) : null; +} + /** The tools of one plugin connection, for its catalog. */ export async function listPluginConnectionTools( db: Db, diff --git a/server/src/services/tool-gateway.ts b/server/src/services/tool-gateway.ts index 4781ea2f768..1d5d0bd89f2 100644 --- a/server/src/services/tool-gateway.ts +++ b/server/src/services/tool-gateway.ts @@ -34,7 +34,7 @@ import { notifyDeliveryWork, DELIVERY_QUEUES } from "./delivery-work-notificatio import { measureToolDiscovery, measureRunPhase, recordConnectionCatalogCounts } from "./execution-preparation-timing.js"; import { nativeProviderCatalogFor } from "./native-provider-catalogs.js"; import { callGoogleWorkspaceRest, googleWorkspaceCatalogToolTitle, googleWorkspaceRestAuditEndpoint } from "./google-workspace-rest-dispatch.js"; -import { paperclipDefinedTool } from "./connectors/paperclip-defined-tools.js"; +import { currentConnectionToolDefinition } from "./connectors/paperclip-defined-tools.js"; import { composeConnectionInstructions } from "./connection-instructions.js"; import { googleWorkspaceToolTarget, googleWorkspaceGrantedScopes, isGoogleWorkspaceToolGranted } from "@paperclipai/shared"; import { isInsufficientConnectionScope, INSUFFICIENT_CONNECTION_SCOPE_MESSAGE } from "./connection-permission-errors.js"; @@ -2075,7 +2075,7 @@ export function createToolGatewayService( ...(baseNameCounts.get(baseName)! > 1 ? [catalogEntry.id] : []), ]); const applicationKey = application.applicationKey ?? null; - const currentDefinition = paperclipDefinedTool(connection, catalogEntry.toolName); + const currentDefinition = currentConnectionToolDefinition(connection, catalogEntry.toolName); const inputSchema = projectedConnectionToolInputSchema( connection, currentDefinition?.inputSchema ?? catalogEntry.inputSchema ?? {},