mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-03 03:36:57 +01:00
feat(apps): add experimental MCP aggregator connectors (#13755)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Its tool gateway applies company access rules and approval controls to connected apps. > - MCP aggregators expose many apps through one provider endpoint. > - Each aggregator needs its own credential, catalog, grants, and lifecycle in Paperclip. > - This pull request adds independent Zapier, Arcade, Composio Connect, and Executor setup with a common Access → Connect layout. > - A default-off MCP aggregators flag lets operators opt in while we complete provider acceptance tests. > - Agents use the normal Paperclip permissions, Test screen, and gateway after setup. ## Linked Issues or Issue Description **Subsystem affected** Apps, connection setup, shared contracts, and the remote MCP gateway. **Problem or motivation** Aggregator endpoints need clear provider setup and correct MCP sessions. Generic setup does not explain each provider's authentication or broad execution tools. Provider approval must preserve the original execution instead of replaying a write. **Proposed solution** Add four separate connectors behind Settings → Experimental → MCP aggregators. Start with human and agent access, then connect the endpoint and read its tools. Enable tools by default. Use the existing Permissions and Test screens after setup. Keep legacy Composio API-key and child connections intact. **Alternatives considered** A shared connection for all providers would mix credentials and access rules. Separate provider-specific permission and test screens would duplicate existing controls. Vercel Connect is outside this change. **Roadmap alignment** Extends the existing MCP Tool Gateway & Apps capability and the Connected Apps roadmap area. This work was requested and reviewed by the maintainer. Related work: #11894, #12630, #12632, #12634, and #12906 concern the legacy Composio broker. #13102 also covers remote MCP pagination. This change preserves the broker path and adds initialized sessions, response matching, and provider resume handling alongside pagination. ## What Changed - Add branded setup and interactive Storybooks for Zapier, Arcade, Composio Connect, and Executor. Use the existing access controls and normal action tests. Do not request a connection name or action choices during setup. - Add the default-off `enableMcpAggregators` flag to settings, managed feature metadata, the catalog, and setup guards. Hidden connections keep running. Legacy Composio connections remain unchanged. - Reuse the vault, grants, policy, and catalog models. Support OAuth discovery, bearer tokens, custom headers, and credential-bearing URLs. Add no database tables or migrations. - Initialize and retain Streamable HTTP sessions by connection and effective credentials. Read paginated catalogs and match streaming responses to request IDs. - Classify unfamiliar aggregator tools as writes despite upstream read-only hints; only exact reviewed read capabilities enter the read-only allowlist. Legacy Composio child behavior is preserved. - Preserve provider authorization links and execution IDs. Support Executor approve/resume, decline, and cancel without automatic replay of uncertain writes. - Preserve Off and Ask first choices during refresh and reconnect. Allow new tools and retire removed tools. Keep agent access updates atomic and preserve an empty agent selection. - Document connector UX rules, provider branding sources, and live acceptance results. - Stabilize the existing Sentry release fixture after its repeated CI failure by reusing one module mock; production Sentry behavior is unchanged. ## Verification - Final head `d11781970`: [CI run](https://github.com/paperclipai/paperclip/actions/runs/35633534900) passed, including broad typecheck, test shards, build, and E2E. All 54 checks pass; 2 optional checks are skipped. Greptile is 5/5, Security Scan passes, and all review threads are resolved. - Passed 27 focused connector Vitest checks and 18 connector-only Storybook browser checks before the flag change. All 85 stories rendered at desktop and narrow widths. - Passed 5 connector lifecycle/server checks and 7 selected flag checks after adding the flag. The latter cover settings, managed defaults, cached catalog visibility, and all four setup routes. - Review fixes passed 13 risk/handoff/lifecycle checks, dedicated session-expiration and transport regressions, 13 selected connector/gateway CI cases, and 10 selected setup/reconnect UI cases. A real Composio connection-list call also succeeded through the refreshed UI on `9ab115f71`. - UI and server TypeScript checks passed. UI build, Storybook build, token gates, and diff whitespace checks passed during implementation. - Real browser and real Paperclip agent tests passed for Arcade, Composio, and Executor. Tested action permissions, denied agent access, reconnect, disconnect, and isolation. Tested Arcade catalog additions/removal and Executor provider approve/resume, decline, and cancel. - Zapier live acceptance is incomplete. Its dedicated provider server is configured, but its credential-copy dialog returned an empty clipboard through browser automation. No live Zapier action is claimed. - The three isolated Sentry release cases pass after the CI fixture fix. - Local verification is deliberately narrow at the maintainer's request. The full local suite, recursive typecheck, and repository-wide build were not run. CI provides the broader checks. ## Risks - Shared MCP transport changes affect other remote MCP servers. Protocol fixtures cover initialized sessions, streaming response matching, pagination, and isolation. - Broad execution tools remain broad permissions. The provider governs actions inside those tools. - Provider handoff links are retained briefly in memory. After a server restart, a one-time link may require reopening the provider dashboard. Paperclip does not replay the original call. - Zapier remains unproven live. Custom-header imports and self-hosted endpoints have fixture coverage rather than a separate live account for every variant. - Turning the experimental flag off hides setup; it does not revoke existing credentials or stop existing connections. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools, shell execution, and browser automation. The exact runtime model ID and context-window size are not exposed in this session. A separate Anthropic-backed Paperclip agent performed live gateway acceptance tasks. ## 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
3790ca2f13
commit
e8c8ba3c19
74 files changed
+2988
-240
No files matched your search
@@ -1,4 +1,5 @@
|
||||
import { connectionPurposeTransportSchema } from "@paperclipai/shared";
|
||||
import { isRemoteMcpConnectorMethod, connectionPurposeTransportSchema } from "@paperclipai/shared";
|
||||
import { instanceSettingsService } from "./instance-settings.js";
|
||||
import { syncConnectionCredentialBindings } from "./connection-credential-bindings.js";
|
||||
import { canBrowseProjectRepositoryGrant, mergeProjectRepository } from "./project-repositories.js";
|
||||
import { captureRunIdentity } from "./run-identity.js";
|
||||
@@ -186,6 +187,10 @@ import { logger } from "../middleware/logger.js";
|
||||
import { logActivity } from "./activity-log.js";
|
||||
import {
|
||||
initializeMcpHttpSession,
|
||||
McpHttpInitializationError,
|
||||
getMcpHttpSession,
|
||||
forgetMcpHttpSessions,
|
||||
readMcpHttpResponse,
|
||||
mcpHttpRequestHeaders,
|
||||
parseMcpHttpResponseBody,
|
||||
} from "./mcp-http.js";
|
||||
@@ -2316,6 +2321,17 @@ function normalizedProviderToolName(toolName: string): string {
|
||||
.replace(/[:._-]+/g, "-");
|
||||
}
|
||||
|
||||
// Aggregators can add arbitrarily powerful tools without changing their MCP
|
||||
// endpoint. Only these reviewed, exact capabilities are read-only. Unknown or
|
||||
// renamed actions remain enabled by the usual access rules, but have write risk.
|
||||
// Legacy Composio child connections do not use these gallery template keys.
|
||||
const AGGREGATOR_READ_TOOLS = new Map<string, ReadonlySet<string>>([
|
||||
["executor", new Set(["skills"])],
|
||||
["composio", new Set(["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_GET_TOOL_SCHEMAS", "COMPOSIO_SEARCH_SKILLS", "COMPOSIO_USE_SKILL"])],
|
||||
["arcade", new Set(["Github.GetRepository"])],
|
||||
["zapier", new Set()],
|
||||
]);
|
||||
|
||||
export function classifyRisk(
|
||||
tool: McpToolDescriptor,
|
||||
sourceTemplateKey?: string | null,
|
||||
@@ -2324,6 +2340,12 @@ export function classifyRisk(
|
||||
if (annotations.destructiveHint === true || annotations.destructive === true)
|
||||
return "destructive";
|
||||
const normalizedToolName = normalizedProviderToolName(tool.name);
|
||||
const reviewedReads = AGGREGATOR_READ_TOOLS.get(sourceTemplateKey ?? "");
|
||||
if (reviewedReads) {
|
||||
if (verbMatches(tool.name, "delete|remove|destroy|unpublish")) return "destructive";
|
||||
if (annotations.readOnlyHint === false || annotations.writeHint === true) return "write";
|
||||
return reviewedReads.has(tool.name) ? "read" : "write";
|
||||
}
|
||||
if (sourceTemplateKey === "railway") {
|
||||
const reviewed = railwayRisk(normalizedToolName);
|
||||
return reviewed === "read" && (annotations.readOnlyHint === false || annotations.writeHint === true) ? "write" : reviewed;
|
||||
@@ -6068,6 +6090,7 @@ export function toolAccessService(
|
||||
removalOptions: { confirmComposioChildren?: boolean } = {},
|
||||
): Promise<ToolConnectionRemovalResult> {
|
||||
const connection = await getConnectionRow(connectionId, companyId);
|
||||
forgetMcpHttpSessions(connection.id);
|
||||
const now = new Date();
|
||||
const binding = actorBinding(actor);
|
||||
|
||||
@@ -6765,31 +6788,26 @@ export function toolAccessService(
|
||||
// Pinned to the address the guard approved: `config.url` is operator-supplied,
|
||||
// so a second DNS resolution here would reopen the rebinding window that
|
||||
// PAP-17098 closed for the OAuth endpoints.
|
||||
const listRequestBody = JSON.stringify({
|
||||
jsonrpc: "2.0",
|
||||
id: "paperclip-catalog-refresh",
|
||||
method: "tools/list",
|
||||
params: {},
|
||||
});
|
||||
const sendRemote = (init: RequestInit) =>
|
||||
requestRemoteHttpEndpoint(new URL(endpoint), init);
|
||||
const sendToolsList = (requestHeaders: Record<string, string>) =>
|
||||
sendRemote({
|
||||
method: "POST",
|
||||
// MCP Streamable HTTP requires advertising that we accept both a JSON body
|
||||
// and an SSE stream; spec-compliant servers 406 without it (see mcp-http.ts).
|
||||
headers: mcpHttpRequestHeaders(requestHeaders),
|
||||
body: listRequestBody,
|
||||
});
|
||||
let listRequestId = "paperclip-catalog-refresh";
|
||||
let sessionHeaders = headers;
|
||||
const sendRemote = (init: RequestInit) => requestRemoteHttpEndpoint(new URL(endpoint), init);
|
||||
const sendToolsList = (requestHeaders: Record<string, string>, cursor?: string) => {
|
||||
sessionHeaders = requestHeaders;
|
||||
return sendRemote({ method: "POST", headers: mcpHttpRequestHeaders(requestHeaders),
|
||||
body: JSON.stringify({ jsonrpc: "2.0", id: listRequestId, method: "tools/list", params: cursor ? { cursor } : {} }) });
|
||||
};
|
||||
let usedInitializedSession = connection.config.mcpSessionRequired === true;
|
||||
let response: Response;
|
||||
if (usedInitializedSession) {
|
||||
const sessionHeaders = await initializeMcpHttpSession({
|
||||
send: sendRemote,
|
||||
headers,
|
||||
requestId: "paperclip-catalog-refresh",
|
||||
});
|
||||
response = await sendToolsList(sessionHeaders);
|
||||
try {
|
||||
sessionHeaders = await getMcpHttpSession({ send: sendRemote, headers,
|
||||
scope: `${connection.id}:catalog:${actor?.actorType}:${actor?.actorId}:${endpoint}`,
|
||||
requestId: listRequestId });
|
||||
response = await sendToolsList(sessionHeaders);
|
||||
} catch (error) {
|
||||
if (!(error instanceof McpHttpInitializationError) || !error.response) throw error;
|
||||
response = error.response;
|
||||
}
|
||||
} else {
|
||||
response = await sendToolsList(headers);
|
||||
// `tools/list` is read-only, so a 400 can safely be retried after the MCP
|
||||
@@ -6810,6 +6828,17 @@ export function toolAccessService(
|
||||
}
|
||||
}
|
||||
}
|
||||
if (response.status === 404 && new Headers(sessionHeaders).has("mcp-session-id")) {
|
||||
// MCP uses 404 for an expired server session. Discovery is read-only, so
|
||||
// discard the stale session and retry it once with a new handshake.
|
||||
forgetMcpHttpSessions(connection.id);
|
||||
await response.body?.cancel().catch(() => undefined);
|
||||
sessionHeaders = await getMcpHttpSession({ send: sendRemote, headers,
|
||||
scope: `${connection.id}:catalog:${actor?.actorType}:${actor?.actorId}:${endpoint}`,
|
||||
requestId: listRequestId });
|
||||
response = await sendToolsList(sessionHeaders);
|
||||
if (response.status === 404) forgetMcpHttpSessions(connection.id);
|
||||
}
|
||||
if (
|
||||
usedInitializedSession &&
|
||||
connection.config.mcpSessionRequired !== true
|
||||
@@ -6833,6 +6862,8 @@ export function toolAccessService(
|
||||
const refreshed = await composioSessions.ensureSession(connection.id, {
|
||||
force: true,
|
||||
});
|
||||
listRequestId = "paperclip-catalog-refresh-retry";
|
||||
sessionHeaders = refreshed.headers;
|
||||
response = await requestRemoteHttpEndpoint(new URL(refreshed.url), {
|
||||
method: "POST",
|
||||
headers: mcpHttpRequestHeaders(refreshed.headers),
|
||||
@@ -6954,20 +6985,23 @@ export function toolAccessService(
|
||||
status: response.status,
|
||||
});
|
||||
}
|
||||
const payload = parseMcpHttpResponseBody(
|
||||
await response.text(),
|
||||
response.headers.get("content-type"),
|
||||
);
|
||||
const result = asRecord(asRecord(payload).result);
|
||||
const payloadTools = asRecord(payload).tools;
|
||||
const tools: unknown[] = Array.isArray(result.tools)
|
||||
? result.tools
|
||||
: Array.isArray(payloadTools)
|
||||
? payloadTools
|
||||
: [];
|
||||
const descriptors = tools
|
||||
.map((tool) => normalizeToolDescriptor(tool))
|
||||
.filter((tool): tool is McpToolDescriptor => Boolean(tool));
|
||||
const descriptors: McpToolDescriptor[] = [];
|
||||
const seenCursors = new Set<string>();
|
||||
for (let page = 0; ; page += 1) {
|
||||
const payload = await readMcpHttpResponse(response, listRequestId);
|
||||
const record = asRecord(payload);
|
||||
if (record.error) throw new HttpError(502, "Remote MCP tool discovery failed", { code: "mcp_catalog_error" });
|
||||
const result = asRecord(record.result);
|
||||
if (!Array.isArray(result.tools)) throw new HttpError(502, "Remote MCP returned an invalid tool catalog", { code: "mcp_catalog_invalid" });
|
||||
descriptors.push(...result.tools.map((tool) => normalizeToolDescriptor(tool)).filter((tool): tool is McpToolDescriptor => Boolean(tool)));
|
||||
const cursor = typeof result.nextCursor === "string" ? result.nextCursor : null;
|
||||
if (!cursor) break;
|
||||
if (seenCursors.has(cursor) || page >= 99 || descriptors.length > 20_000) throw new HttpError(502, "Remote MCP tool catalog pagination did not finish", { code: "mcp_catalog_pagination" });
|
||||
seenCursors.add(cursor);
|
||||
listRequestId = `paperclip-catalog-refresh-${page + 1}`;
|
||||
response = await sendToolsList(sessionHeaders, cursor);
|
||||
if (!response.ok) throw new HttpError(502, "Remote MCP catalog page could not be read", { status: response.status });
|
||||
}
|
||||
if (!isRailwayConnection(connection)) return descriptors;
|
||||
if (descriptors.some((tool) => normalizeRailwayToolName(tool.name).startsWith(RAILWAY_TOOL_PREFIX))) {
|
||||
throw unprocessable("Railway advertised a reserved Paperclip action name. Refresh is blocked pending review.", { code: "railway_tool_name_collision" });
|
||||
@@ -7015,7 +7049,7 @@ export function toolAccessService(
|
||||
connection: typeof toolConnections.$inferSelect,
|
||||
): boolean {
|
||||
return (
|
||||
asRecord(connection.config).sourceTemplateKey === COMPOSIO_GALLERY_KEY
|
||||
asRecord(connection.config).sourceTemplateKey === COMPOSIO_GALLERY_KEY && connection.transport === "rest_api"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7772,6 +7806,13 @@ export function toolAccessService(
|
||||
const existingByName = new Map(
|
||||
existingRows.map((entry) => [entry.toolName, entry]),
|
||||
);
|
||||
if (isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey)) {
|
||||
const discoveredNames = new Set(descriptors.map((descriptor) => descriptor.name));
|
||||
const removedIds = existingRows.filter((entry) => !discoveredNames.has(entry.toolName) && entry.status !== "disabled").map((entry) => entry.id);
|
||||
if (removedIds.length) await db.update(toolCatalogEntries)
|
||||
.set({ status: "disabled", quarantineReason: "mcp_tool_removed", updatedAt: refreshedAt })
|
||||
.where(and(eq(toolCatalogEntries.companyId, connection.companyId), eq(toolCatalogEntries.connectionId, connection.id), inArray(toolCatalogEntries.id, removedIds)));
|
||||
}
|
||||
// Retired native actions are absent from discovery, but old catalog rows
|
||||
// still need to show as disabled. Gateway denial also applies before refresh.
|
||||
const blockedRailwayEntryIds = isRailwayEndpoint(connection.config.url)
|
||||
@@ -7835,7 +7876,7 @@ export function toolAccessService(
|
||||
? "disabled"
|
||||
: shouldQuarantine
|
||||
? "quarantined"
|
||||
: existing?.status === "disabled"
|
||||
: existing?.status === "disabled" && existing.quarantineReason !== "mcp_tool_removed"
|
||||
? "disabled"
|
||||
: quarantineOnRefresh && existing?.status === "quarantined"
|
||||
? "quarantined"
|
||||
@@ -7950,10 +7991,12 @@ export function toolAccessService(
|
||||
const activeEntries = updatedEntries.filter(
|
||||
(entry) => entry.status === "active",
|
||||
);
|
||||
if (!refreshOptions.skipDefaultProfileSync) {
|
||||
const preserveMcpAccess = connection.config.mcpPreserveAccess === true
|
||||
&& isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey);
|
||||
if (!refreshOptions.skipDefaultProfileSync || preserveMcpAccess) {
|
||||
await enableCatalogEntriesByDefault({
|
||||
connection: updatedConnection,
|
||||
newCatalogEntryIds: refreshOptions.enableAllByDefault
|
||||
newCatalogEntryIds: refreshOptions.enableAllByDefault && !isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey)
|
||||
? activeEntries.map((entry) => entry.id)
|
||||
: activeEntries
|
||||
.filter((entry) => {
|
||||
@@ -7962,7 +8005,7 @@ export function toolAccessService(
|
||||
})
|
||||
.map((entry) => entry.id),
|
||||
activeCatalogEntryIds: activeEntries.map((entry) => entry.id),
|
||||
restoreDraftDefaults: refreshOptions.restoreDraftDefaults,
|
||||
restoreDraftDefaults: refreshOptions.restoreDraftDefaults || preserveMcpAccess,
|
||||
actor,
|
||||
});
|
||||
}
|
||||
@@ -12231,6 +12274,15 @@ export function toolAccessService(
|
||||
return `${base.slice(0, 151).trimEnd()} (${randomUUID().slice(0, 6)})`;
|
||||
}
|
||||
|
||||
async function assertMcpAggregatorSetupEnabled(provider: unknown, method: unknown) {
|
||||
if (isRemoteMcpConnectorMethod(provider, method)
|
||||
&& !(await instanceSettingsService(db).getExperimental()).enableMcpAggregators) {
|
||||
throw forbidden("Enable MCP aggregators in Settings → Experimental to set up this connection", {
|
||||
code: "mcp_aggregators_disabled",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function connectGalleryApp(
|
||||
companyId: string,
|
||||
input: ConnectToolApp,
|
||||
@@ -12377,18 +12429,20 @@ export function toolAccessService(
|
||||
const method = galleryEntry
|
||||
? connectionMethodFor(galleryEntry, inferredMethodKey)
|
||||
: null;
|
||||
const remoteMcpConnector = isRemoteMcpConnectorMethod(galleryEntry?.slug, method?.key);
|
||||
await assertMcpAggregatorSetupEnabled(galleryEntry?.slug, method?.key);
|
||||
if (galleryEntry && input.link) {
|
||||
const acceptsProviderGeneratedUrl =
|
||||
method?.transport === "mcp_remote" &&
|
||||
method.auth === "none" &&
|
||||
!method.defaults?.serverUrl &&
|
||||
!method.defaults?.serverUrlTemplate;
|
||||
if (!acceptsProviderGeneratedUrl) {
|
||||
if (!acceptsProviderGeneratedUrl && !remoteMcpConnector) {
|
||||
throw badRequest(
|
||||
`${galleryEntry.name} does not accept a provider-generated connection URL`,
|
||||
);
|
||||
}
|
||||
if (!getAppDefinitionForUrl(input.link, [galleryEntry])) {
|
||||
if (!(remoteMcpConnector && galleryEntry.slug === "executor") && !getAppDefinitionForUrl(input.link, [galleryEntry])) {
|
||||
throw badRequest(
|
||||
`That connection URL does not belong to ${galleryEntry.name}`,
|
||||
);
|
||||
@@ -12699,6 +12753,7 @@ export function toolAccessService(
|
||||
transport === "mcp_remote"
|
||||
? {
|
||||
url:
|
||||
(remoteMcpConnector ? remoteUrlCredential?.publicUrl : undefined) ??
|
||||
normalizedMethodConfig?.url ??
|
||||
method?.defaults?.serverUrl ??
|
||||
remoteUrlCredential?.publicUrl ??
|
||||
@@ -12716,6 +12771,11 @@ export function toolAccessService(
|
||||
// the wizard projects the app's action defaults into policies at
|
||||
// finish time instead of using catalog quarantine as access state.
|
||||
quarantineNewEntries: galleryEntry.slug === "railway",
|
||||
...(remoteMcpConnector ? {
|
||||
mcpSessionRequired: true,
|
||||
mcpAuthMode: input.authMode ?? "auto",
|
||||
mcpPreserveAccess: Boolean(retainedConnection && (retainedConnection.status === "active" || asRecord(retainedConnection.config).mcpPreserveAccess === true)),
|
||||
} : {}),
|
||||
...(galleryEntry.slug === "posthog" ? { safeDefault: true } : {}),
|
||||
}
|
||||
: { ...baseConfig, quarantineNewEntries: false, unverifiedServer: true };
|
||||
@@ -12734,7 +12794,7 @@ export function toolAccessService(
|
||||
config.quarantineNewEntries = true;
|
||||
}
|
||||
const acceptsCustomerOAuthClient =
|
||||
method?.auth === "oauth" && method.ownershipModes.includes("customer");
|
||||
remoteMcpConnector || (method?.auth === "oauth" && method.ownershipModes.includes("customer"));
|
||||
if (galleryEntry && input.oauthClient && !acceptsCustomerOAuthClient) {
|
||||
throw badRequest(
|
||||
`${galleryEntry.name} does not accept customer-owned OAuth client credentials`,
|
||||
@@ -12784,7 +12844,7 @@ export function toolAccessService(
|
||||
// operator supplied and is upgraded to `oauth` when discovery proves the
|
||||
// endpoint needs sign-in (see `remoteTools` and `startOAuth`).
|
||||
const genericAuthKind: ToolConnectionAuthKind =
|
||||
method?.auth ??
|
||||
(remoteMcpConnector ? undefined : method?.auth) ??
|
||||
(input.authMode === "oauth" || input.oauthClient
|
||||
? "oauth"
|
||||
: input.authMode === "bearer" || input.authMode === "custom_headers"
|
||||
@@ -12834,7 +12894,8 @@ export function toolAccessService(
|
||||
previousGrantKind === requestedGrantKind &&
|
||||
galleryEntry &&
|
||||
retainedSource === galleryEntry.slug &&
|
||||
retainedMethodKey === method?.key,
|
||||
retainedMethodKey === method?.key &&
|
||||
(!remoteMcpConnector || (baseConfig.url === retainedConfig.url && genericAuthKind === retainedConnection.authKind)),
|
||||
);
|
||||
const retainedCredentialSecretRefs = canRetainCredentialMaterial
|
||||
? (retainedPersonalIdentity?.grant?.credentialSecretRefs ??
|
||||
@@ -12866,9 +12927,9 @@ export function toolAccessService(
|
||||
const credentialFields =
|
||||
credentialSource === "vercel_connect"
|
||||
? []
|
||||
: galleryEntry
|
||||
: galleryEntry && !remoteMcpConnector
|
||||
? credentialFieldsFor(galleryEntry, method?.key)
|
||||
: linkCredentialFields(credentialValues);
|
||||
: linkCredentialFields({ ...Object.fromEntries(retainedCredentialSecretRefs.filter((ref) => ref.configPath.startsWith("headers.") || ref.configPath === "credentials.authorization").map((ref) => [ref.configPath, "retained"])), ...credentialValues });
|
||||
for (const field of credentialFields) {
|
||||
const value = credentialValues[field.configPath];
|
||||
const retainedSecretRef = retainedCredentialSecretRefs.find(
|
||||
@@ -12923,6 +12984,13 @@ export function toolAccessService(
|
||||
}
|
||||
}
|
||||
|
||||
if (!remoteUrlCredential?.secretUrl && canRetainCredentialMaterial && baseConfig.url === retainedConfig.url) {
|
||||
const retainedUrl = retainedCredentialSecretRefs.find((ref) => ref.configPath === REMOTE_URL_SECRET_CONFIG_PATH);
|
||||
if (retainedUrl) {
|
||||
credentialSecretRefs.push(retainedUrl);
|
||||
credentialRefs.push({ name: REMOTE_URL_SECRET_CONFIG_PATH, secretId: retainedUrl.secretId, version: retainedUrl.versionSelector ?? "latest", placement: "url", key: "url", prefix: null });
|
||||
}
|
||||
}
|
||||
if (remoteUrlCredential?.secretUrl) {
|
||||
const secret = await secrets.create(
|
||||
companyId,
|
||||
@@ -13072,6 +13140,7 @@ export function toolAccessService(
|
||||
const connectionCredentialSecretRefs =
|
||||
personalIdentityUserId || dedicatedAgentId ? [] : credentialSecretRefs;
|
||||
if (revivedConnectionPrevious) {
|
||||
forgetMcpHttpSessions(revivedConnectionPrevious.id);
|
||||
[connectionRow] = await db
|
||||
.update(toolConnections)
|
||||
.set({
|
||||
@@ -13292,6 +13361,10 @@ export function toolAccessService(
|
||||
);
|
||||
await ensureRuntimeSlot(connectionRow);
|
||||
|
||||
if (input.saveDraft && remoteMcpConnector) {
|
||||
return { connectionId: connectionRow.id, application: toApplication(applicationRow), connection: toConnection(connectionRow),
|
||||
catalog: [], actions: { readOnly: [], canMakeChanges: [] }, suggestedDefaults: { access: "all_agents", askFirstRiskLevels: [] } };
|
||||
}
|
||||
if (galleryEntry && method?.auth === "oauth") {
|
||||
const suggestedDefaults = recommendedDefaultsForApp(
|
||||
galleryEntry,
|
||||
@@ -13317,7 +13390,7 @@ export function toolAccessService(
|
||||
// empty personal grant below so later catalog refreshes use the same
|
||||
// identity policy.
|
||||
const unauthenticatedPersonalProbe = Boolean(
|
||||
!galleryEntry &&
|
||||
(!galleryEntry || remoteMcpConnector) &&
|
||||
genericAuthKind === "none" &&
|
||||
credentialSecretRefs.length === 0 &&
|
||||
personalIdentityUserId &&
|
||||
@@ -13330,7 +13403,10 @@ export function toolAccessService(
|
||||
});
|
||||
} catch (error) {
|
||||
if (
|
||||
!galleryEntry &&
|
||||
(!galleryEntry || remoteMcpConnector) &&
|
||||
input.authMode !== "none" &&
|
||||
input.authMode !== "bearer" &&
|
||||
input.authMode !== "custom_headers" &&
|
||||
error instanceof HttpError &&
|
||||
asRecord(error.details).code === "oauth_challenge"
|
||||
) {
|
||||
@@ -13421,7 +13497,7 @@ export function toolAccessService(
|
||||
// later fails: another retry may already be using the committed grant.
|
||||
personalPublicSetupEstablished = true;
|
||||
}
|
||||
if (galleryEntry?.slug === COMPOSIO_GALLERY_KEY) {
|
||||
if (galleryEntry?.slug === COMPOSIO_GALLERY_KEY && transport === "rest_api") {
|
||||
const [application] = await db
|
||||
.select()
|
||||
.from(toolApplications)
|
||||
@@ -13440,7 +13516,7 @@ export function toolAccessService(
|
||||
}
|
||||
const restoreDraftDefaults = Boolean(revivedConnectionPrevious);
|
||||
const refreshOptions = {
|
||||
enableAllByDefault: restoreDraftDefaults,
|
||||
enableAllByDefault: restoreDraftDefaults && !remoteMcpConnector,
|
||||
restoreDraftDefaults,
|
||||
};
|
||||
const catalogConnectionId = connectionRow.id;
|
||||
@@ -13802,6 +13878,23 @@ export function toolAccessService(
|
||||
const connection = await getConnectionRow(connectionId, companyId);
|
||||
if (connection.status === "archived")
|
||||
throw conflict("Archived app connections cannot be finished");
|
||||
if (connection.config.mcpPreserveAccess === true && isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey)) {
|
||||
const [profile] = await db.select().from(toolProfiles).where(and(
|
||||
eq(toolProfiles.companyId, companyId), eq(toolProfiles.profileKey, `app:${connection.id}`),
|
||||
)).limit(1);
|
||||
if (!profile) throw conflict("The saved connection permissions could not be found");
|
||||
const config = { ...connection.config };
|
||||
delete config.mcpPreserveAccess;
|
||||
const updated = await db.transaction(async (tx) => {
|
||||
const [row] = await tx.update(toolConnections).set({ config, transportConfig: config, status: "active", enabled: true, updatedAt: new Date() })
|
||||
.where(and(eq(toolConnections.id, connection.id), eq(toolConnections.companyId, companyId))).returning();
|
||||
await tx.update(toolApplications).set({ status: "active", updatedAt: new Date() }).where(and(eq(toolApplications.id, connection.applicationId), eq(toolApplications.companyId, companyId)));
|
||||
return row;
|
||||
});
|
||||
const details = await profileDetails(profile.id, companyId);
|
||||
const policies = (await db.select().from(toolPolicies).where(eq(toolPolicies.companyId, companyId))).filter((policy) => asRecord(policy.config).connectionId === connection.id);
|
||||
return { connection: toConnection(updated), profile: toProfile(profile), profileEntries: details.entries, profileBindings: details.bindings, policies: policies.map(toPolicy) };
|
||||
}
|
||||
const enabledIds = [
|
||||
...new Set([
|
||||
...input.enabledCatalogEntryIds,
|
||||
@@ -13825,7 +13918,7 @@ export function toolAccessService(
|
||||
connection.id,
|
||||
input.askFirstCatalogEntryIds,
|
||||
);
|
||||
if (enabledRows.some((entry) => entry.status === "disabled")) {
|
||||
if (enabledRows.some((entry) => entry.status === "disabled" && !(entry.quarantineReason === "mcp_tool_removed" && isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey)))) {
|
||||
throw badRequest("Disabled actions cannot be enabled");
|
||||
}
|
||||
if (reviewedIds.length > 0) {
|
||||
@@ -14032,6 +14125,28 @@ export function toolAccessService(
|
||||
}
|
||||
|
||||
const profileBindings: ToolProfileBinding[] = [];
|
||||
// These connectors expose one agent-access choice. Commit installation
|
||||
// reach and permission bindings together, including an empty selection.
|
||||
if (isRemoteMcpConnectorMethod(connection.config.sourceTemplateKey, connection.config.connectionMethodKey)) {
|
||||
const existingInstalls = await tx.select().from(toolConnectionInstalls).where(and(
|
||||
eq(toolConnectionInstalls.companyId, companyId), eq(toolConnectionInstalls.connectionId, connection.id),
|
||||
));
|
||||
const desired = new Map(bindingInputs.flatMap((binding) => binding.targetType === "company" || binding.targetType === "agent"
|
||||
? [[`${binding.targetType}:${binding.targetId}`, { targetType: binding.targetType, targetId: binding.targetId }] as const] : []));
|
||||
const removed = existingInstalls.filter((install) => !desired.has(`${install.targetType}:${install.targetId}`));
|
||||
const added = [...desired.values()].filter((binding) => !existingInstalls.some((install) => install.targetType === binding.targetType && install.targetId === binding.targetId));
|
||||
if (removed.length) await tx.delete(toolConnectionInstalls).where(inArray(toolConnectionInstalls.id, removed.map((install) => install.id)));
|
||||
if (added.length) await tx.insert(toolConnectionInstalls).values(added.map((binding) => ({
|
||||
companyId, connectionId: connection.id, targetType: binding.targetType, targetId: binding.targetId,
|
||||
createdByAgentId: actor?.actorType === "agent" ? (actor.actorId ?? null) : null,
|
||||
createdByUserId: actor?.actorType === "user" ? (actor.actorId ?? null) : null,
|
||||
})));
|
||||
if (added.length || removed.length) await tx.insert(toolAccessAuditEvents).values({
|
||||
companyId, connectionId: connection.id, actorType: actor?.actorType ?? "system", actorId: actor?.actorId ?? null,
|
||||
action: "connection_installs.changed", outcome: "success", reasonCode: "installs_changed",
|
||||
details: { added: added.map(({ targetType, targetId }) => ({ targetType, targetId })), removed: removed.map(({ targetType, targetId }) => ({ targetType, targetId })) },
|
||||
});
|
||||
}
|
||||
for (const bindingInput of bindingInputs) {
|
||||
const [binding] = await tx
|
||||
.insert(toolProfileBindings)
|
||||
@@ -14094,6 +14209,7 @@ export function toolAccessService(
|
||||
eq(toolCatalogEntries.companyId, companyId),
|
||||
inArray(toolCatalogEntries.id, enabledIds),
|
||||
ne(toolCatalogEntries.status, "quarantined"),
|
||||
ne(toolCatalogEntries.status, "disabled"),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -14228,6 +14344,7 @@ export function toolAccessService(
|
||||
actor?: ActorInfo,
|
||||
): Promise<ToolConnectionHealthCheckResult> {
|
||||
const connection = await getConnectionRow(connectionId, companyId);
|
||||
await assertMcpAggregatorSetupEnabled(connection.config.sourceTemplateKey, connection.config.connectionMethodKey);
|
||||
if (connection.status === "archived")
|
||||
throw conflict("Archived app connections cannot be reconnected");
|
||||
if (connection.credentialSource === "vercel_connect") {
|
||||
@@ -14409,6 +14526,7 @@ export function toolAccessService(
|
||||
},
|
||||
): Promise<ToolOAuthStartResult> {
|
||||
let connection = await getConnectionRow(connectionId, companyId);
|
||||
await assertMcpAggregatorSetupEnabled(connection.config.sourceTemplateKey, connection.config.connectionMethodKey);
|
||||
if (connection.status === "archived")
|
||||
throw conflict("Archived app connections cannot start sign in");
|
||||
const sourceTemplateKey =
|
||||
@@ -15143,10 +15261,11 @@ export function toolAccessService(
|
||||
: suggestedAgentIds.length > 0
|
||||
? { agentIds: suggestedAgentIds }
|
||||
: "all_agents";
|
||||
const remoteMcpAccess = isRemoteMcpConnectorMethod(input.connection.config.sourceTemplateKey, input.connection.config.connectionMethodKey);
|
||||
const access: FinishToolApp["access"] = deferTaskAccess
|
||||
? { agentIds: [] }
|
||||
: installs.length === 0
|
||||
? normalizedSuggestedAccess
|
||||
? remoteMcpAccess ? { agentIds: [] } : normalizedSuggestedAccess
|
||||
: companyInstall
|
||||
? "all_agents"
|
||||
: { agentIds };
|
||||
@@ -15181,7 +15300,7 @@ export function toolAccessService(
|
||||
},
|
||||
input.actor,
|
||||
);
|
||||
if (!deferTaskAccess && installs.length === 0) {
|
||||
if (!deferTaskAccess && !remoteMcpAccess && installs.length === 0) {
|
||||
const installTargets =
|
||||
access === "all_agents"
|
||||
? [
|
||||
@@ -16856,6 +16975,7 @@ export function toolAccessService(
|
||||
if (!app || app.availability?.available === false)
|
||||
throw notFound("App not found");
|
||||
const method = connectionMethodFor(app, methodKey);
|
||||
await assertMcpAggregatorSetupEnabled(app.slug, method.key);
|
||||
if (method.transport !== "mcp_remote" || !method.defaults?.serverUrl) {
|
||||
throw unprocessable(
|
||||
"This app method does not use a hosted remote MCP endpoint",
|
||||
|
||||
Reference in new issue
Block a user