mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-23 17:33:51 +02:00
Add experimental Paperclip Notebook MCP connection (#16984)
## Thinking Path > - Paperclip connects agents to external tools through saved accounts and per-action permissions. > - Notebook exposes artifact management through an ordinary remote MCP server with OAuth. > - A private pilot needs a hidden, default-off catalog and execution gate. > - Local file publishing belongs to Notebook, which can accept bounded file bytes through ordinary MCP tools. > - Paperclip therefore needs the connector registration and generic availability checks, with no file-transfer architecture. ## Linked Issues or Issue Description **Subsystem affected** Apps catalog, experimental feature metadata, connection setup, and connector availability. **Problem or motivation** Users need to connect Notebook as their Cloud account, assign its tools to agents, and retain Paperclip's normal Allowed / Ask first / Off rules. The private pilot must remain hidden until an operator enables it. Notebook should own its upload protocol and local publishing script. **Proposed solution** Register a personal remote MCP OAuth connection at Notebook's canonical endpoint. Reuse existing OAuth discovery, credential storage, refresh, reconnect, and removal. Enforce availability through generic catalog feature metadata and saved application identity. Keep Notebook's standalone uploader in its own service repository; it calls the ordinary gateway and receives no saved OAuth credential. **Alternatives considered** A gallery-only filter permits retained tools and deep links while disabled. A shared workspace publisher and private upload-ticket transport add runtime behavior that a normal MCP connector does not require. Notebook can receive file bytes directly through its own tools instead. **Roadmap alignment** This extends Connected Apps and supports Artifacts and Work Products. ROADMAP.md and related PRs were checked. This PR is standalone on master. The separate OAuth lifecycle and file-transfer proposals (#17085 and #17086) are closed and are not dependencies. ## What Changed - Register Notebook's personal MCP OAuth method, canonical endpoint, scopes, catalog metadata, and branding. - Declare managed `enablePaperclipNotebook` with false defaults and no user-facing settings toggle or staging opt-in. - Use generic availability metadata for gallery/setup, retained connection identity, OAuth completion, health, tool/context discovery, and dispatch. Resources/prompts recheck before credentials, including retained handles. Removal remains available while disabled. - Resolve catalog application identity from the saved application key, so editable connection labels cannot bypass the hidden gate. - Select a method's sole supported credential kind when no kind is supplied. - Keep UI changes to metadata-driven availability and existing setup/reconnect controls. - Document Notebook's service-owned upload script, inline publication, ordinary action policies, and credential behavior. - Add ordinary MCP OAuth, assignment, action-policy, disabled-state, settings, and catalog tests. No workspace contribution registry, private transfer endpoint, native publisher, Runner file-reader change, or Paperclip CLI upload command is included. The entire native-runtime and CLI trees match master. Upload code lives in `paperclip-cloud/notebook/`. ## Verification Source head: `65ef741e4f476c67425b57d2fb2d6d4c00e99b06`, directly on master `53732c811bb69655eb43d3d12f2063ae4ca5ad67`. The diff is 42 files. Shared execution changes only enforce generic catalog availability; tool access also resolves saved application identity and the sole supported credential kind. Neither module contains Notebook upload logic. - Catalog/shared/settings/UI suites: 592 tests passed across 12 files. Shared/server/UI typechecks passed using installed compilers. - Fresh real PostgreSQL generic MCP suite: 84/84 passed at final source; server typecheck and module boundaries pass. Coverage includes personal OAuth, ordinary refresh/reconnect, assignments, Allowed / Ask first / Off, hidden feature enforcement, and local credential removal. Four new resources/prompts cases failed against the prior code and pass after filtering saved application identity and rechecking before credentials. They prove missing/relabelled setup markers and stale eligibility cannot dispatch or read secrets while disabled; an ordinary provider remains available with the flag off. - The full tool-access service suite passed 463/464 cases. One unchanged Google Workspace `slides.write` case timed out at 15 seconds; it passed on one isolated retry without source or timeout changes. Its exact test block matches master. The cause is not established; final-head CI must qualify the complete suite. - Maps, module boundaries, token gates, and whitespace checks passed. Byte comparisons confirm the former transfer/runtime/CLI surfaces match master. - Fresh exact-head Greptile is 5/5 with zero unresolved findings after an exhaustive feedback audit. Current-head CI workflow [39625691137](https://github.com/paperclipai/paperclip/actions/runs/39625691137) succeeded, including both required checks (`ci / verify`, `ci / e2e`), Build, and browser E2E. Supplementary security/advisory scan status is recorded in the PR Checks panel and qualification receipt; prior-head scans are not counted. The superseded `4bd7af9b2e` completed CI successfully, but Greptile found the valid resources/prompts availability gap described above. It was fixed, replied to, and resolved; earlier-head results do not qualify this revision. Preserved environment failures: the first socket-restricted UI/route run had 93 listener setup failures, and the same 93 cases passed with local-socket access. The package-manager launcher could not fetch its signature metadata; installed compilers passed without dependency or configuration changes. The full service timeout and isolated retry remain recorded separately. The superseded `585e870e73` CI also failed an unchanged agent-chat project-plan revision assertion after task creation; the complete spec and relevant runtime sources match master, and a same-master prior run passed. Its cause is not established. Logs are preserved; no test or timeout was weakened and no old-head rerun was requested. The subsequent heads run full CI independently; no prior-head pass substitutes for current qualification. The Notebook uploader requires a separate service release. This public PR adds no uploader runtime to Paperclip and claims no newly deployed browser/agent acceptance. The Notebook-owned upload path is qualified separately. Code-owner review remains required before merge. ## Risks - The feature flag gates the curated connector; it does not create a Notebook service-side team allowlist or block arbitrary standard MCP URLs. - Publishing, sharing, and deletion retain the existing assignment and action-policy boundaries. - The hidden feature must be checked for retained tools and saved identity, including when connection labels change. - Disconnect removes local credentials. It does not revoke the remote Notebook authorization; the owner can revoke it in Notebook. - Ordinary refresh uses the existing client. A lost response after refresh-token rotation can require reconnect. - The standalone Notebook script and its bounded upload tools must ship together in the Notebook service before that documented convenience path is available. - No database schema, workflow, lockfile, shared transfer, or Runner change is included. No merge, deployment, or rollout is performed by this update. ## Model Used OpenAI GPT-6 in Codex, with reasoning, repository inspection, code execution, and tool use. The runtime did not expose a more specific model ID or context-window size. ## 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 - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
00331e0254
commit
3ce8d976a9
42 files changed
+1095
-48
No files matched your search
@@ -7,6 +7,9 @@ import pino from "pino";
|
||||
import request from "supertest";
|
||||
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
EMBEDDED_POSTGRES_TEST_TIMEOUT_MS,
|
||||
applyPendingMigrations,
|
||||
closeRegisteredClients,
|
||||
activityLog,
|
||||
agents,
|
||||
authUsers,
|
||||
@@ -17,6 +20,7 @@ import {
|
||||
companySecrets,
|
||||
companySecretVersions,
|
||||
createDb,
|
||||
heartbeatRuns,
|
||||
issueThreadInteractions,
|
||||
issues,
|
||||
principalPermissionGrants,
|
||||
@@ -24,6 +28,9 @@ import {
|
||||
toolAccessAuditEvents,
|
||||
toolCallEvents,
|
||||
toolInvocations,
|
||||
toolGatewaySessions,
|
||||
toolMcpGateways,
|
||||
toolMcpGatewayTokens,
|
||||
toolActionRequests,
|
||||
toolApplications,
|
||||
toolCatalogEntries,
|
||||
@@ -35,13 +42,16 @@ import {
|
||||
toolProfiles,
|
||||
toolRuntimeSlots,
|
||||
} from "@paperclipai/db";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||
import { APP_DEFINITIONS, MCP_CONFIG_HELP_PROMPT } from "@paperclipai/shared";
|
||||
import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { toolAccessService } from "../services/tool-access.js";
|
||||
import { instanceSettingsService } from "../services/instance-settings.js";
|
||||
import * as instanceSettingsModule from "../services/instance-settings.js";
|
||||
import { connectionIntentService } from "../services/connection-intents.js";
|
||||
import { ComposioApiError, type ComposioClient } from "../services/composio.js";
|
||||
import { createComposioSessionManager } from "../services/composio-session-manager.js";
|
||||
import { createToolGatewayService } from "../services/tool-gateway.js";
|
||||
@@ -52,7 +62,8 @@ import { createHttpLogger } from "../middleware/logger.js";
|
||||
import { HTTP_LOG_REDACT_PATHS } from "../middleware/http-log-redaction.js";
|
||||
import { startOAuthRefreshFixture } from "../../../scripts/mcp-fixtures/servers/oauth-refresh-fixture.mjs";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const externalTestDatabaseUrl = process.env.PAPERCLIP_TEST_DATABASE_URL?.trim();
|
||||
const embeddedPostgresSupport = externalTestDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
|
||||
/**
|
||||
@@ -81,6 +92,11 @@ const FIXTURE_TOOLS = [
|
||||
];
|
||||
|
||||
type FixtureOptions = {
|
||||
notebookAccount?: { id: string; email: string; emailVerified: boolean };
|
||||
contextResults?: Record<string, unknown>;
|
||||
scopes?: string[];
|
||||
rotateRefreshTokens?: boolean;
|
||||
dropFirstRefreshResponse?: boolean;
|
||||
/** How the MCP endpoint authenticates. */
|
||||
auth?: "public" | "oauth" | "header";
|
||||
/** For `auth: "header"`, the header the endpoint requires and its value. */
|
||||
@@ -169,18 +185,23 @@ function installMcpOAuthFixture(options: FixtureOptions = {}) {
|
||||
const requests: FixtureRequest[] = [];
|
||||
const issuedCodes = new Map<string, { codeChallenge: string; resource: string | null }>();
|
||||
let accessToken: string | null = null;
|
||||
let refreshToken = "fixture-refresh";
|
||||
let refreshResponseDropped = false;
|
||||
const tokenResponses: { access_token: string; refresh_token: string }[] = [];
|
||||
const tools = options.tools ?? FIXTURE_TOOLS;
|
||||
const scopes = options.scopes ?? (options.notebookAccount ? ["notebook:read", "notebook:write", "notebook:share", "notebook:delete"] : null);
|
||||
const resourceMetadataUrl = `${MCP_ORIGIN}/.well-known/oauth-protected-resource/mcp`;
|
||||
|
||||
const authorizationServerMetadata = () => ({
|
||||
issuer: ISSUER,
|
||||
authorization_endpoint: options.authorizationEndpoint ?? `${ISSUER}/authorize`,
|
||||
token_endpoint: options.tokenEndpoint ?? `${ISSUER}/token`,
|
||||
...(options.notebookAccount ? { revocation_endpoint: `${MCP_ORIGIN}/oauth/revoke` } : {}),
|
||||
...(options.dcr === false ? {} : { registration_endpoint: `${ISSUER}/register` }),
|
||||
...(options.cimd ? { client_id_metadata_document_supported: true } : {}),
|
||||
code_challenge_methods_supported: ["S256"],
|
||||
token_endpoint_auth_methods_supported: options.tokenEndpointAuthMethods ?? ["none"],
|
||||
scopes_supported: ["mcp:read", "mcp:write"],
|
||||
scopes_supported: scopes ?? ["mcp:read", "mcp:write"],
|
||||
});
|
||||
|
||||
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (url, init) => {
|
||||
@@ -204,6 +225,16 @@ function installMcpOAuthFixture(options: FixtureOptions = {}) {
|
||||
if (supplied !== options.requiredHeader.value) return unauthorizedMcpResponse(resourceMetadataUrl);
|
||||
}
|
||||
const rpc = parsedBody as Record<string, unknown>;
|
||||
if (options.notebookAccount && rpc.method === "initialize") {
|
||||
return jsonResponse({ jsonrpc: "2.0", id: rpc.id, result: { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "Notebook fixture", version: "1" } } });
|
||||
}
|
||||
if (options.notebookAccount && rpc.method === "notifications/initialized") return jsonResponse({}, 202);
|
||||
if (options.notebookAccount && rpc.method === "tools/call" && (rpc.params as Record<string, unknown>)?.name === "notebook_get_account") {
|
||||
return jsonResponse({ jsonrpc: "2.0", id: rpc.id, result: { structuredContent: options.notebookAccount, content: [] } });
|
||||
}
|
||||
if (typeof rpc.method === "string" && options.contextResults && Object.hasOwn(options.contextResults, rpc.method)) {
|
||||
return jsonResponse({ jsonrpc: "2.0", id: rpc.id, result: options.contextResults[rpc.method] });
|
||||
}
|
||||
if (rpc.method === "tools/call") {
|
||||
return jsonResponse({ jsonrpc: "2.0", id: rpc.id, result: {
|
||||
content: [{ type: "text", text: "Fixture meeting data" }],
|
||||
@@ -254,14 +285,24 @@ function installMcpOAuthFixture(options: FixtureOptions = {}) {
|
||||
const issued = issuedCodes.get(body.get("code") ?? "");
|
||||
if (!issued) return jsonResponse({ error: "invalid_grant" }, 400);
|
||||
}
|
||||
if (grantType === "refresh_token" && options.rotateRefreshTokens && body.get("refresh_token") !== refreshToken) {
|
||||
return jsonResponse({ error: "invalid_grant" }, 400);
|
||||
}
|
||||
accessToken = `fixture-access-${randomUUID()}`;
|
||||
return jsonResponse({
|
||||
if (options.rotateRefreshTokens) refreshToken = `fixture-refresh-${randomUUID()}`;
|
||||
const response = {
|
||||
access_token: accessToken,
|
||||
refresh_token: "fixture-refresh",
|
||||
refresh_token: refreshToken,
|
||||
expires_in: 3600,
|
||||
token_type: "Bearer",
|
||||
scope: "mcp:read",
|
||||
});
|
||||
scope: scopes?.join(" ") ?? "mcp:read",
|
||||
};
|
||||
tokenResponses.push(response);
|
||||
if (grantType === "refresh_token" && options.dropFirstRefreshResponse && !refreshResponseDropped) {
|
||||
refreshResponseDropped = true;
|
||||
throw new TypeError("Fixture lost the committed rotating refresh response");
|
||||
}
|
||||
return jsonResponse(response);
|
||||
}
|
||||
|
||||
// 404 rather than throw: discovery legitimately probes several well-known
|
||||
@@ -272,6 +313,7 @@ function installMcpOAuthFixture(options: FixtureOptions = {}) {
|
||||
return {
|
||||
fetchMock,
|
||||
requests,
|
||||
tokenResponses,
|
||||
/** Pretend the operator approved the consent screen and got a code back. */
|
||||
issueAuthorizationCode(authorizationUrl: string) {
|
||||
const parsed = new URL(authorizationUrl);
|
||||
@@ -339,15 +381,23 @@ function createRouteApp(
|
||||
describeEmbeddedPostgres("generic remote MCP connections", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
const restoreCatalogEndpoints: (() => void)[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
if (externalTestDatabaseUrl) {
|
||||
db = createDb(externalTestDatabaseUrl);
|
||||
await applyPendingMigrations(externalTestDatabaseUrl);
|
||||
return;
|
||||
}
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-generic-mcp-");
|
||||
db = createDb(tempDb.connectionString);
|
||||
}, 20_000);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
|
||||
afterEach(async () => {
|
||||
for (const restore of restoreCatalogEndpoints.splice(0)) restore();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
await instanceSettingsService(db).updateExperimental({ enablePaperclipNotebook: false });
|
||||
await db.delete(toolCallEvents);
|
||||
await db.delete(toolInvocations);
|
||||
await db.delete(toolActionRequests);
|
||||
@@ -358,6 +408,9 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
|
||||
await db.delete(companySecrets);
|
||||
await db.delete(activityLog);
|
||||
await db.delete(toolAccessAuditEvents);
|
||||
await db.delete(toolGatewaySessions);
|
||||
await db.delete(toolMcpGatewayTokens);
|
||||
await db.delete(toolMcpGateways);
|
||||
await db.delete(toolRuntimeSlots);
|
||||
await db.delete(toolConnectionInstalls);
|
||||
await db.delete(toolProfileBindings);
|
||||
@@ -367,6 +420,7 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
|
||||
await db.delete(toolConnections);
|
||||
await db.delete(toolApplications);
|
||||
await db.delete(issueThreadInteractions);
|
||||
await db.delete(heartbeatRuns);
|
||||
await db.delete(issues);
|
||||
await db.delete(principalPermissionGrants);
|
||||
await db.delete(companyMemberships);
|
||||
@@ -376,6 +430,7 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (externalTestDatabaseUrl) await closeRegisteredClients(externalTestDatabaseUrl);
|
||||
await tempDb?.cleanup();
|
||||
});
|
||||
|
||||
@@ -397,6 +452,292 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
|
||||
return false;
|
||||
}
|
||||
|
||||
function useNotebookFixtureEndpoint() {
|
||||
const method = APP_DEFINITIONS.find(app => app.slug === "paperclip-notebook")!.methods.find(method => method.key === "mcp-oauth")!;
|
||||
const originalUrl = method.defaults!.serverUrl;
|
||||
method.defaults!.serverUrl = MCP_URL;
|
||||
restoreCatalogEndpoints.push(() => { method.defaults!.serverUrl = originalUrl; });
|
||||
}
|
||||
|
||||
async function notebookContextFixture() {
|
||||
const settings = instanceSettingsService(db);
|
||||
await settings.updateExperimental({ enablePaperclipNotebook: true });
|
||||
useNotebookFixtureEndpoint();
|
||||
const fixture = installMcpOAuthFixture({ auth: "oauth", notebookAccount: { id: "cloud-owner", email: "owner@example.test", emailVerified: true },
|
||||
tools: [{ name: "notebook_get_account", annotations: { readOnlyHint: true } }],
|
||||
contextResults: {
|
||||
"resources/list": { resources: [{ uri: "notes://one", name: "Note one" }] },
|
||||
"resources/read": { contents: [{ uri: "notes://one", text: "resource body" }] },
|
||||
"prompts/list": { prompts: [{ name: "summarize", title: "Summarize note" }] },
|
||||
"prompts/get": { messages: [{ role: "user", content: { type: "text", text: "Summarize it" } }] },
|
||||
} });
|
||||
const company = await createCompany(db), service = toolAccessService(db, { paperclipCloudConnector: null });
|
||||
const actor = { actorType: "user" as const, actorId: "board-user" };
|
||||
const connected = await service.connectGalleryApp(company.id, { galleryKey: "paperclip-notebook" }, actor);
|
||||
const start = await service.startOAuth(company.id, connected.connectionId, { redirectUri: REDIRECT_URI, actor });
|
||||
const completed = await service.completeOAuthCallback({ state: new URL(start.authorizationUrl).searchParams.get("state")!,
|
||||
code: fixture.issueAuthorizationCode(start.authorizationUrl), iss: ISSUER, redirectUri: REDIRECT_URI, actor });
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Context reader", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning();
|
||||
const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Read Notebook context", status: "in_progress", assigneeAgentId: agent!.id }).returning();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent!.id, invocationSource: "assignment", status: "running", responsibleUserId: "board-user", contextSnapshot: { issueId: issue!.id } }).returning();
|
||||
await service.finishGalleryAppConnection(company.id, connected.connectionId, { enabledCatalogEntryIds: completed.catalog.map(entry => entry.id), askFirstCatalogEntryIds: [], access: { agentIds: [agent!.id] } }, actor);
|
||||
const [profile] = await db.select().from(toolProfiles).where(eq(toolProfiles.profileKey, `app:${connected.connectionId}`));
|
||||
await db.insert(toolProfileEntries).values({ companyId: company.id, profileId: profile!.id, selectorType: "connection", effect: "include", connectionId: connected.connectionId });
|
||||
const gateway = createToolGatewayService(db);
|
||||
const named = await gateway.createNamedGateway({ companyId: company.id, body: { name: "Notebook context", profileId: profile!.id, agentId: agent!.id, issueId: issue!.id } });
|
||||
const token = await gateway.createNamedGatewayToken({ companyId: company.id, gatewayId: named.id, body: { name: "Context run", subjectType: "heartbeat_run", subjectId: run!.id } });
|
||||
const context = (method: "resources/list" | "resources/read" | "prompts/list" | "prompts/get", params?: Record<string, unknown>) =>
|
||||
gateway.executeContextForNamedGateway({ gatewayPublicId: named.gatewayPublicId, bearerToken: token.token, method, params });
|
||||
const resources = await context("resources/list"), prompts = await context("prompts/list");
|
||||
const uri = (resources.resources as { uri: string }[])[0]!.uri, name = (prompts.prompts as { name: string }[])[0]!.name;
|
||||
expect(await context("resources/read", { uri })).toMatchObject({ contents: [{ uri, text: "resource body" }] });
|
||||
expect(await context("prompts/get", { name })).toMatchObject({ messages: [{ role: "user" }] });
|
||||
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId));
|
||||
await db.update(connectionGrants).set({ providerTenant: { ...grant!.providerTenant, oauth: {
|
||||
...grant!.providerTenant?.oauth, accessTokenExpiresAt: new Date(0).toISOString(),
|
||||
} } }).where(eq(connectionGrants.id, grant!.id));
|
||||
return { settings, fixture, service, connected, context, uri, name };
|
||||
}
|
||||
|
||||
it.each(["missing", "relabelled"])("omits disabled Notebook resources and prompts and denies retained handles with %s markers", async marker => {
|
||||
const f = await notebookContextFixture(), saved = await f.service.getConnection(f.connected.connectionId);
|
||||
const config = { ...saved.config };
|
||||
if (marker === "missing") delete config.sourceTemplateKey;
|
||||
else config.sourceTemplateKey = "fireflies";
|
||||
await f.service.updateConnection(f.connected.connectionId, { config });
|
||||
await f.settings.updateExperimental({ enablePaperclipNotebook: false });
|
||||
const calls = f.fixture.requests.length, secretAccess = await db.select().from(secretAccessEvents);
|
||||
await expect(f.context("resources/list")).resolves.toEqual({ resources: [] });
|
||||
await expect(f.context("prompts/list")).resolves.toEqual({ prompts: [] });
|
||||
await expect(f.context("resources/read", { uri: f.uri })).rejects.toMatchObject({ reasonCode: "mcp_resource_not_found" });
|
||||
await expect(f.context("prompts/get", { name: f.name })).rejects.toMatchObject({ reasonCode: "mcp_prompt_not_found" });
|
||||
expect(f.fixture.requests).toHaveLength(calls);
|
||||
expect(await db.select().from(secretAccessEvents)).toEqual(secretAccess);
|
||||
await db.update(toolApplications).set({ applicationKey: "fireflies" }).where(eq(toolApplications.id, f.connected.application.id));
|
||||
await expect(f.context("resources/list")).resolves.toMatchObject({ resources: [{ uri: f.uri }] });
|
||||
await expect(f.context("prompts/list")).resolves.toMatchObject({ prompts: [{ name: f.name }] });
|
||||
await expect(f.context("resources/read", { uri: f.uri })).resolves.toMatchObject({ contents: [{ uri: f.uri }] });
|
||||
await expect(f.context("prompts/get", { name: f.name })).resolves.toMatchObject({ messages: [{ role: "user" }] });
|
||||
});
|
||||
|
||||
it.each(["resources/read", "prompts/get"] as const)("rechecks saved availability before credentials when %s eligibility becomes stale", async method => {
|
||||
const f = await notebookContextFixture(), actualService = instanceSettingsModule.instanceSettingsService;
|
||||
let settingsReads = 0;
|
||||
vi.spyOn(instanceSettingsModule, "instanceSettingsService").mockImplementation((...args) => {
|
||||
const service = actualService(...args);
|
||||
return { ...service, async getExperimental() {
|
||||
const settings = await service.getExperimental();
|
||||
if (++settingsReads === 1) await f.settings.updateExperimental({ enablePaperclipNotebook: false });
|
||||
return settings;
|
||||
} };
|
||||
});
|
||||
const calls = f.fixture.requests.length, secretAccess = await db.select().from(secretAccessEvents);
|
||||
await expect(f.context(method, method === "resources/read" ? { uri: f.uri } : { name: f.name })).rejects.toMatchObject({ reasonCode: "connector_unavailable" });
|
||||
expect(settingsReads).toBe(2);
|
||||
expect(f.fixture.requests).toHaveLength(calls);
|
||||
expect(await db.select().from(secretAccessEvents)).toEqual(secretAccess);
|
||||
});
|
||||
|
||||
it.each(["missing", "relabelled"])("keeps Notebook setup internal after %s markers, denying pending OAuth and finalization while allowing removal", async marker => {
|
||||
const company = await createCompany(db), settings = instanceSettingsService(db);
|
||||
await settings.updateExperimental({ enablePaperclipNotebook: false });
|
||||
const service = toolAccessService(db, { paperclipCloudConnector: null });
|
||||
const actor = { actorType: "user" as const, actorId: "board-user" };
|
||||
const app = createRouteApp(db);
|
||||
const gallery = await request(app).get(`/api/companies/${company.id}/tools/gallery`).expect(200);
|
||||
expect(gallery.body.apps.some((item: { slug: string }) => item.slug === "paperclip-notebook")).toBe(false);
|
||||
await expect(service.connectGalleryApp(company.id, { galleryKey: "paperclip-notebook", grantKind: "user" }, actor))
|
||||
.rejects.toMatchObject({ status: 403, details: { code: "connector_disabled" } });
|
||||
await request(app).get(`/api/companies/${company.id}/tools/apps/paperclip-notebook/preflight`).expect(403);
|
||||
await expect(service.createConnection(company.id, { name: "Notebook bypass", transport: "mcp_remote", config: {
|
||||
sourceTemplateKey: "paperclip-notebook", url: MCP_URL,
|
||||
} }, actor)).rejects.toMatchObject({ status: 403, details: { code: "connector_disabled" } });
|
||||
expect(await db.select().from(toolConnections).where(eq(toolConnections.companyId, company.id))).toEqual([]);
|
||||
expect(await db.select().from(companySecrets).where(eq(companySecrets.companyId, company.id))).toEqual([]);
|
||||
await settings.updateExperimental({ enablePaperclipNotebook: true });
|
||||
useNotebookFixtureEndpoint();
|
||||
const fixture = installMcpOAuthFixture({ auth: "oauth", notebookAccount: { id: "cloud-owner", email: "owner@example.test", emailVerified: true } });
|
||||
const enabledGallery = await request(app).get(`/api/companies/${company.id}/tools/gallery`).expect(200);
|
||||
expect(enabledGallery.body.apps.some((item: { slug: string }) => item.slug === "paperclip-notebook")).toBe(true);
|
||||
const connected = await service.connectGalleryApp(company.id, { galleryKey: "paperclip-notebook", grantKind: "user" }, actor);
|
||||
const start = await service.startOAuth(company.id, connected.connectionId, { redirectUri: REDIRECT_URI, actor });
|
||||
const saved = await service.getConnection(connected.connectionId, company.id);
|
||||
const config = { ...saved.config };
|
||||
delete config.sourceTemplateKey;
|
||||
if (marker === "relabelled") config.sourceTemplateKey = "custom-mcp";
|
||||
await service.updateConnection(connected.connectionId, { config });
|
||||
await settings.updateExperimental({ enablePaperclipNotebook: false });
|
||||
await expect(service.completeOAuthCallback({ state: new URL(start.authorizationUrl).searchParams.get("state")!,
|
||||
code: fixture.issueAuthorizationCode(start.authorizationUrl), iss: ISSUER, redirectUri: REDIRECT_URI, actor }))
|
||||
.rejects.toMatchObject({ status: 403, details: { code: "connector_disabled" } });
|
||||
expect(fixture.requestsTo("/token")).toHaveLength(0);
|
||||
await expect(service.startOAuth(company.id, connected.connectionId, { redirectUri: REDIRECT_URI, actor }))
|
||||
.rejects.toMatchObject({ status: 403, details: { code: "connector_disabled" } });
|
||||
await expect(service.reconnectGalleryApp(connected.connectionId, company.id, { credentialValues: {} }, actor))
|
||||
.rejects.toMatchObject({ status: 403, details: { code: "connector_disabled" } });
|
||||
await expect(service.connectGalleryApp(company.id, { resumeConnectionId: connected.connectionId, grantKind: "user" }, actor))
|
||||
.rejects.toMatchObject({ status: 403, details: { code: "connector_disabled" } });
|
||||
await expect(service.finishGalleryAppConnection(company.id, connected.connectionId, { enabledCatalogEntryIds: [], askFirstCatalogEntryIds: [], access: { agentIds: [] } }, actor))
|
||||
.rejects.toMatchObject({ status: 403, details: { code: "connector_disabled" } });
|
||||
await expect(service.archiveConnection(connected.connectionId, company.id, actor)).resolves.toMatchObject({ connection: { status: "archived" } });
|
||||
});
|
||||
|
||||
it("connects Notebook with personal OAuth and preserves policies across ordinary rotation, reconnect, and local removal", async () => {
|
||||
await instanceSettingsService(db).updateExperimental({ enablePaperclipNotebook: true });
|
||||
useNotebookFixtureEndpoint();
|
||||
const scopes = ["notebook:read", "notebook:write", "notebook:share", "notebook:delete"];
|
||||
const fixture = installMcpOAuthFixture({ auth: "oauth", scopes, rotateRefreshTokens: true,
|
||||
notebookAccount: { id: "cloud-owner", email: "owner@example.test", emailVerified: true },
|
||||
tools: [
|
||||
{ name: "notebook_get_account", annotations: { readOnlyHint: true } },
|
||||
{ name: "notebook_list_pages", annotations: { readOnlyHint: true } },
|
||||
{ name: "notebook_publish", annotations: { readOnlyHint: false } },
|
||||
{ name: "notebook_set_sharing", annotations: { readOnlyHint: false } },
|
||||
{ name: "notebook_delete_page", annotations: { readOnlyHint: false, destructiveHint: true } },
|
||||
] });
|
||||
const company = await createCompany(db);
|
||||
const serviceDb = createDb(externalTestDatabaseUrl ?? tempDb!.connectionString, { maxConnections: 1 });
|
||||
const service = toolAccessService(serviceDb, { paperclipCloudConnector: null });
|
||||
const actor = { actorType: "user" as const, actorId: "board-user" };
|
||||
const connected = await service.connectGalleryApp(company.id, { galleryKey: "paperclip-notebook" }, actor);
|
||||
const authorize = async () => {
|
||||
const start = await service.startOAuth(company.id, connected.connectionId, { redirectUri: REDIRECT_URI, actor });
|
||||
expect(start.registrationSource).toBe("dcr");
|
||||
const authorization = new URL(start.authorizationUrl);
|
||||
expect(authorization.searchParams.get("resource")).toBe(MCP_URL);
|
||||
expect(authorization.searchParams.get("code_challenge_method")).toBe("S256");
|
||||
expect(authorization.searchParams.get("scope")?.split(" ")).toEqual(scopes);
|
||||
return service.completeOAuthCallback({ state: authorization.searchParams.get("state")!, code: fixture.issueAuthorizationCode(start.authorizationUrl),
|
||||
iss: ISSUER, redirectUri: REDIRECT_URI, actor });
|
||||
};
|
||||
const completed = await authorize();
|
||||
expect(completed.connection).toMatchObject({ name: "Paperclip Notebook", credentialPolicy: "per_user" });
|
||||
expect(completed.catalog).toHaveLength(5);
|
||||
expect(completed.catalog.every(entry => entry.status === "active")).toBe(true);
|
||||
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId));
|
||||
expect(grant).toMatchObject({ kind: "user", subjectUserId: "board-user" });
|
||||
expect(grant!.providerTenant).not.toHaveProperty("name");
|
||||
expect(grant!.providerTenant).not.toHaveProperty("externalId");
|
||||
expect(fixture.requestsTo("/mcp").filter(call => (call.body as Record<string, unknown>)?.method === "tools/call")).toEqual([]);
|
||||
const stored = await db.select().from(companySecrets).where(inArray(companySecrets.id, grant!.credentialSecretRefs.map(ref => ref.secretId)));
|
||||
expect(stored).toHaveLength(2);
|
||||
expect(stored.every(secret => secret.scope === "user" && secret.ownerUserId === "board-user")).toBe(true);
|
||||
expect(JSON.stringify(completed)).not.toContain("fixture-access-");
|
||||
for (let rotation = 0; rotation < 2; rotation += 1) {
|
||||
await service.refreshOAuthGrantCredentials({ companyId: company.id, connectionId: connected.connectionId, grantId: grant!.id, forceRefresh: true, actor });
|
||||
}
|
||||
const refreshRequests = fixture.requestsTo("/token").filter(call => (call.body as URLSearchParams).get("grant_type") === "refresh_token");
|
||||
expect(refreshRequests).toHaveLength(2);
|
||||
expect((refreshRequests[0]!.body as URLSearchParams).get("refresh_token")).toBe(fixture.tokenResponses[0]!.refresh_token);
|
||||
expect((refreshRequests[1]!.body as URLSearchParams).get("refresh_token")).toBe(fixture.tokenResponses[1]!.refresh_token);
|
||||
expect(fixture.tokenResponses[0]!.refresh_token).not.toBe(fixture.tokenResponses[1]!.refresh_token);
|
||||
expect(fixture.requests.every(call => call.headers["idempotency-key"] === undefined)).toBe(true);
|
||||
const [agent] = await db.insert(agents).values({ companyId: company.id, name: "Notebook author", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning();
|
||||
const [unassigned] = await db.insert(agents).values({ companyId: company.id, name: "Unassigned", role: "engineer", status: "active", adapterType: "process", adapterConfig: {}, runtimeConfig: {} }).returning();
|
||||
await service.finishGalleryAppConnection(company.id, connected.connectionId, {
|
||||
enabledCatalogEntryIds: completed.catalog.filter(entry => entry.toolName !== "notebook_delete_page").map(entry => entry.id),
|
||||
askFirstCatalogEntryIds: completed.catalog.filter(entry => entry.toolName === "notebook_set_sharing").map(entry => entry.id), access: { agentIds: [agent!.id] },
|
||||
}, actor);
|
||||
await authorize();
|
||||
expect(await db.select({ id: connectionGrants.id }).from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId))).toEqual([{ id: grant!.id }]);
|
||||
const policy = toolAccessPolicyService(db);
|
||||
const decision = (name: string, agentId = agent!.id) => {
|
||||
const entry = completed.catalog.find(entry => entry.toolName === name)!;
|
||||
return policy.decide({ companyId: company.id, actor: { actorType: "agent", actorId: agentId, agentId },
|
||||
request: { connectionId: connected.connectionId, catalogEntryId: entry.id, toolName: name } });
|
||||
};
|
||||
await expect(decision("notebook_publish")).resolves.toMatchObject({ allowed: true });
|
||||
await expect(decision("notebook_set_sharing")).resolves.toMatchObject({ allowed: false, decision: "require_approval" });
|
||||
await expect(decision("notebook_delete_page")).resolves.toMatchObject({ allowed: false, decision: "deny" });
|
||||
await expect(decision("notebook_publish", unassigned!.id)).resolves.toMatchObject({ allowed: false });
|
||||
const [issue] = await db.insert(issues).values({ companyId: company.id, title: "Notebook MCP publication", status: "in_progress", assigneeAgentId: agent!.id }).returning();
|
||||
const [run] = await db.insert(heartbeatRuns).values({ companyId: company.id, agentId: agent!.id, invocationSource: "assignment", status: "running",
|
||||
responsibleUserId: "board-user", contextSnapshot: { issueId: issue!.id } }).returning();
|
||||
const [profile] = await db.select().from(toolProfiles).where(eq(toolProfiles.profileKey, `app:${connected.connectionId}`));
|
||||
const gateway = createToolGatewayService(db, { toolActionSigningSecret: "notebook-mcp-fixture" });
|
||||
const named = await gateway.createNamedGateway({ companyId: company.id, body: { name: "Notebook MCP", profileId: profile!.id, agentId: agent!.id, issueId: issue!.id } });
|
||||
const token = await gateway.createNamedGatewayToken({ companyId: company.id, gatewayId: named.id, body: { name: "Notebook run", subjectType: "heartbeat_run", subjectId: run!.id } });
|
||||
const descriptors = await gateway.listToolsForNamedGateway({ gatewayPublicId: named.gatewayPublicId, bearerToken: token.token });
|
||||
const publish = descriptors.find(tool => tool.upstreamToolName === "notebook_publish")!;
|
||||
const share = descriptors.find(tool => tool.upstreamToolName === "notebook_set_sharing")!;
|
||||
expect(descriptors.some(tool => tool.upstreamToolName === "notebook_delete_page")).toBe(false);
|
||||
await expect(gateway.executeTool({ gatewayPublicId: named.gatewayPublicId, sessionToken: token.token, tool: publish.name, parameters: {} })).resolves.toMatchObject({ status: "completed" });
|
||||
const callsBeforeApproval = fixture.requestsTo("/mcp").length;
|
||||
await expect(gateway.executeTool({ gatewayPublicId: named.gatewayPublicId, sessionToken: token.token, tool: share.name, parameters: {} })).rejects.toMatchObject({ reasonCode: "approval_required" });
|
||||
expect(fixture.requestsTo("/mcp")).toHaveLength(callsBeforeApproval);
|
||||
const [action] = await db.select().from(toolActionRequests).where(and(eq(toolActionRequests.companyId, company.id), eq(toolActionRequests.status, "pending")));
|
||||
expect(action).toBeDefined();
|
||||
const saved = await service.getConnection(connected.connectionId, company.id);
|
||||
const config = { ...saved.config };
|
||||
delete config.sourceTemplateKey;
|
||||
await service.updateConnection(connected.connectionId, { config });
|
||||
const [currentGrant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant!.id));
|
||||
await db.update(connectionGrants).set({ providerTenant: { ...currentGrant!.providerTenant, oauth: {
|
||||
...currentGrant!.providerTenant?.oauth, accessTokenExpiresAt: new Date(0).toISOString(),
|
||||
} } }).where(eq(connectionGrants.id, grant!.id));
|
||||
await instanceSettingsService(db).updateExperimental({ enablePaperclipNotebook: false });
|
||||
const callsBeforeDisabledDispatch = fixture.requestsTo("/mcp").length;
|
||||
expect(await gateway.listToolsForNamedGateway({ gatewayPublicId: named.gatewayPublicId, bearerToken: token.token })).toEqual([]);
|
||||
await expect(gateway.executeTool({ gatewayPublicId: named.gatewayPublicId, sessionToken: token.token, tool: publish.name, parameters: {} })).rejects.toMatchObject({ reasonCode: "tool_not_found" });
|
||||
await expect(gateway.approveActionRequest({ companyId: company.id, actionRequestId: action!.id, actor: { userId: "board-user" } })).rejects.toMatchObject({ reasonCode: "tool_not_found" });
|
||||
const intents = connectionIntentService(db);
|
||||
const claims = { sub: agent!.id, company_id: company.id, run_id: run!.id, responsible_user_id: "board-user" };
|
||||
expect((await intents.search(claims, "Paperclip Notebook")).results.some(item => item.service === "paperclip-notebook")).toBe(false);
|
||||
await expect(intents.request(claims, "paperclip-notebook")).rejects.toMatchObject({ status: 404 });
|
||||
expect(fixture.requestsTo("/mcp")).toHaveLength(callsBeforeDisabledDispatch);
|
||||
const tokenRequestsWhileOff = fixture.requestsTo("/token").length;
|
||||
const mcpRequestsWhileOff = fixture.requestsTo("/mcp").length;
|
||||
const secretAccessBeforeOff = await db.select({ id: secretAccessEvents.id }).from(secretAccessEvents);
|
||||
await expect(service.checkHealth(connected.connectionId, actor)).rejects.toMatchObject({ status: 403, details: { code: "connector_disabled" } });
|
||||
await expect(service.refreshCatalog(connected.connectionId, actor)).rejects.toMatchObject({ status: 403, details: { code: "connector_disabled" } });
|
||||
expect(fixture.requestsTo("/token")).toHaveLength(tokenRequestsWhileOff);
|
||||
expect(fixture.requestsTo("/mcp")).toHaveLength(mcpRequestsWhileOff);
|
||||
expect(await db.select({ id: secretAccessEvents.id }).from(secretAccessEvents)).toEqual(secretAccessBeforeOff);
|
||||
const removed = await service.archiveConnection(connected.connectionId, company.id, actor);
|
||||
expect(removed.connection.status).toBe("archived");
|
||||
expect(removed.removal).not.toHaveProperty("oauthRevocationPending");
|
||||
await expect(decision("notebook_publish")).resolves.toMatchObject({ allowed: false });
|
||||
const [removedGrant] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant!.id));
|
||||
expect(removedGrant).toMatchObject({ status: "revoked", credentialSecretRefs: [] });
|
||||
expect(await db.select().from(companySecrets).where(inArray(companySecrets.id, currentGrant!.credentialSecretRefs.map(ref => ref.secretId)))).toEqual([]);
|
||||
expect(fixture.requestsTo("/oauth/revoke")).toEqual([]);
|
||||
await instanceSettingsService(db).updateExperimental({ enablePaperclipNotebook: true });
|
||||
await service.connectGalleryApp(company.id, { galleryKey: "paperclip-notebook", applicationId: connected.application.id }, actor);
|
||||
await authorize();
|
||||
expect(fixture.requestsTo("/oauth/revoke")).toEqual([]);
|
||||
expect(fixture.requests.every(call => call.headers["idempotency-key"] === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it("reconnects Notebook after a lost rotating refresh response requires new authorization", async () => {
|
||||
await instanceSettingsService(db).updateExperimental({ enablePaperclipNotebook: true });
|
||||
useNotebookFixtureEndpoint();
|
||||
const fixture = installMcpOAuthFixture({ auth: "oauth", rotateRefreshTokens: true, dropFirstRefreshResponse: true,
|
||||
notebookAccount: { id: "cloud-owner", email: "owner@example.test", emailVerified: true } });
|
||||
const company = await createCompany(db), service = toolAccessService(db, { paperclipCloudConnector: null });
|
||||
const actor = { actorType: "user" as const, actorId: "board-user" };
|
||||
const connected = await service.connectGalleryApp(company.id, { galleryKey: "paperclip-notebook" }, actor);
|
||||
const authorize = async () => {
|
||||
const start = await service.startOAuth(company.id, connected.connectionId, { redirectUri: REDIRECT_URI, actor });
|
||||
return service.completeOAuthCallback({ state: new URL(start.authorizationUrl).searchParams.get("state")!, code: fixture.issueAuthorizationCode(start.authorizationUrl),
|
||||
iss: ISSUER, redirectUri: REDIRECT_URI, actor });
|
||||
};
|
||||
await authorize();
|
||||
const [grant] = await db.select().from(connectionGrants).where(eq(connectionGrants.connectionId, connected.connectionId));
|
||||
const refresh = () => service.refreshOAuthGrantCredentials({ companyId: company.id, connectionId: connected.connectionId, grantId: grant!.id, forceRefresh: true, actor });
|
||||
await expect(refresh()).rejects.toThrow("Fixture lost the committed rotating refresh response");
|
||||
expect(fixture.requestsTo("/token")).toHaveLength(2);
|
||||
await expect(refresh()).rejects.toMatchObject({ status: 422, details: { code: "oauth_reauthorization_required" } });
|
||||
const [expired] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant!.id));
|
||||
expect(expired!.status).toBe("needs_reauthorization");
|
||||
await authorize();
|
||||
const [renewed] = await db.select().from(connectionGrants).where(eq(connectionGrants.id, grant!.id));
|
||||
expect(renewed).toMatchObject({ status: "active", credentialSecretRefs: expect.any(Array) });
|
||||
expect(renewed!.credentialSecretRefs).toHaveLength(2);
|
||||
await expect(refresh()).resolves.toMatchObject({ status: "active" });
|
||||
expect(fixture.requestsTo("/oauth/revoke")).toEqual([]);
|
||||
expect(fixture.requests.every(call => call.headers["idempotency-key"] === undefined)).toBe(true);
|
||||
});
|
||||
|
||||
it.each(["mcp-oauth", "mcp-api-key"])("connects Fireflies through %s with vaulted credentials and its stable meeting tools", async (methodKey) => {
|
||||
// Keep the real catalog method and governance identity; redirect only its
|
||||
// transport URL to the deterministic protocol fixture.
|
||||
@@ -1332,7 +1673,7 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
|
||||
it("completes organization OAuth with a single database connection", async () => {
|
||||
const fixture = installMcpOAuthFixture({ auth: "oauth" });
|
||||
const company = await createCompany(db);
|
||||
const callbackDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
|
||||
const callbackDb = createDb(externalTestDatabaseUrl ?? tempDb!.connectionString, { maxConnections: 1 });
|
||||
const service = toolAccessService(callbackDb);
|
||||
let deadline: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
@@ -1416,8 +1757,8 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
|
||||
it("serializes organization OAuth completion behind membership revocation", async () => {
|
||||
const fixture = installMcpOAuthFixture({ auth: "oauth" });
|
||||
const company = await createCompany(db);
|
||||
const callbackDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
|
||||
const removalDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
|
||||
const callbackDb = createDb(externalTestDatabaseUrl ?? tempDb!.connectionString, { maxConnections: 1 });
|
||||
const removalDb = createDb(externalTestDatabaseUrl ?? tempDb!.connectionString, { maxConnections: 1 });
|
||||
const service = toolAccessService(callbackDb);
|
||||
const actor = { actorType: "user" as const, actorId: "board-user" };
|
||||
let releaseRemoval!: () => void;
|
||||
@@ -2187,7 +2528,7 @@ describeEmbeddedPostgres("generic remote MCP connections", () => {
|
||||
// serialize the two callbacks and prove nothing. With two connections both
|
||||
// callbacks can read a live state row before either deletes it, so the
|
||||
// atomic `DELETE … RETURNING` is what picks the winner.
|
||||
const otherDb = createDb(tempDb!.connectionString);
|
||||
const otherDb = createDb(externalTestDatabaseUrl ?? tempDb!.connectionString);
|
||||
const otherService = toolAccessService(otherDb);
|
||||
let settled: PromiseSettledResult<unknown>[];
|
||||
try {
|
||||
|
||||
@@ -85,6 +85,43 @@ describe("applyManagedExperimentalOverlay", () => {
|
||||
});
|
||||
|
||||
describe("instanceSettingsService managed overlay", () => {
|
||||
it.each(["team.staging.paperclip.app", "team.paperclip.app"])(
|
||||
"enables private Notebook through managed config without changing stored opt-out on %s",
|
||||
async (primaryHost) => {
|
||||
const row = settingsRow({ enablePaperclipNotebook: false });
|
||||
const { db, persistedSets } = stubDb(row);
|
||||
const service = instanceSettingsService(db, { runtimeEnv: {
|
||||
PAPERCLIP_PRIMARY_HOST: primaryHost,
|
||||
...managedEnv(JSON.stringify({
|
||||
v: 1, mode: "cloud", catalogVersion: "test",
|
||||
features: { enablePaperclipNotebook: true }, plugins: { autoInstall: [] },
|
||||
})),
|
||||
} });
|
||||
expect(await service.getExperimental()).toMatchObject({
|
||||
enablePaperclipNotebook: true,
|
||||
managedKeys: { enablePaperclipNotebook: { managed: true, managedBy: "paperclip-cloud" } },
|
||||
});
|
||||
expect((await service.get()).experimental.enablePaperclipNotebook).toBe(true);
|
||||
expect(persistedSets).toHaveLength(0);
|
||||
expect(row.experimental).toEqual({ enablePaperclipNotebook: false });
|
||||
expect((await instanceSettingsService(db, { runtimeEnv: {} }).getExperimental()).enablePaperclipNotebook).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it("persists an explicit self-hosted Notebook opt-in and disable across service recreation", async () => {
|
||||
const row = settingsRow({});
|
||||
const { db, persistedSets } = stubDb(row);
|
||||
expect((await instanceSettingsService(db, { runtimeEnv: {} }).getExperimental()).enablePaperclipNotebook).toBe(false);
|
||||
for (const enabled of [true, false]) {
|
||||
const service = instanceSettingsService(db, { runtimeEnv: {} });
|
||||
const updated = await service.updateExperimental({ enablePaperclipNotebook: enabled });
|
||||
Object.assign(row, persistedSets.at(-1));
|
||||
expect(updated.experimental.enablePaperclipNotebook).toBe(enabled);
|
||||
expect((row.experimental as Record<string, unknown>).enablePaperclipNotebook).toBe(enabled);
|
||||
expect((await instanceSettingsService(db, { runtimeEnv: {} }).getExperimental()).enablePaperclipNotebook).toBe(enabled);
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["team.staging.paperclip.app", "team.paperclip.app", undefined])(
|
||||
"enforces every Cloud-enabled flag over old tenant values on %s",
|
||||
async (primaryHost) => {
|
||||
|
||||
@@ -912,6 +912,38 @@ describe("instance settings routes", () => {
|
||||
});
|
||||
|
||||
describe("Cloud staging experiments", () => {
|
||||
it.each([
|
||||
["team.staging.paperclip.app", 200],
|
||||
["team.paperclip.app", 403],
|
||||
] as const)(
|
||||
"keeps private Notebook operator-only under the real hidden wildcard on %s",
|
||||
async (primaryHost, visibleExperimentStatus) => {
|
||||
vi.stubEnv("PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN", "tenant-token");
|
||||
vi.stubEnv("PAPERCLIP_PRIMARY_HOST", primaryHost);
|
||||
vi.stubEnv("PAPERCLIP_HIDDEN_SETTINGS", "instance.experimental.*");
|
||||
mockInstanceSettingsService.getExperimental.mockResolvedValue({
|
||||
enablePaperclipNotebook: false, enableChatConnectors: false,
|
||||
});
|
||||
const app = createApp({
|
||||
type: "board", userId: "stack-admin-1", source: "cloud_tenant",
|
||||
companyIds: ["company-1"], isInstanceAdmin: false, canManageExperimentalSettings: true,
|
||||
});
|
||||
const denied = await request(app).patch("/api/instance/settings/experimental")
|
||||
.send({ enablePaperclipNotebook: true }).expect(403);
|
||||
expect(denied.body.details).toMatchObject({ code: "settings_operator_managed" });
|
||||
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
|
||||
expect(mockLogActivity).not.toHaveBeenCalled();
|
||||
|
||||
await request(app).patch("/api/instance/settings/experimental")
|
||||
.send({ enableChatConnectors: true }).expect(visibleExperimentStatus);
|
||||
if (visibleExperimentStatus === 200) {
|
||||
expect(mockInstanceSettingsService.updateExperimental).toHaveBeenCalledExactlyOnceWith({ enableChatConnectors: true });
|
||||
} else {
|
||||
expect(mockInstanceSettingsService.updateExperimental).not.toHaveBeenCalled();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["team.staging.paperclip.app", "team.paperclip.app"])(
|
||||
"reads Cloud-enabled isolation and rejects disabling it through the real service on %s",
|
||||
async (primaryHost) => {
|
||||
|
||||
@@ -7,6 +7,18 @@ import {
|
||||
} from "../services/instance-settings.js";
|
||||
|
||||
describe("instance settings service", () => {
|
||||
it("keeps Notebook off for legacy or invalid settings and round-trips explicit operator choices", () => {
|
||||
for (const stored of [undefined, null, {}, { enableApps: true },
|
||||
{ enablePaperclipNotebook: "true" }, { enablePaperclipNotebook: 1 },
|
||||
{ enablePaperclipNotebook: true, enableCases: "invalid" }]) {
|
||||
expect(normalizeExperimentalSettings(stored).enablePaperclipNotebook).toBe(false);
|
||||
}
|
||||
const enabled = applyExperimentalSettingsPatch({}, { enablePaperclipNotebook: true });
|
||||
const restored = normalizeExperimentalSettings(JSON.parse(JSON.stringify(enabled)));
|
||||
expect(restored).toMatchObject({ enablePaperclipNotebook: true, enableMemoryConnectors: false });
|
||||
const disabled = applyExperimentalSettingsPatch(restored, { enablePaperclipNotebook: false });
|
||||
expect(normalizeExperimentalSettings(JSON.parse(JSON.stringify(disabled))).enablePaperclipNotebook).toBe(false);
|
||||
});
|
||||
it("keeps OpenAI Dot opt-in and persists its setting independently of its prerequisites", () => {
|
||||
expect(normalizeExperimentalSettings({}).enableOpenAiDot).toBe(false);
|
||||
const enabled = applyExperimentalSettingsPatch({}, { enableOpenAiDot: true });
|
||||
@@ -67,6 +79,7 @@ describe("instance settings service", () => {
|
||||
enableChatConnectors: false,
|
||||
enableGitHubReviewBots: false,
|
||||
enableMemoryConnectors: false,
|
||||
enablePaperclipNotebook: false,
|
||||
enableConferenceRoomChat: false,
|
||||
enableClassicTaskInterface: false,
|
||||
enableExternalObjects: false,
|
||||
|
||||
@@ -94,6 +94,7 @@ import { HttpError } from "../errors.js";
|
||||
import type { VercelConnectClient } from "../services/vercel-connect.js";
|
||||
import { invalidatePaperclipCloudConnectorCapabilities, type PaperclipCloudConnector } from "../services/paperclip-cloud-connector.js";
|
||||
|
||||
const externalDatabaseUrl = process.env.PAPERCLIP_TOOL_ACCESS_TEST_DATABASE_URL?.trim();
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported
|
||||
? describe
|
||||
@@ -909,8 +910,6 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
> | null = null;
|
||||
|
||||
beforeAll(async () => {
|
||||
const externalDatabaseUrl =
|
||||
process.env.PAPERCLIP_TOOL_ACCESS_TEST_DATABASE_URL?.trim();
|
||||
if (externalDatabaseUrl) {
|
||||
db = createDb(externalDatabaseUrl);
|
||||
await instanceSettingsService(db).updateExperimental({ enableMemoryConnectors: true });
|
||||
@@ -1104,8 +1103,8 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
const { run } = await createIssueAndRun(db, company.id, agent.id);
|
||||
const { connection } = await createBrokerConnection(db, company.id);
|
||||
await allowConnectionForAgent(db, company.id, agent.id, connection.id);
|
||||
const mintDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
|
||||
const revocationDb = createDb(tempDb!.connectionString, {
|
||||
const mintDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, { maxConnections: 1 });
|
||||
const revocationDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, {
|
||||
maxConnections: 1,
|
||||
});
|
||||
const service = createTestToolAccessService(mintDb);
|
||||
@@ -1691,9 +1690,9 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
.values(personalGrantRow(company, connection))
|
||||
.returning()
|
||||
.then((rows) => rows[0]!);
|
||||
const serviceDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
|
||||
const serviceDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, { maxConnections: 1 });
|
||||
const service = createTestToolAccessService(serviceDb);
|
||||
const removalDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
|
||||
const removalDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, { maxConnections: 1 });
|
||||
let releaseRemoval!: () => void;
|
||||
const removalMayCommit = new Promise<void>((resolve) => {
|
||||
releaseRemoval = resolve;
|
||||
@@ -1973,13 +1972,13 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
subjectId: "previous-user",
|
||||
});
|
||||
|
||||
const firstReplacementDb = createDb(tempDb!.connectionString, {
|
||||
const firstReplacementDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, {
|
||||
maxConnections: 1,
|
||||
});
|
||||
const replacementDb = createDb(tempDb!.connectionString, {
|
||||
const replacementDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, {
|
||||
maxConnections: 1,
|
||||
});
|
||||
const cleanupDb = createDb(tempDb!.connectionString, {
|
||||
const cleanupDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, {
|
||||
maxConnections: 1,
|
||||
});
|
||||
const replacementService = createTestToolAccessService(replacementDb);
|
||||
@@ -7579,7 +7578,7 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
const company = await createCompany(db);
|
||||
const userId = `gmail-member-${randomUUID()}`;
|
||||
await grantBoardUser(db, company.id, userId, []);
|
||||
const callbackDb = createDb(tempDb!.connectionString, {
|
||||
const callbackDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, {
|
||||
maxConnections: 1,
|
||||
});
|
||||
const connector = fakeGmailConnector(company.id, userId);
|
||||
@@ -9383,7 +9382,7 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
await grantBoardUser(db, company.id, userId, [], "owner");
|
||||
const actor = { actorType: "user" as const, actorId: userId };
|
||||
const connector = fakeGmailConnector(company.id, userId);
|
||||
const refreshDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
|
||||
const refreshDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, { maxConnections: 1 });
|
||||
const service = createTestToolAccessService(db, { paperclipCloudConnector: connector });
|
||||
const definition = getConnectableAppDefinition("gmail")!;
|
||||
const availability = definition.ownershipAvailability;
|
||||
@@ -9523,10 +9522,10 @@ describeEmbeddedPostgres("tool access service", () => {
|
||||
const company = await createCompany(db);
|
||||
const userId = `gmail-member-${randomUUID()}`;
|
||||
await grantBoardUser(db, company.id, userId, []);
|
||||
const callbackDb = createDb(tempDb!.connectionString, {
|
||||
const callbackDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, {
|
||||
maxConnections: 1,
|
||||
});
|
||||
const removalDb = createDb(tempDb!.connectionString, { maxConnections: 1 });
|
||||
const removalDb = createDb(externalDatabaseUrl ?? tempDb!.connectionString, { maxConnections: 1 });
|
||||
const service = createTestToolAccessService(callbackDb, {
|
||||
paperclipCloudConnector: fakeGmailConnector(company.id, userId),
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import { agents, companies, connectionGrants, issueThreadInteractions, toolConne
|
||||
import { and, eq, or } from "drizzle-orm";
|
||||
import {
|
||||
APP_STORE_DEFINITIONS,
|
||||
isConnectorFeatureEnabled,
|
||||
isMemoryConnectorId,
|
||||
GITHUB_CONNECTOR_PROFILES,
|
||||
GOOGLE_WORKSPACE_CONNECTOR_PROFILES,
|
||||
@@ -819,7 +820,7 @@ function connectorEnrollmentPrincipal(req: Request): string {
|
||||
? await options.paperclipCloudConnector.getCapabilities()
|
||||
: [];
|
||||
const vercelConnect = vercelConnectIntegrationStatus();
|
||||
const { enableMemoryConnectors } = await instanceSettingsService(db).getExperimental();
|
||||
const settings = await instanceSettingsService(db).getExperimental();
|
||||
let oauthCallbackUrl: string | undefined;
|
||||
try {
|
||||
// Setup must display the callback used by its initiating POST. Provider
|
||||
@@ -850,7 +851,8 @@ function connectorEnrollmentPrincipal(req: Request): string {
|
||||
: "Vercel Connect setup is disabled on this Paperclip instance.",
|
||||
},
|
||||
},
|
||||
apps: [...APP_STORE_DEFINITIONS.filter((app) => (enableMemoryConnectors || !isMemoryConnectorId(app.slug))).map((app) =>
|
||||
apps: [...APP_STORE_DEFINITIONS.filter((app) => (settings.enableMemoryConnectors || !isMemoryConnectorId(app.slug))
|
||||
&& isConnectorFeatureEnabled(app, settings)).map((app) =>
|
||||
appWithPaperclipCloudConnectorAvailability(app, advertisedProfiles)
|
||||
), ...await aiConnectionRouterService(db).catalog()],
|
||||
});
|
||||
|
||||
@@ -29,6 +29,8 @@ import {
|
||||
} from "@paperclipai/db";
|
||||
import {
|
||||
APP_STORE_DEFINITIONS,
|
||||
isConnectorFeatureEnabled,
|
||||
getAppDefinitionForApplicationKey,
|
||||
AGGREGATOR_PRIORITY, AGGREGATOR_NAMES, AGGREGATOR_CATALOG_SOURCES,
|
||||
findAggregatorService, searchAggregatorServices, prepareConnectionSearch, scoreConnectionSearch, explicitAggregatorQuery, normalizeConnectionQuery, parseAggregatorRoute, aggregatorProviderQuestion, aggregatorProviderQuestionSet,
|
||||
aggregatorContinuationInstruction, isRemoteMcpConnectorId, askUserQuestionsPayloadSchema, askUserQuestionsResultSchema,
|
||||
@@ -364,6 +366,9 @@ export function connectionIntentService(db: Db) {
|
||||
if (!service.startsWith("connection:")) {
|
||||
const app = getAppStoreDefinition(service);
|
||||
if (!app) throw notFound("Connection service was not found");
|
||||
if (app.experimentalFeatureKey && !isConnectorFeatureEnabled(app, await instanceSettingsService(db).getExperimental())) {
|
||||
throw notFound("Connection service was not found");
|
||||
}
|
||||
if (purpose === "channel" && service !== "agentmail") {
|
||||
throw unprocessable("This email connection is not available");
|
||||
}
|
||||
@@ -389,6 +394,14 @@ export function connectionIntentService(db: Db) {
|
||||
|| (grant.kind === "agent" && grant.subjectAgentId === agentId)
|
||||
))) throw notFound("Configured connection was not found");
|
||||
const application = await access.getApplication(connection.applicationId, companyId);
|
||||
const definition = application.applicationKey != null
|
||||
? getAppDefinitionForApplicationKey(application.applicationKey)
|
||||
: typeof connection.config?.sourceTemplateKey === "string"
|
||||
? getAppStoreDefinition(connection.config?.sourceTemplateKey) : null;
|
||||
if (definition?.experimentalFeatureKey && !isConnectorFeatureEnabled(definition,
|
||||
await instanceSettingsService(db).getExperimental())) {
|
||||
throw notFound("Configured connection was not found");
|
||||
}
|
||||
return {
|
||||
slug: service, name: connection.name, description: application.description, searchCapabilities: "",
|
||||
branding: { logoUrl: undefined, darkLogoUrl: undefined },
|
||||
@@ -413,7 +426,8 @@ export function connectionIntentService(db: Db) {
|
||||
const discoveryMethods = (app: (typeof APP_STORE_DEFINITIONS)[number]) => getAvailableConnectionMethods(app)
|
||||
.filter(method => method.purpose !== "channel" || app.slug === "agentmail"
|
||||
|| (method.provider === "github" ? settings.enableGitHubReviewBots : settings.enableChatConnectors));
|
||||
const services = [...APP_STORE_DEFINITIONS.filter(app => discoveryMethods(app).length).map((app) => app.slug),
|
||||
const services = [...APP_STORE_DEFINITIONS.filter(app => isConnectorFeatureEnabled(app, settings)
|
||||
&& discoveryMethods(app).length).map((app) => app.slug),
|
||||
...inventory.connections.filter((connection) =>
|
||||
sourceSlugForConnection(connection, inventory.applicationsById)?.startsWith("connection:")
|
||||
&& connection.status !== "archived").map((connection) => `connection:${connection.id}`)];
|
||||
|
||||
@@ -243,6 +243,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableChatConnectors: parsed.data.enableChatConnectors ?? false,
|
||||
enableGitHubReviewBots: parsed.data.enableGitHubReviewBots ?? false,
|
||||
enableMemoryConnectors: parsed.data.enableMemoryConnectors ?? false,
|
||||
enablePaperclipNotebook: parsed.data.enablePaperclipNotebook ?? false,
|
||||
enableCases: parsed.data.enableCases ?? false,
|
||||
enableAgentChat: parsed.data.enableAgentChat ?? false,
|
||||
enableCombinedInboxTasks: parsed.data.enableCombinedInboxTasks ?? false,
|
||||
@@ -293,6 +294,7 @@ export function normalizeExperimentalSettings(raw: unknown): InstanceExperimenta
|
||||
enableChatConnectors: false,
|
||||
enableGitHubReviewBots: false,
|
||||
enableMemoryConnectors: false,
|
||||
enablePaperclipNotebook: false,
|
||||
enableCases: false,
|
||||
enableAgentChat: false,
|
||||
enableCombinedInboxTasks: false,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { getAppDefinitionForApplicationKey, isConnectorFeatureEnabled } from "@paperclipai/shared";
|
||||
import { stableHash, descriptorHash } from "./tool-catalog-hash.js";
|
||||
import { assertProfileEntryInputs } from "./tool-profile-entry-validation.js";
|
||||
import { DAYTONA_TOOLS, daytonaClient, daytonaRisk, isDaytonaConnection, isDaytonaToolName } from "./daytona.js";
|
||||
@@ -7182,6 +7183,7 @@ export function toolAccessService(
|
||||
unavailableServices: string[] = [],
|
||||
): Promise<McpToolDescriptor[]> {
|
||||
assertSupportedConnection(connection);
|
||||
await assertConnectorConnectionSetupEnabled(connection);
|
||||
let headers = credentialHeaders ?? {
|
||||
...projectedConnectionHeaders(connection),
|
||||
...(await resolveCredentialHeaders(connection, actor)),
|
||||
@@ -7561,6 +7563,7 @@ export function toolAccessService(
|
||||
unavailableServices: string[] = [],
|
||||
): Promise<McpToolDescriptor[]> {
|
||||
assertSupportedConnection(connection);
|
||||
await assertConnectorConnectionSetupEnabled(connection);
|
||||
if (connection.connectionPurpose === "ai") throw unprocessable("AI connections provide runtime authentication, not tool actions");
|
||||
if (isDaytonaConnection(connection)) {
|
||||
const headers = credentialHeaders ?? await resolveCredentialHeaders(connection, actor);
|
||||
@@ -7681,6 +7684,7 @@ export function toolAccessService(
|
||||
): Promise<ToolConnectionHealthCheckResult> {
|
||||
const connection = await getConnectionRow(connectionId);
|
||||
if (connection.connectionPurpose === "ai") return { connection: toConnection(connection), runtimeSlot: null };
|
||||
await assertConnectorConnectionSetupEnabled(connection);
|
||||
const unavailableServices: string[] = [];
|
||||
try {
|
||||
assertSupportedConnection(connection);
|
||||
@@ -7828,6 +7832,7 @@ export function toolAccessService(
|
||||
): Promise<ToolCatalogRefreshResult> {
|
||||
const connection = await getConnectionRow(connectionId);
|
||||
if (connection.connectionPurpose === "ai") throw unprocessable("AI connections do not have a tool catalog");
|
||||
await assertConnectorConnectionSetupEnabled(connection);
|
||||
const refreshedAt = now();
|
||||
const unavailableServices: string[] = [];
|
||||
let descriptors: McpToolDescriptor[];
|
||||
@@ -12440,12 +12445,31 @@ export function toolAccessService(
|
||||
}
|
||||
|
||||
async function assertExperimentalConnectorSetupEnabled(provider: unknown, existing = false) {
|
||||
if (!existing && isMemoryConnectorId(provider)
|
||||
&& !(await instanceSettingsService(db).getExperimental()).enableMemoryConnectors) {
|
||||
const app = typeof provider === "string" ? getConnectableAppDefinition(provider) : null;
|
||||
if (!app?.experimentalFeatureKey && (existing || !isMemoryConnectorId(provider))) return;
|
||||
const settings = await instanceSettingsService(db).getExperimental();
|
||||
if (app && !isConnectorFeatureEnabled(app, settings)) {
|
||||
throw forbidden(`${app.name} is unavailable on this instance`, { code: "connector_disabled" });
|
||||
}
|
||||
if (!existing && isMemoryConnectorId(provider) && !settings.enableMemoryConnectors) {
|
||||
throw forbidden("Enable memory connectors in Settings → Experimental to set up this connection", { code: "memory_connectors_disabled" });
|
||||
}
|
||||
}
|
||||
|
||||
async function assertConnectorConnectionSetupEnabled(connection: { config?: Record<string, unknown>; transportConfig?: Record<string, unknown>; applicationId?: string; companyId?: string; status?: string }, applicationKey?: unknown) {
|
||||
let resolvedApplicationKey = applicationKey;
|
||||
if (resolvedApplicationKey == null && connection.applicationId && connection.companyId) {
|
||||
const [application] = await db.select({ applicationKey: toolApplications.applicationKey })
|
||||
.from(toolApplications).where(and(eq(toolApplications.id, connection.applicationId),
|
||||
eq(toolApplications.companyId, connection.companyId))).limit(1);
|
||||
resolvedApplicationKey = application?.applicationKey;
|
||||
}
|
||||
const marker = connection.config?.sourceTemplateKey ?? connection.transportConfig?.sourceTemplateKey;
|
||||
const app = resolvedApplicationKey != null ? getAppDefinitionForApplicationKey(resolvedApplicationKey)
|
||||
: typeof marker === "string" ? getConnectableAppDefinition(marker) : null;
|
||||
if (app) await assertExperimentalConnectorSetupEnabled(app.slug, connection.status !== "draft");
|
||||
}
|
||||
|
||||
async function connectGalleryApp(
|
||||
companyId: string,
|
||||
input: ConnectToolApp,
|
||||
@@ -12565,6 +12589,7 @@ export function toolAccessService(
|
||||
}
|
||||
}
|
||||
|
||||
await assertConnectorConnectionSetupEnabled(requestedResumeConnection ?? {}, existingApplication?.applicationKey);
|
||||
const requestedName =
|
||||
input.name ??
|
||||
existingApplication?.name ??
|
||||
@@ -12769,7 +12794,7 @@ export function toolAccessService(
|
||||
}
|
||||
}
|
||||
const requestedGrantKind =
|
||||
retainedGrantKind ?? input.grantKind ?? "organization";
|
||||
retainedGrantKind ?? input.grantKind ?? (method?.grantKinds?.length === 1 ? method.grantKinds[0]! : "organization");
|
||||
if (method?.grantKinds && !method.grantKinds.includes(requestedGrantKind)) {
|
||||
throw badRequest(
|
||||
`${galleryEntry?.name ?? "This app"} supports only ${method.grantKinds.join(" or ")} credentials`,
|
||||
@@ -14066,6 +14091,7 @@ export function toolAccessService(
|
||||
actor?: ActorInfo,
|
||||
): Promise<FinishToolAppResult> {
|
||||
const connection = await getConnectionRow(connectionId, companyId);
|
||||
await assertConnectorConnectionSetupEnabled(connection);
|
||||
if (connection.status === "archived")
|
||||
throw conflict("Archived app connections cannot be finished");
|
||||
if (connection.config.mcpPreserveAccess === true && isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey)) {
|
||||
@@ -14561,6 +14587,7 @@ export function toolAccessService(
|
||||
): Promise<ToolConnectionHealthCheckResult> {
|
||||
const connection = await getConnectionRow(connectionId, companyId);
|
||||
assertSupportedConnection(connection);
|
||||
await assertConnectorConnectionSetupEnabled(connection);
|
||||
await assertExperimentalConnectorSetupEnabled(connection.config.sourceTemplateKey, connection.status !== "draft");
|
||||
if (connection.status === "archived")
|
||||
throw conflict("Archived app connections cannot be reconnected");
|
||||
@@ -14745,6 +14772,7 @@ export function toolAccessService(
|
||||
): Promise<ToolOAuthStartResult> {
|
||||
let connection = await getConnectionRow(connectionId, companyId);
|
||||
assertSupportedConnection(connection);
|
||||
await assertConnectorConnectionSetupEnabled(connection);
|
||||
await assertExperimentalConnectorSetupEnabled(connection.config.sourceTemplateKey, connection.status !== "draft");
|
||||
if (connection.status === "archived")
|
||||
throw conflict("Archived app connections cannot start sign in");
|
||||
@@ -16371,6 +16399,7 @@ export function toolAccessService(
|
||||
status: connection.status,
|
||||
enabled: connection.enabled,
|
||||
};
|
||||
await assertConnectorConnectionSetupEnabled(connection);
|
||||
const sourceTemplateKey =
|
||||
typeof connection.config.sourceTemplateKey === "string"
|
||||
? connection.config.sourceTemplateKey
|
||||
@@ -18474,6 +18503,7 @@ export function toolAccessService(
|
||||
const config = normalizeGoogleSheetsConnectionConfig(
|
||||
input.config ?? input.transportConfig ?? {},
|
||||
);
|
||||
await assertConnectorConnectionSetupEnabled({ config, applicationId, companyId });
|
||||
// Validate company-scoped references before touching a caller-supplied
|
||||
// network endpoint. Besides failing fast, this keeps cross-company
|
||||
// authorization errors from being masked by DNS or SSRF validation.
|
||||
@@ -18489,6 +18519,7 @@ export function toolAccessService(
|
||||
if (applicationId) {
|
||||
const app = await assertApplication(companyId, applicationId);
|
||||
applicationNamespace = app.applicationKey ?? app.name;
|
||||
await assertConnectorConnectionSetupEnabled({ config }, applicationNamespace);
|
||||
if (
|
||||
(transport === "mcp_remote" && app.type !== "mcp_http") ||
|
||||
(transport === "local_stdio" && app.type !== "mcp_stdio")
|
||||
|
||||
@@ -29,6 +29,8 @@ import { emitConnectionInvoked } from "./connector-telemetry.js";
|
||||
import { resolveManagedGitHubIdentitySelection } from "./git-credentials.js";
|
||||
import { extractRemoteMcpPending } from "./remote-mcp-pending.js";
|
||||
import { logger } from "../middleware/logger.js";
|
||||
import { getAppDefinitionForApplicationKey, isConnectorFeatureEnabled } from "@paperclipai/shared";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import { spawn } from "node:child_process";
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import { isDeepStrictEqual } from "node:util";
|
||||
@@ -1437,8 +1439,11 @@ export function createToolGatewayService(
|
||||
return connectionRow ? [{ catalogEntry, ...connectionRow }] : [];
|
||||
});
|
||||
|
||||
const featureSettings = connectionRows.some(({ application }) => getAppDefinitionForApplicationKey(application.applicationKey)?.experimentalFeatureKey)
|
||||
? await instanceSettingsService(db).getExperimental() : undefined;
|
||||
const eligibleRows = rows.filter(
|
||||
({ catalogEntry, connection, application }) =>
|
||||
(!featureSettings || isConnectorFeatureEnabled(getAppDefinitionForApplicationKey(application.applicationKey), featureSettings)) &&
|
||||
!isRetiredComposioConnection(connection) &&
|
||||
!(isDaytonaConnection(connection) && !isCurrentDaytonaCatalogEntry(catalogEntry)) &&
|
||||
!(isRailwayEndpoint(connection.config.url) && (isRailwayToolBlocked(catalogEntry.toolName) || (normalizeRailwayToolName(catalogEntry.toolName).startsWith(RAILWAY_TOOL_PREFIX) && connection.config.railwayApiStatus !== "available"))) &&
|
||||
@@ -5340,15 +5345,23 @@ export function createToolGatewayService(
|
||||
}
|
||||
}
|
||||
|
||||
async function assertApplicationFeatureAvailable(applicationKey: unknown) {
|
||||
const app = getAppDefinitionForApplicationKey(applicationKey);
|
||||
if (app?.experimentalFeatureKey && !isConnectorFeatureEnabled(app, await instanceSettingsService(db).getExperimental())) {
|
||||
throw new ToolGatewayHttpError(403, "This connector is unavailable on this instance.", "connector_unavailable");
|
||||
}
|
||||
}
|
||||
|
||||
async function fullyAssignedMcpConnections(session: ToolGatewaySession) {
|
||||
if (!session.gatewayProfileId) return [];
|
||||
return db
|
||||
.select({ connection: toolConnections })
|
||||
const rows = await db
|
||||
.select({ connection: toolConnections, applicationKey: toolApplications.applicationKey })
|
||||
.from(toolProfileEntries)
|
||||
.innerJoin(
|
||||
toolConnections,
|
||||
eq(toolProfileEntries.connectionId, toolConnections.id),
|
||||
)
|
||||
.innerJoin(toolApplications, eq(toolConnections.applicationId, toolApplications.id))
|
||||
.where(
|
||||
and(
|
||||
eq(toolProfileEntries.companyId, session.companyId),
|
||||
@@ -5356,12 +5369,16 @@ export function createToolGatewayService(
|
||||
eq(toolProfileEntries.selectorType, "connection"),
|
||||
eq(toolProfileEntries.effect, "include"),
|
||||
eq(toolConnections.companyId, session.companyId),
|
||||
eq(toolApplications.companyId, session.companyId),
|
||||
eq(toolConnections.enabled, true),
|
||||
eq(toolConnections.status, "active"),
|
||||
inArray(toolConnections.transport, ["mcp_remote", "local_stdio"]),
|
||||
),
|
||||
)
|
||||
.then((rows) => rows.map((row) => row.connection));
|
||||
);
|
||||
const settings = rows.some(row => getAppDefinitionForApplicationKey(row.applicationKey)?.experimentalFeatureKey)
|
||||
? await instanceSettingsService(db).getExperimental() : undefined;
|
||||
return rows.filter(row => !settings || isConnectorFeatureEnabled(getAppDefinitionForApplicationKey(row.applicationKey), settings))
|
||||
.map(row => row.connection);
|
||||
}
|
||||
|
||||
async function callRemoteConnectionProtocol(input: {
|
||||
@@ -5472,6 +5489,10 @@ export function createToolGatewayService(
|
||||
params?: Record<string, unknown>;
|
||||
callerHeaders?: Record<string, string | string[] | undefined>;
|
||||
}): Promise<unknown> {
|
||||
const [application] = await db.select({ applicationKey: toolApplications.applicationKey }).from(toolApplications)
|
||||
.where(and(eq(toolApplications.id, input.connection.applicationId), eq(toolApplications.companyId, input.session.companyId))).limit(1);
|
||||
if (!application) throw new ToolGatewayHttpError(404, "MCP connection not found", "connection_not_found");
|
||||
await assertApplicationFeatureAvailable(application.applicationKey);
|
||||
if (input.connection.transport === "mcp_remote") {
|
||||
return callRemoteConnectionProtocol({
|
||||
...input,
|
||||
@@ -6039,6 +6060,7 @@ export function createToolGatewayService(
|
||||
session,
|
||||
tool,
|
||||
);
|
||||
await assertApplicationFeatureAvailable(tool.applicationKey);
|
||||
// Recheck immediately before dispatch, including previously approved calls
|
||||
// and connections whose stored grant/catalog predates scope reduction.
|
||||
assertGoogleChatToolArgumentsSupported(connection, entry.toolName, parameters);
|
||||
|
||||
Reference in new issue
Block a user