Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: mcp pipedream integration (#5578)

Eric Hayes2838339c3166
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 6e8fd4b576..3381836510 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -102,6 +102,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -127,6 +128,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/pipedream_mcp",
"crates/projects",
"crates/prompt",
"crates/properties",
@@ -280,6 +282,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -305,6 +308,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/pipedream_mcp",
"crates/projects",
"crates/prompt",
"crates/properties",
@@ -767,6 +771,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -792,6 +797,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/pipedream_mcp",
"crates/projects",
"crates/prompt",
"crates/properties",
@@ -1555,6 +1561,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/memory",
"crates/mention_utils",
"crates/model",
@@ -1582,6 +1589,7 @@
"crates/onboarding",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/pipedream_mcp",
"crates/projects",
"crates/prompt",
"crates/properties",
@@ -1700,6 +1708,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -1726,6 +1735,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/pipedream_mcp",
"crates/projects",
"crates/prompt",
"crates/properties",
@@ -3426,6 +3436,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -3440,6 +3451,7 @@
"crates/models_properties",
"crates/non_empty",
"crates/notification",
+ "crates/pipedream_mcp",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
@@ -3928,6 +3940,31 @@
"crates/remote_env_var",
"crates/workspace-hack"
],
+ "mcp_select": [
+ "crates/agent",
+ "crates/ai_toolset",
+ "crates/ai_usage",
+ "crates/attachment",
+ "crates/bot_id",
+ "crates/cowlike",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_user_id",
+ "crates/macro_uuid",
+ "crates/mcp_client",
+ "crates/mcp_select",
+ "crates/model-entity",
+ "crates/model-error-response",
+ "crates/model_file_type",
+ "crates/model_user",
+ "crates/non_empty",
+ "crates/pipedream_mcp",
+ "crates/prompt",
+ "crates/remote_env_var",
+ "crates/workspace-hack"
+ ],
"mcp_service": [
"crates/activity",
"crates/agent",
@@ -3993,6 +4030,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -4018,6 +4056,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/pipedream_mcp",
"crates/projects",
"crates/prompt",
"crates/properties",
@@ -4107,6 +4146,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/memory",
"crates/mention_utils",
"crates/model",
@@ -4133,6 +4173,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/pipedream_mcp",
"crates/projects",
"crates/prompt",
"crates/properties",
@@ -4696,6 +4737,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/mention_utils",
"crates/model",
"crates/model-entity",
@@ -4711,6 +4753,7 @@
"crates/non_empty",
"crates/notification",
"crates/onboarding",
+ "crates/pipedream_mcp",
"crates/prompt",
"crates/properties",
"crates/rate_limit",
@@ -4857,6 +4900,21 @@
"crates/workspace-hack",
"services/organization_retention_trigger"
],
+ "pipedream_mcp": [
+ "crates/ai_toolset",
+ "crates/bot_id",
+ "crates/cowlike",
+ "crates/macro_auth",
+ "crates/macro_authorization",
+ "crates/macro_env",
+ "crates/macro_env_var",
+ "crates/macro_user_id",
+ "crates/model-error-response",
+ "crates/model_user",
+ "crates/pipedream_mcp",
+ "crates/remote_env_var",
+ "crates/workspace-hack"
+ ],
"projects": [
"crates/activity",
"crates/agent",
@@ -5213,6 +5271,7 @@
"crates/macro_user_id",
"crates/macro_uuid",
"crates/mcp_client",
+ "crates/mcp_select",
"crates/memory",
"crates/mention_utils",
"crates/model",
@@ -5239,6 +5298,7 @@
"crates/notification",
"crates/opensearch_client",
"crates/opensearch_query_builder",
+ "crates/pipedream_mcp",
"crates/projects",
"crates/prompt",
"crates/properties",
diff --git a/.sqlx/query-0b68582245945550352951f088e1aa97e8d47b0ba5c9d8db55ce6bdc4b06ab57.json b/.sqlx/query-0b68582245945550352951f088e1aa97e8d47b0ba5c9d8db55ce6bdc4b06ab57.json
new file mode 100644
index 0000000000..c46621f279
--- /dev/null
+++ b/.sqlx/query-0b68582245945550352951f088e1aa97e8d47b0ba5c9d8db55ce6bdc4b06ab57.json
@@ -0,0 +1,15 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "DELETE FROM pipedream_mcp_connections WHERE user_id = $1 AND app_slug = $2",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "0b68582245945550352951f088e1aa97e8d47b0ba5c9d8db55ce6bdc4b06ab57"
+}
diff --git a/.sqlx/query-9bb0c84cfdbb24adebbe1b353b2e7eca014bcee5d23b98848be98e730fda35dc.json b/.sqlx/query-9bb0c84cfdbb24adebbe1b353b2e7eca014bcee5d23b98848be98e730fda35dc.json
new file mode 100644
index 0000000000..461e85d094
--- /dev/null
+++ b/.sqlx/query-9bb0c84cfdbb24adebbe1b353b2e7eca014bcee5d23b98848be98e730fda35dc.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO pipedream_mcp_connections (user_id, app_slug, server_name, account_id, enabled)\n VALUES ($1, $2, $3, $4, $5)\n ON CONFLICT (user_id, app_slug) DO UPDATE SET\n server_name = EXCLUDED.server_name,\n account_id = EXCLUDED.account_id,\n enabled = EXCLUDED.enabled,\n updated_at = NOW()\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text",
+ "Text",
+ "Text",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "9bb0c84cfdbb24adebbe1b353b2e7eca014bcee5d23b98848be98e730fda35dc"
+}
diff --git a/.sqlx/query-a905842e5c1f31766d551eb43ab6dc520f212c9af7ec5b6de4965213916fd9ea.json b/.sqlx/query-a905842e5c1f31766d551eb43ab6dc520f212c9af7ec5b6de4965213916fd9ea.json
new file mode 100644
index 0000000000..5d0d74d997
--- /dev/null
+++ b/.sqlx/query-a905842e5c1f31766d551eb43ab6dc520f212c9af7ec5b6de4965213916fd9ea.json
@@ -0,0 +1,46 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id, app_slug, server_name, account_id, enabled\n FROM pipedream_mcp_connections\n WHERE user_id = $1\n ORDER BY server_name\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "app_slug",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "server_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "account_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "a905842e5c1f31766d551eb43ab6dc520f212c9af7ec5b6de4965213916fd9ea"
+}
diff --git a/.sqlx/query-ccee0941901634aaa91df3d5978662fdcb9ef8fb9553587ff3f53913895eea14.json b/.sqlx/query-ccee0941901634aaa91df3d5978662fdcb9ef8fb9553587ff3f53913895eea14.json
new file mode 100644
index 0000000000..6166e02773
--- /dev/null
+++ b/.sqlx/query-ccee0941901634aaa91df3d5978662fdcb9ef8fb9553587ff3f53913895eea14.json
@@ -0,0 +1,47 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT user_id, app_slug, server_name, account_id, enabled\n FROM pipedream_mcp_connections\n WHERE user_id = $1 AND app_slug = $2\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "user_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 1,
+ "name": "app_slug",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "server_name",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "account_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 4,
+ "name": "enabled",
+ "type_info": "Bool"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "ccee0941901634aaa91df3d5978662fdcb9ef8fb9553587ff3f53913895eea14"
+}
diff --git a/Cargo.lock b/Cargo.lock
index a351a5b3b2..5e8ea684ee 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -301,6 +301,7 @@ dependencies = [
"macro_service_urls",
"macro_user_id",
"mcp_client",
+ "mcp_select",
"model",
"model-entity",
"model_notifications",
@@ -313,6 +314,7 @@ dependencies = [
"models_soup",
"non_empty",
"notification",
+ "pipedream_mcp",
"projects",
"prompt",
"properties",
@@ -4386,6 +4388,7 @@ dependencies = [
"macro_user_id",
"macro_uuid",
"mcp_client",
+ "mcp_select",
"memory",
"model",
"model-entity",
@@ -4397,6 +4400,7 @@ dependencies = [
"non_empty",
"notification",
"onboarding",
+ "pipedream_mcp",
"prompt",
"readonly_pool",
"redis",
@@ -7549,7 +7553,7 @@ dependencies = [
"macro_authorization",
"macro_db_migrator",
"macro_user_id",
- "mcp_client",
+ "mcp_select",
"model-entity",
"models_properties",
"properties",
@@ -9172,6 +9176,20 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "mcp_select"
+version = "0.1.0"
+dependencies = [
+ "ai_toolset",
+ "anyhow",
+ "macro_user_id",
+ "mcp_client",
+ "pipedream_mcp",
+ "serde_json",
+ "tracing",
+ "workspace-hack",
+]
+
[[package]]
name = "mcp_service"
version = "0.1.0"
@@ -10531,6 +10549,7 @@ dependencies = [
"macro_authorization",
"macro_user_id",
"mcp_client",
+ "mcp_select",
"serde",
"serde_json",
"sqlx",
@@ -11238,6 +11257,30 @@ version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
+[[package]]
+name = "pipedream_mcp"
+version = "0.1.0"
+dependencies = [
+ "ai_toolset",
+ "anyhow",
+ "axum",
+ "futures",
+ "macro_authorization",
+ "macro_user_id",
+ "model-error-response",
+ "reqwest 0.13.4",
+ "rmcp",
+ "schemars 1.2.1",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.18",
+ "tokio",
+ "tracing",
+ "utoipa",
+ "workspace-hack",
+]
+
[[package]]
name = "piper"
version = "0.2.5"
diff --git a/Cargo.toml b/Cargo.toml
index b59dd8dd8e..5fdb8927a8 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -47,6 +47,8 @@ members = [
"crates/macro_sync_service_jwt",
"crates/maybe_send",
"crates/memory",
+ "crates/mcp_select",
+ "crates/pipedream_mcp",
"crates/onboarding",
"crates/prompt",
"crates/properties_service",
diff --git a/apps/web/src/features/getting-started/getting-started.tsx b/apps/web/src/features/getting-started/getting-started.tsx
index 4473f47a8f..528ebc0dc1 100644
--- a/apps/web/src/features/getting-started/getting-started.tsx
+++ b/apps/web/src/features/getting-started/getting-started.tsx
@@ -26,6 +26,7 @@ import { useGithubLinkStatusQuery } from '@queries/auth/github-link';
import { isRealNamePart, useOwnUserName } from '@queries/auth/user-name-self';
import { useEmailLinksQuery } from '@queries/email/link';
import { useMcpServersQuery } from '@queries/mcp-servers';
+import { usePipedreamConnectionsQuery } from '@queries/pipedream-connectors';
import { useStarterDocsQuery } from '@queries/starter-docs';
import {
currentThemeId,
@@ -76,6 +77,10 @@ function GettingStartedContent() {
refetchInterval: 4_000,
neverSuspend: true,
});
+ const pipedreamConnections = usePipedreamConnectionsQuery({
+ refetchInterval: 4_000,
+ neverSuspend: true,
+ });
const emailLinks = useEmailLinksQuery();
const githubLink = useGithubLinkStatusQuery();
const userInfo = useUserInfo();
@@ -165,6 +170,7 @@ function GettingStartedContent() {
isComplete: () =>
(emailLinks.data?.links.length ?? 0) > 1 ||
githubLink.data?.status === 'linked' ||
+ (pipedreamConnections.data ?? []).length > 0 ||
(mcpServers.data ?? []).some((server) => server.authenticated),
},
],
diff --git a/apps/web/src/features/home/home-hub.tsx b/apps/web/src/features/home/home-hub.tsx
index 81df8ae5b8..04bd774194 100644
--- a/apps/web/src/features/home/home-hub.tsx
+++ b/apps/web/src/features/home/home-hub.tsx
@@ -25,6 +25,7 @@ import {
} from '@queries/ai/homeRecommendations';
import { useEmailLinksQuery } from '@queries/email/link';
import { useMcpServersQuery } from '@queries/mcp-servers';
+import { usePipedreamConnectionsQuery } from '@queries/pipedream-connectors';
import { useNavigate } from '@solidjs/router';
import { For, Match, Show, Switch } from 'solid-js';
import { match } from 'ts-pattern';
@@ -217,12 +218,15 @@ export function RecommendedSection() {
function useConnectionsCount() {
const emailLinks = useEmailLinksQuery();
const mcpServers = useMcpServersQuery();
+ const pipedreamConnections = usePipedreamConnectionsQuery();
return () => {
const inboxes = emailLinks.data?.links.length ?? 0;
- const servers = (mcpServers.data ?? []).filter(
- (server) => server.authenticated
- ).length;
+ // Mirrors the backend's stack selection: Pipedream connectors win.
+ const pipedream = (pipedreamConnections.data ?? []).length;
+ const servers = pipedream
+ ? pipedream
+ : (mcpServers.data ?? []).filter((server) => server.authenticated).length;
return inboxes + servers;
};
}
diff --git a/apps/web/src/features/settings/ConnectedAccounts.tsx b/apps/web/src/features/settings/ConnectedAccounts.tsx
index 61dbc88c70..0c339cf69b 100644
--- a/apps/web/src/features/settings/ConnectedAccounts.tsx
+++ b/apps/web/src/features/settings/ConnectedAccounts.tsx
@@ -1,8 +1,10 @@
import { ENABLE_EMAIL } from '@core/constant/featureFlags';
+import { usePipedreamMcpFlag } from '@core/pipedream/flag';
import { Show, Suspense } from 'solid-js';
import { EmailCard } from './Email';
import { GitHubCard } from './GitHub';
import { IntegrationsSection } from './Integrations';
+import { PipedreamIntegrationsSection } from './PipedreamIntegrations';
import { SettingsPage, SettingsSection } from './primitives';
/**
@@ -11,6 +13,7 @@ import { SettingsPage, SettingsSection } from './primitives';
* Macro is connected to lives in one place.
*/
export function ConnectedAccounts() {
+ const pipedreamMcp = usePipedreamMcpFlag();
return (
<SettingsPage
title="Connections"
@@ -29,7 +32,9 @@ export function ConnectedAccounts() {
</div>
</SettingsSection>
<Suspense>
- <IntegrationsSection />
+ <Show when={pipedreamMcp()} fallback={<IntegrationsSection />}>
+ <PipedreamIntegrationsSection />
+ </Show>
</Suspense>
</SettingsPage>
);
diff --git a/apps/web/src/features/settings/PipedreamIntegrations.tsx b/apps/web/src/features/settings/PipedreamIntegrations.tsx
new file mode 100644
index 0000000000..e8f1d376d4
--- /dev/null
+++ b/apps/web/src/features/settings/PipedreamIntegrations.tsx
@@ -0,0 +1,355 @@
+import {
+ FEATURED_MCP_SERVERS,
+ PIPEDREAM_ICON_MAP,
+ pipedreamAppAvailableInEnv,
+} from '@core/component/AI/constant/mcpServers';
+import { toast } from '@core/component/Toast/Toast';
+import PlugIcon from '@phosphor-icons/core/regular/plug.svg?component-solid';
+import XIcon from '@phosphor-icons/core/regular/x.svg?component-solid';
+import {
+ connectPipedreamApp,
+ useDeletePipedreamConnectionMutation,
+ usePipedreamCatalogQuery,
+ usePipedreamConnectionsQuery,
+ useUpdatePipedreamConnectionMutation,
+} from '@queries/pipedream-connectors';
+import type {
+ PipedreamCatalogEntryResponse,
+ PipedreamConnectionResponse,
+} from '@service-cognition/client';
+import { Button, ToggleSwitch } from '@ui';
+import { createSignal, For, onCleanup, Show } from 'solid-js';
+import { ConnectAction } from './integration-ui';
+import { IntegrationRow, SettingsCard, SettingsSection } from './primitives';
+
+/** A connected app: enable/disable for tool use, or disconnect. */
+function ServerRow(props: { server: PipedreamConnectionResponse }) {
+ const updateMutation = useUpdatePipedreamConnectionMutation();
+ const deleteMutation = useDeletePipedreamConnectionMutation();
+ const [confirmDelete, setConfirmDelete] = createSignal(false);
+
+ const handleToggleEnabled = () => {
+ updateMutation.mutate(
+ { app_slug: props.server.app_slug, enabled: !props.server.enabled },
+ {
+ onError: () => {
+ toast.failure('Failed to update connector');
+ },
+ }
+ );
+ };
+
+ const handleDelete = () => {
+ deleteMutation.mutate(
+ { app_slug: props.server.app_slug },
+ {
+ onSuccess: () => {
+ toast.success('Connector removed');
+ setConfirmDelete(false);
+ },
+ onError: () => {
+ toast.failure('Failed to remove connector');
+ setConfirmDelete(false);
+ },
+ }
+ );
+ };
+
+ const Icon = () => PIPEDREAM_ICON_MAP.get(props.server.app_slug) ?? PlugIcon;
+
+ return (
+ <IntegrationRow
+ icon={(() => {
+ const C = Icon();
+ return <C class="size-5" />;
+ })()}
+ title={props.server.server_name}
+ description={props.server.app_slug}
+ >
+ <ToggleSwitch
+ size="md"
+ checked={props.server.enabled}
+ disabled={updateMutation.isPending}
+ onChange={handleToggleEnabled}
+ label={props.server.enabled ? 'Enabled' : 'Disabled'}
+ labelClass="inline-block w-14 text-left text-xs text-ink-muted whitespace-nowrap"
+ />
+
+ <Show
+ when={!confirmDelete()}
+ fallback={
+ <div class="flex items-center gap-1">
+ <Button
+ variant="danger"
+ size="sm"
+ depth={3}
+ disabled={deleteMutation.isPending}
+ onClick={handleDelete}
+ >
+ {deleteMutation.isPending ? 'Removing...' : 'Confirm'}
+ </Button>
+ <Button
+ variant="base"
+ size="sm"
+ depth={3}
+ onClick={() => setConfirmDelete(false)}
+ >
+ Cancel
+ </Button>
+ </div>
+ }
+ >
+ <Button
+ variant="base"
+ size="sm"
+ depth={3}
+ tooltip="Remove"
+ onClick={() => setConfirmDelete(true)}
+ >
+ <XIcon class="size-4" />
+ </Button>
+ </Show>
+ </IntegrationRow>
+ );
+}
+
+/**
+ * A connectable app from the catalog the user hasn't connected yet, shown
+ * inline in the integrations list to make connecting a one-click affair.
+ * Once connected, the app shows up as a regular {@link ServerRow} instead.
+ */
+function CatalogRow(props: { entry: PipedreamCatalogEntryResponse }) {
+ const [busy, setBusy] = createSignal(false);
+
+ const handleConnect = async () => {
+ if (busy()) return;
+ setBusy(true);
+ try {
+ const outcome = await connectPipedreamApp({
+ appSlug: props.entry.app_slug,
+ serverName: props.entry.display_name,
+ });
+ if (outcome === 'connected') {
+ toast.success(`${props.entry.display_name} connected`);
+ } else if (outcome === 'unsupported') {
+ toast.failure('Connectors are not available on this deployment');
+ }
+ } catch {
+ toast.failure(`Failed to connect ${props.entry.display_name}`);
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ return (
+ <IntegrationRow
+ icon={<CatalogIcon entry={props.entry} />}
+ title={props.entry.display_name}
+ description={props.entry.description ?? props.entry.app_slug}
+ >
+ <ConnectAction label="Connect" onClick={handleConnect} loading={busy()} />
+ </IntegrationRow>
+ );
+}
+
+/**
+ * Connector icon: our bundled SVG for the apps we ship icons for, the
+ * directory-provided icon otherwise, and a generic plug as the fallback.
+ */
+function CatalogIcon(props: { entry: PipedreamCatalogEntryResponse }) {
+ const BundledIcon = () => PIPEDREAM_ICON_MAP.get(props.entry.app_slug);
+ return (
+ <Show
+ when={BundledIcon()}
+ fallback={
+ <Show
+ when={props.entry.icon_url}
+ fallback={<PlugIcon class="size-5" />}
+ >
+ {(iconUrl) => (
+ <img
+ src={iconUrl()}
+ alt=""
+ loading="lazy"
+ class="size-5 rounded object-contain"
+ />
+ )}
+ </Show>
+ }
+ >
+ {(Icon) => {
+ const C = Icon();
+ return <C class="size-5" />;
+ }}
+ </Show>
+ );
+}
+
+/**
+ * Featured connectors as catalog entries, for when the catalog API hasn't
+ * answered yet (or is unavailable): the same curated list the backend pins,
+ * derived from the bundled presets so the section never renders empty.
+ */
+const FALLBACK_FEATURED: PipedreamCatalogEntryResponse[] =
+ FEATURED_MCP_SERVERS.map((server) => ({
+ app_slug: server.app_slug,
+ display_name: server.server_name,
+ description: server.tagline,
+ icon_url: null,
+ priority: true,
+ }));
+
+/**
+ * The "MCP integrations" section of the Connections page: apps the user has
+ * connected, then the curated featured connectors they haven't, then a
+ * searchable catalog of every connectable app — all connecting through
+ * Pipedream, the single connect path.
+ */
+export function PipedreamIntegrationsSection() {
+ const serversQuery = usePipedreamConnectionsQuery();
+
+ const [searchInput, setSearchInput] = createSignal('');
+ const [search, setSearch] = createSignal('');
+ let debounceTimer: ReturnType<typeof setTimeout> | undefined;
+ const onSearchInput = (value: string) => {
+ setSearchInput(value);
+ clearTimeout(debounceTimer);
+ debounceTimer = setTimeout(() => setSearch(value), 250);
+ };
+ onCleanup(() => clearTimeout(debounceTimer));
+
+ const catalogQuery = usePipedreamCatalogQuery(search);
+ // Separate un-searched instance backing the featured section, so it stays
+ // put while the user types in the catalog search below. Same cache entry
+ // as browsing with an empty search, so this costs no extra request.
+ const featuredQuery = usePipedreamCatalogQuery(() => '');
+
+ const servers = () => serversQuery.data ?? [];
+ const connectedSlugs = () => new Set(servers().map((s) => s.app_slug));
+
+ const offered = (entry: PipedreamCatalogEntryResponse) =>
+ pipedreamAppAvailableInEnv(entry.app_slug) &&
+ !connectedSlugs().has(entry.app_slug);
+
+ const catalogEntries = () =>
+ (catalogQuery.data?.pages ?? [])
+ .flatMap((page) => page.servers)
+ .filter(offered);
+
+ // The featured section always shows the full curated list, served from
+ // the presets bundled with the app until the catalog answers — the
+ // backend pins the same list, so nothing jumps when it does.
+ const featured = () => {
+ const entries = (featuredQuery.data?.pages ?? [])
+ .flatMap((page) => page.servers)
+ .filter((entry) => entry.priority)
+ .filter(offered);
+ return entries.length > 0 ? entries : FALLBACK_FEATURED.filter(offered);
+ };
+
+ // Searching shows every match, with featured connectors ranked first by
+ // the backend (flagged `priority`); browsing shows only organic directory
+ // results, since the full featured list already sits above.
+ const browseResults = () =>
+ search().trim()
+ ? catalogEntries()
+ : catalogEntries().filter((entry) => !entry.priority);
+
+ return (
+ <SettingsSection
+ title="MCP integrations"
+ description="Connect the tools your team already uses to give Macro's agent access to them."
+ >
+ <Show when={serversQuery.isError}>
+ <SettingsCard>
+ <div class="px-6 py-8 text-center text-sm text-ink-muted">
+ Failed to load integrations.
+ <Button
+ variant="base"
+ size="sm"
+ depth={3}
+ onClick={() => serversQuery.refetch()}
+ class="ml-2"
+ >
+ Retry
+ </Button>
+ </div>
+ </SettingsCard>
+ </Show>
+
+ <Show when={!serversQuery.isError}>
+ <SettingsCard>
+ <For each={servers()}>
+ {(server) => <ServerRow server={server} />}
+ </For>
+ <For each={featured()}>{(entry) => <CatalogRow entry={entry} />}</For>
+ </SettingsCard>
+ </Show>
+
+ <SettingsCard>
+ <div class="px-4 py-3">
+ <input
+ type="search"
+ class="settings-input w-full"
+ placeholder="Search all connectors..."
+ value={searchInput()}
+ onInput={(e) => onSearchInput(e.currentTarget.value)}
+ />
+ </div>
+
+ <Show when={catalogQuery.isError}>
+ <div class="px-6 py-6 text-center text-sm text-ink-muted">
+ Couldn't load the connector catalog.
+ <Button
+ variant="base"
+ size="sm"
+ depth={3}
+ onClick={() => catalogQuery.refetch()}
+ class="ml-2"
+ >
+ Retry
+ </Button>
+ </div>
+ </Show>
+
+ <Show when={!catalogQuery.isError}>
+ <For each={browseResults()}>
+ {(entry) => <CatalogRow entry={entry} />}
+ </For>
+
+ <Show when={catalogQuery.isFetching && browseResults().length === 0}>
+ <div class="px-6 py-6 text-center text-sm text-ink-muted">
+ Loading connectors...
+ </div>
+ </Show>
+
+ <Show
+ when={
+ !catalogQuery.isFetching &&
+ browseResults().length === 0 &&
+ search().trim()
+ }
+ >
+ <div class="px-6 py-6 text-center text-sm text-ink-muted">
+ No connectors found for "{search().trim()}".
+ </div>
+ </Show>
+
+ <Show when={catalogQuery.hasNextPage}>
+ <div class="px-4 py-3 text-center">
+ <Button
+ variant="base"
+ size="sm"
+ depth={3}
+ disabled={catalogQuery.isFetchingNextPage}
+ onClick={() => void catalogQuery.fetchNextPage()}
+ >
+ {catalogQuery.isFetchingNextPage ? 'Loading...' : 'Load more'}
+ </Button>
+ </div>
+ </Show>
+ </Show>
+ </SettingsCard>
+ </SettingsSection>
+ );
+}
diff --git a/apps/web/src/features/setup/flow/ConnectorStep.tsx b/apps/web/src/features/setup/flow/ConnectorStep.tsx
index bb6babee81..8ee68e8bee 100644
--- a/apps/web/src/features/setup/flow/ConnectorStep.tsx
+++ b/apps/web/src/features/setup/flow/ConnectorStep.tsx
@@ -1,7 +1,9 @@
import { useAnalytics } from '@app/lib/analytics/analytics-context';
import type { FeaturedMcpServer } from '@core/component/AI/constant/mcpServers';
+import { usePipedreamMcpFlag } from '@core/pipedream/flag';
import SpinnerIcon from '@phosphor/spinner-gap.svg';
import { useMcpServersQuery } from '@queries/mcp-servers';
+import { usePipedreamConnectionsQuery } from '@queries/pipedream-connectors';
import { Layer } from '@ui';
import { createEffect, createMemo, Show } from 'solid-js';
import { ConnectorRow } from '../ConnectorRow';
@@ -21,19 +23,37 @@ export function ConnectorStep(props: {
}) {
// Poll: OAuth completes in a popup, and if this window never blurs no
// focus-refetch would ever flip the step.
+ const pipedreamMcp = usePipedreamMcpFlag();
const serversQuery = useMcpServersQuery({
refetchInterval: 4_000,
neverSuspend: true,
});
+ const pipedreamQuery = usePipedreamConnectionsQuery({
+ refetchInterval: 4_000,
+ neverSuspend: true,
+ });
const record = createMemo(() =>
serversQuery.data?.find((server) => server.url === props.server.url)
);
- const authenticated = () => record()?.authenticated ?? false;
+ const pipedreamRecord = createMemo(() =>
+ pipedreamQuery.data?.find(
+ (connection) => connection.app_slug === props.server.app_slug
+ )
+ );
+ const authenticated = () =>
+ pipedreamMcp()
+ ? pipedreamRecord() !== undefined
+ : (record()?.authenticated ?? false);
const analytics = useAnalytics();
let wasAuthenticated: boolean | undefined;
createEffect(() => {
- if (serversQuery.isPlaceholderData) return;
+ if (
+ pipedreamMcp()
+ ? pipedreamQuery.isPlaceholderData
+ : serversQuery.isPlaceholderData
+ )
+ return;
const authed = authenticated();
if (wasAuthenticated === false && authed) {
analytics.track('onboarding_v4_connector_connected', {
@@ -48,7 +68,11 @@ export function ConnectorStep(props: {
{/* On the placeholder, an already-connected server would render as
unconnected and clickable (duplicate add + pointless popup). */}
<Show
- when={!serversQuery.isPlaceholderData}
+ when={
+ pipedreamMcp()
+ ? !pipedreamQuery.isPlaceholderData
+ : !serversQuery.isPlaceholderData
+ }
fallback={
<Layer depth={2}>
<div class="flex h-11 w-full items-center gap-2.5 rounded-xl border border-ink/[0.05] bg-surface px-3.5 text-sm">
@@ -68,7 +92,11 @@ export function ConnectorStep(props: {
>
<ConnectorRow
server={props.server}
- connected={record() !== undefined}
+ connected={
+ pipedreamMcp()
+ ? pipedreamRecord() !== undefined
+ : record() !== undefined
+ }
authenticated={authenticated()}
/>
</Show>
diff --git a/apps/web/src/features/setup/flow/OnboardingFlow.tsx b/apps/web/src/features/setup/flow/OnboardingFlow.tsx
index baacaa35e6..1c98d4a4f5 100644
--- a/apps/web/src/features/setup/flow/OnboardingFlow.tsx
+++ b/apps/web/src/features/setup/flow/OnboardingFlow.tsx
@@ -10,6 +10,7 @@ import { useEmailLinksQuery } from '@queries/email/link';
import { useImportQuery } from '@queries/import';
import { useMcpServersQuery } from '@queries/mcp-servers';
import { useOnboardingQuery } from '@queries/onboarding';
+import { usePipedreamConnectionsQuery } from '@queries/pipedream-connectors';
import { useNavigate } from '@solidjs/router';
import { cn } from '@ui';
import { Stepper } from '@ui/components/Stepper';
@@ -270,15 +271,26 @@ function FlowContent() {
// suspend this boundary.
const linksQuery = useEmailLinksQuery();
const serversQuery = useMcpServersQuery({ neverSuspend: true });
+ const pipedreamQuery = usePipedreamConnectionsQuery({ neverSuspend: true });
const analytics = useAnalytics();
// Live connection state, derived from the flow's queries (no standing
// bookkeeping): whether an MCP server authenticated, and which tools the
// user connected. Drives the hero-module states and the build phrases.
- const serverAuthed = (name: string) =>
- (serversQuery.data ?? []).some(
+ // Mirrors the backend's stack-selection rule (`mcp_select`): a user with
+ // any Pipedream connectors is served those, so native rows stop counting.
+ const serverAuthed = (name: string) => {
+ const pipedream = pipedreamQuery.data ?? [];
+ if (pipedream.length > 0) {
+ return pipedream.some(
+ (connection) =>
+ connection.server_name.toLowerCase() === name.toLowerCase()
+ );
+ }
+ return (serversQuery.data ?? []).some(
(server) => server.server_name === name && server.authenticated
);
+ };
const connectedTools = (): ConnectedTools => ({
google: (linksQuery.data?.links.length ?? 0) > 0,
linear: serverAuthed('Linear'),
@@ -412,9 +424,13 @@ function FlowContent() {
const finish = createFlowFinish({
completionRollup: () => ({
emails_connected: linksQuery.data?.links.length ?? 0,
- connectors_connected: (serversQuery.data ?? [])
- .filter((server) => server.authenticated)
- .map((server) => server.server_name.toLowerCase()),
+ connectors_connected: (pipedreamQuery.data ?? []).length
+ ? (pipedreamQuery.data ?? []).map((connection) =>
+ connection.server_name.toLowerCase()
+ )
+ : (serversQuery.data ?? [])
+ .filter((server) => server.authenticated)
+ .map((server) => server.server_name.toLowerCase()),
}),
});
const controls: StepControls = {
diff --git a/apps/web/src/features/setup/useConnectorConnect.ts b/apps/web/src/features/setup/useConnectorConnect.ts
index 77143f9d71..1aafe9b1c8 100644
--- a/apps/web/src/features/setup/useConnectorConnect.ts
+++ b/apps/web/src/features/setup/useConnectorConnect.ts
@@ -1,11 +1,13 @@
import type { FeaturedMcpServer } from '@core/component/AI/constant/mcpServers';
import { toast } from '@core/component/Toast/Toast';
+import { usePipedreamMcpFlag } from '@core/pipedream/flag';
import { isTauri } from '@core/util/platform';
import { openExternalUrl } from '@core/util/url';
import {
useAddMcpServerMutation,
useStartMcpAuthMutation,
} from '@queries/mcp-servers';
+import { connectPipedreamApp } from '@queries/pipedream-connectors';
import type { StartAuthResponse } from '@service-cognition/generated/schemas';
import { type Accessor, createSignal } from 'solid-js';
@@ -33,11 +35,31 @@ export function createConnectorConnect(options: {
}) {
const addMutation = useAddMcpServerMutation();
const authMutation = useStartMcpAuthMutation();
+ const pipedreamMcp = usePipedreamMcpFlag();
const [busy, setBusy] = createSignal(false);
const connect = async () => {
if (options.authenticated() || busy()) return;
setBusy(true);
+ // Behind the PostHog flag, connectors go through Pipedream's hosted
+ // Connect UI (an iframe — no popup involved) instead of the native
+ // OAuth popup flow.
+ if (pipedreamMcp()) {
+ try {
+ const outcome = await connectPipedreamApp({
+ appSlug: options.server.app_slug,
+ serverName: options.server.server_name,
+ });
+ if (outcome === 'unsupported') {
+ toast.failure('Connectors are not available on this deployment');
+ }
+ } catch {
+ toast.failure(`Failed to connect ${options.server.server_name}`);
+ } finally {
+ setBusy(false);
+ }
+ return;
+ }
const popup = isTauri() ? null : window.open('about:blank', '_blank');
if (popup) popup.opener = null;
try {
diff --git a/apps/web/src/lib/core/component/AI/constant/mcpServers.ts b/apps/web/src/lib/core/component/AI/constant/mcpServers.ts
index 9d5ec8834c..f48f051def 100644
--- a/apps/web/src/lib/core/component/AI/constant/mcpServers.ts
+++ b/apps/web/src/lib/core/component/AI/constant/mcpServers.ts
@@ -13,11 +13,13 @@ export type SvgIcon = Component<JSX.SvgSVGAttributes<SVGSVGElement>>;
export const QUICK_CONNECT_SERVERS = [
{
server_name: 'GitHub',
+ app_slug: 'github',
url: 'https://api.githubcopilot.com/mcp',
icon: IconGithub as SvgIcon,
},
{
server_name: 'Linear',
+ app_slug: 'linear',
url: 'https://mcp.linear.app/mcp',
icon: IconLinear as SvgIcon,
},
@@ -26,6 +28,7 @@ export const QUICK_CONNECT_SERVERS = [
? ([
{
server_name: 'Slack',
+ app_slug: 'slack',
url: 'https://mcp.slack.com/mcp',
icon: IconSlack as SvgIcon,
},
@@ -33,21 +36,25 @@ export const QUICK_CONNECT_SERVERS = [
: []),
{
server_name: 'Notion',
+ app_slug: 'notion',
url: 'https://mcp.notion.com/mcp',
icon: IconNotion as SvgIcon,
},
{
server_name: 'PostHog',
+ app_slug: 'posthog',
url: 'https://mcp.posthog.com/mcp',
icon: IconPostHog as SvgIcon,
},
{
server_name: 'Datadog',
+ app_slug: 'datadog',
url: 'https://mcp.datadoghq.com/mcp',
icon: IconDatadog as SvgIcon,
},
{
server_name: 'Grafana',
+ app_slug: 'grafana',
url: 'https://mcp.grafana.com/mcp',
icon: IconGrafana as SvgIcon,
},
@@ -84,6 +91,20 @@ export const QUICK_CONNECT_ICON_MAP: Map<string, SvgIcon> = new Map(
QUICK_CONNECT_SERVERS.map((s) => [s.url, s.icon])
);
+/** Bundled connector icons keyed by Pipedream app slug (Pipedream flow). */
+export const PIPEDREAM_ICON_MAP: Map<string, SvgIcon> = new Map(
+ QUICK_CONNECT_SERVERS.map((s) => [s.app_slug, s.icon])
+);
+
+/**
+ * Whether a Pipedream catalog app should be offered in this environment.
+ * Mirrors the gating in {@link QUICK_CONNECT_SERVERS} (Slack is dev-only).
+ */
+export function pipedreamAppAvailableInEnv(appSlug: string): boolean {
+ if (DEV_MODE_ENV) return true;
+ return appSlug !== 'slack';
+}
+
const SERVER_NAME_ICON_MAP: Map<string, SvgIcon> = new Map(
QUICK_CONNECT_SERVERS.map((s) => [s.server_name.toLowerCase(), s.icon])
);
diff --git a/apps/web/src/lib/core/pipedream/connect-ui.ts b/apps/web/src/lib/core/pipedream/connect-ui.ts
new file mode 100644
index 0000000000..bc359a6ae1
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/connect-ui.ts
@@ -0,0 +1,84 @@
+/**
+ * Minimal client for Pipedream's hosted Connect UI.
+ *
+ * Vendored equivalent of the iframe portion of `@pipedream/sdk`'s browser
+ * client (adding the dependency would require regenerating the nix
+ * node_modules hash): a fullscreen iframe pointed at Pipedream's hosted
+ * connect page, which reports lifecycle events back via `postMessage`.
+ */
+
+const CONNECT_UI_URL = 'https://pipedream.com/_static/connect.html';
+
+export type PipedreamConnectEvent =
+ /** The user authorized the app; `accountId` is the connected account. */
+ | { type: 'success'; accountId: string }
+ /** Something failed inside the connect flow. */
+ | { type: 'error'; error?: string }
+ /** The user closed the Connect UI. */
+ | { type: 'close' };
+
+export type PipedreamConnectUI = {
+ /** Remove the iframe and stop listening for events. */
+ close: () => void;
+};
+
+/**
+ * Open Pipedream's hosted Connect UI in a fullscreen iframe.
+ *
+ * The UI walks the user through authorizing `app` (OAuth consent or API-key
+ * entry — Pipedream owns the whole flow and stores the credentials).
+ * Lifecycle events are delivered to `onEvent`; the caller closes the UI
+ * after a success event (the hosted page closes itself otherwise).
+ */
+export function openPipedreamConnectUI(options: {
+ /** Short-lived Connect token minted by our backend for this user. */
+ token: string;
+ /** The Pipedream app to connect, by name slug (e.g. `linear`). */
+ app: string;
+ onEvent: (event: PipedreamConnectEvent) => void;
+}): PipedreamConnectUI {
+ const params = new URLSearchParams({
+ token: options.token,
+ app: options.app,
+ });
+
+ const iframe = document.createElement('iframe');
+ iframe.title = 'Pipedream Connect';
+ iframe.src = `${CONNECT_UI_URL}?${params.toString()}`;
+ iframe.style.cssText =
+ 'position:fixed;inset:0;z-index:2147483647;border:0;display:block;overflow:hidden auto;width:100%;height:100%';
+
+ const cleanup = () => {
+ window.removeEventListener('message', onMessage);
+ iframe.remove();
+ };
+
+ const onMessage = (event: MessageEvent) => {
+ // The hosted page posts from pipedream.com; ignore everything else.
+ if (!String(event.origin).endsWith('pipedream.com')) return;
+ const data = event.data as
+ | { type?: string; authProvisionId?: string; error?: string }
+ | undefined;
+ switch (data?.type) {
+ case 'success':
+ if (data.authProvisionId) {
+ options.onEvent({ type: 'success', accountId: data.authProvisionId });
+ }
+ break;
+ case 'error':
+ options.onEvent({ type: 'error', error: data.error });
+ break;
+ case 'close':
+ cleanup();
+ options.onEvent({ type: 'close' });
+ break;
+ default:
+ break;
+ }
+ };
+
+ window.addEventListener('message', onMessage);
+ document.body.appendChild(iframe);
+
+ return { close: cleanup };
+}
diff --git a/apps/web/src/lib/core/pipedream/flag.ts b/apps/web/src/lib/core/pipedream/flag.ts
new file mode 100644
index 0000000000..1fd664b389
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/flag.ts
@@ -0,0 +1,17 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import type { Accessor } from 'solid-js';
+
+/**
+ * PostHog feature flag switching the MCP connector frontend from the native
+ * stack (in-house OAuth, `/mcp/servers*`) to the Pipedream stack
+ * (`/pipedream/mcp/*`). Frontend-only: the backend serves both stacks
+ * unconditionally and picks a user's toolset by what they've connected
+ * (Pipedream connectors win — see the `mcp_select` crate).
+ */
+export const PIPEDREAM_MCP_FLAG = 'pipedream-mcp';
+
+/** Whether this user sees the Pipedream connector frontend. */
+export function usePipedreamMcpFlag(): Accessor<boolean> {
+ const flag = useFeatureFlag(PIPEDREAM_MCP_FLAG);
+ return () => flag().enabled;
+}
diff --git a/apps/web/src/lib/queries/pipedream-connectors.ts b/apps/web/src/lib/queries/pipedream-connectors.ts
new file mode 100644
index 0000000000..a7d6c62d40
--- /dev/null
+++ b/apps/web/src/lib/queries/pipedream-connectors.ts
@@ -0,0 +1,215 @@
+import { openPipedreamConnectUI } from '@core/pipedream/connect-ui';
+import { ThrownResultError, throwOnErr } from '@core/util/result';
+import { queryClient } from '@queries/client';
+import {
+ cognitionApiServiceClient,
+ PIPEDREAM_DISABLED,
+ type PipedreamCatalogResponse,
+ type PipedreamConnectionResponse,
+ type PipedreamUpdateRequest,
+} from '@service-cognition/client';
+import {
+ type InfiniteData,
+ useInfiniteQuery,
+ useMutation,
+ useQuery,
+} from '@tanstack/solid-query';
+
+const KEYS = {
+ all: ['pipedreamConnectors'] as const,
+ list: ['pipedreamConnectors', 'list'] as const,
+ catalog: (search: string) =>
+ ['pipedreamConnectors', 'catalog', search] as const,
+};
+
+/** Stable placeholder for `neverSuspend` consumers (see below). */
+const NO_CONNECTIONS: PipedreamConnectionResponse[] = [];
+
+export function usePipedreamConnectionsQuery(options?: {
+ /**
+ * Poll for connection changes. Connecting finishes in the Connect UI
+ * iframe, but other tabs never get a focus refetch — surfaces that must
+ * flip promptly (the setup connector cards) pass a short interval.
+ */
+ refetchInterval?: number;
+ /** See the same option on `useMcpServersQuery`. */
+ neverSuspend?: boolean;
+}) {
+ return useQuery(() => ({
+ queryKey: KEYS.list,
+ queryFn: async () =>
+ throwOnErr(
+ async () => await cognitionApiServiceClient.listPipedreamConnections()
+ ),
+ refetchOnMount: 'always' as const,
+ refetchOnWindowFocus: 'always' as const,
+ refetchInterval: options?.refetchInterval,
+ placeholderData: options?.neverSuspend ? NO_CONNECTIONS : undefined,
+ }));
+}
+
+/**
+ * Browse or search the Pipedream app catalog, paged by cursor. Curated
+ * priority connectors arrive first (flagged `priority`), followed by
+ * organic results from Pipedream's app directory.
+ */
+export function usePipedreamCatalogQuery(search: () => string) {
+ return useInfiniteQuery(() => ({
+ queryKey: KEYS.catalog(search().trim()),
+ queryFn: async ({ pageParam }: { pageParam: string | undefined }) =>
+ throwOnErr(
+ async () =>
+ await cognitionApiServiceClient.browsePipedreamCatalog({
+ search: search().trim() || undefined,
+ cursor: pageParam,
+ })
+ ),
+ initialPageParam: undefined as string | undefined,
+ getNextPageParam: (lastPage: PipedreamCatalogResponse) =>
+ lastPage.next_cursor ?? undefined,
+ staleTime: 5 * 60 * 1000,
+ // Serve the previous search's results (or nothing) instead of
+ // suspending: first load must not block the settings page on the
+ // directory, and keystrokes must not blank the list while refetching.
+ placeholderData: (
+ previous:
+ | InfiniteData<PipedreamCatalogResponse, string | undefined>
+ | undefined
+ ) => previous ?? { pages: [], pageParams: [] },
+ }));
+}
+
+function invalidateConnections() {
+ return queryClient.invalidateQueries({ queryKey: KEYS.list });
+}
+
+function upsertConnection(connection: PipedreamConnectionResponse) {
+ queryClient.setQueryData(
+ KEYS.list,
+ (current: PipedreamConnectionResponse[] | undefined) => {
+ if (!current) return [connection];
+ const index = current.findIndex(
+ (c) => c.app_slug === connection.app_slug
+ );
+ if (index === -1) return [...current, connection];
+ const next = [...current];
+ next[index] = connection;
+ return next;
+ }
+ );
+}
+
+function removeConnection(appSlug: string) {
+ queryClient.setQueryData(
+ KEYS.list,
+ (current: PipedreamConnectionResponse[] | undefined) =>
+ current?.filter((c) => c.app_slug !== appSlug) ?? current
+ );
+}
+
+export function useUpdatePipedreamConnectionMutation() {
+ return useMutation(() => ({
+ mutationFn: async (request: PipedreamUpdateRequest) =>
+ throwOnErr(
+ async () =>
+ await cognitionApiServiceClient.updatePipedreamConnection(request)
+ ),
+ onSuccess: async (connection: PipedreamConnectionResponse) => {
+ upsertConnection(connection);
+ await invalidateConnections();
+ },
+ }));
+}
+
+export function useDeletePipedreamConnectionMutation() {
+ return useMutation(() => ({
+ mutationFn: async (args: { app_slug: string }) =>
+ throwOnErr(
+ async () =>
+ await cognitionApiServiceClient.deletePipedreamConnection(args)
+ ),
+ onSuccess: async (_result: unknown, variables: { app_slug: string }) => {
+ removeConnection(variables.app_slug);
+ await invalidateConnections();
+ },
+ }));
+}
+
+export type PipedreamConnectOutcome = 'connected' | 'closed' | 'unsupported';
+
+// Whether the backend has Pipedream configured, learned from the first token
+// attempt (501 → unsupported). Cached so later connect clicks on an
+// unconfigured deployment fail fast instead of re-probing.
+let pipedreamUnsupported = false;
+
+/**
+ * Connect an MCP app through Pipedream's hosted Connect UI.
+ *
+ * Mints a Connect token (Pipedream owns the consent flow, credential
+ * storage, and refresh), opens the hosted Connect UI in a fullscreen
+ * iframe, and — once the user authorizes — registers the resulting account
+ * with our backend, which verifies ownership against Pipedream before
+ * storing it.
+ *
+ * Resolves `'connected'` on success (connections cache already refreshed),
+ * `'closed'` when the user dismissed the UI without finishing, and
+ * `'unsupported'` when the deployment has no Pipedream configured. Rejects
+ * on errors.
+ */
+export async function connectPipedreamApp(args: {
+ /** The Pipedream app to connect, by name slug (e.g. `linear`). */
+ appSlug: string;
+ /** Display name stored on the connection row. */
+ serverName?: string;
+}): Promise<PipedreamConnectOutcome> {
+ if (pipedreamUnsupported) return 'unsupported';
+
+ const token = await cognitionApiServiceClient.createPipedreamToken();
+ if (token.isErr()) {
+ if (token.error.some((e) => e.code === PIPEDREAM_DISABLED)) {
+ pipedreamUnsupported = true;
+ return 'unsupported';
+ }
+ throw new ThrownResultError(token.error);
+ }
+
+ return await new Promise<PipedreamConnectOutcome>((resolve, reject) => {
+ let settled = false;
+ const ui = openPipedreamConnectUI({
+ token: token.value.token,
+ app: args.appSlug,
+ onEvent: (event) => {
+ if (event.type === 'success' && !settled) {
+ settled = true;
+ void (async () => {
+ try {
+ const connection = await throwOnErr(
+ async () =>
+ await cognitionApiServiceClient.completePipedreamConnection({
+ account_id: event.accountId,
+ server_name: args.serverName,
+ })
+ );
+ upsertConnection(connection);
+ await invalidateConnections();
+ resolve('connected');
+ } catch (error) {
+ reject(
+ error instanceof Error
+ ? error
+ : new Error('failed to register Pipedream connection')
+ );
+ } finally {
+ ui.close();
+ }
+ })();
+ } else if (event.type === 'close' && !settled) {
+ settled = true;
+ resolve('closed');
+ }
+ // 'error' events are shown inside the Connect UI itself; the user
+ // can retry there or close, so they don't settle the promise.
+ },
+ });
+ });
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/client.ts b/apps/web/src/lib/service-clients/service-cognition/client.ts
index 0383e72bf9..c94b863f1f 100644
--- a/apps/web/src/lib/service-clients/service-cognition/client.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/client.ts
@@ -67,6 +67,43 @@ type Success = { success: boolean };
type IdMappingResponse = { target_id: string | null };
+// Hand-written mirrors of the DCS OpenAPI types for the Pipedream MCP
+// connector endpoints (`/pipedream/mcp/*`); replace with the orval-generated
+// schemas on the next client regeneration.
+export type PipedreamConnectionResponse = {
+ app_slug: string;
+ server_name: string;
+ enabled: boolean;
+};
+export type PipedreamUpdateRequest = {
+ app_slug: string;
+ server_name?: string;
+ enabled?: boolean;
+};
+export type PipedreamTokenResponse = {
+ token: string;
+ expires_at: string;
+ connect_link_url: string;
+};
+export type PipedreamCompleteRequest = {
+ account_id: string;
+ server_name?: string;
+};
+export type PipedreamCatalogEntryResponse = {
+ app_slug: string;
+ display_name: string;
+ description?: string | null;
+ icon_url?: string | null;
+ priority: boolean;
+};
+export type PipedreamCatalogResponse = {
+ servers: PipedreamCatalogEntryResponse[];
+ next_cursor?: string | null;
+};
+
+/** Error code for deployments where Pipedream MCP connect is not configured. */
+export const PIPEDREAM_DISABLED = 'PIPEDREAM_DISABLED' as const;
+
export const cognitionApiServiceClient = {
/** Creates a mapping from source_id to target_id */
async createIdMapping(args: { source_id: string; target_id: string }) {
@@ -359,6 +396,99 @@ export const cognitionApiServiceClient = {
).map((result) => result);
},
+ async listPipedreamConnections() {
+ return (
+ await dcsFetch<PipedreamConnectionResponse[]>(
+ `/pipedream/mcp/connections`,
+ {
+ method: 'GET',
+ }
+ )
+ ).map((result) => result);
+ },
+
+ async updatePipedreamConnection(args: PipedreamUpdateRequest) {
+ return (
+ await dcsFetch<PipedreamConnectionResponse>(
+ `/pipedream/mcp/connections`,
+ {
+ method: 'PUT',
+ body: JSON.stringify(args),
+ }
+ )
+ ).map((result) => result);
+ },
+
+ async deletePipedreamConnection(args: { app_slug: string }) {
+ return await dcsFetch(
+ `/pipedream/mcp/connections?app_slug=${encodeURIComponent(args.app_slug)}`,
+ { method: 'DELETE' }
+ );
+ },
+
+ /**
+ * Create a Pipedream Connect token for authorizing an MCP connector.
+ * Answers with the {@link PIPEDREAM_DISABLED} error code on deployments
+ * where Pipedream isn't configured (HTTP 501).
+ */
+ async createPipedreamToken() {
+ return (
+ await fetchWithToken<PipedreamTokenResponse, typeof PIPEDREAM_DISABLED>(
+ `${dcsHost}/pipedream/mcp/token`,
+ {
+ method: 'POST',
+ body: JSON.stringify({}),
+ errorResponseHandler: async (response) => {
+ if (response.status === 501) {
+ return {
+ code: PIPEDREAM_DISABLED,
+ message: 'Pipedream is not configured for this deployment',
+ };
+ }
+ return {
+ code: 'HTTP_ERROR',
+ message: `HTTP error! status: ${response.status}`,
+ };
+ },
+ }
+ )
+ ).map((result) => result);
+ },
+
+ /** Register a connected account reported by the Pipedream Connect UI. */
+ async completePipedreamConnection(args: PipedreamCompleteRequest) {
+ return (
+ await dcsFetch<PipedreamConnectionResponse>(`/pipedream/mcp/complete`, {
+ method: 'POST',
+ body: JSON.stringify(args),
+ })
+ ).map((result) => result);
+ },
+
+ /**
+ * Browse or search the Pipedream app catalog. Curated priority connectors
+ * come first (flagged `priority`), followed by directory results.
+ */
+ async browsePipedreamCatalog(args: {
+ search?: string;
+ cursor?: string;
+ limit?: number;
+ }) {
+ const params = new URLSearchParams();
+ if (args.search) params.set('search', args.search);
+ if (args.cursor) params.set('cursor', args.cursor);
+ if (args.limit) params.set('limit', String(args.limit));
+ const query = params.size > 0 ? `?${params}` : '';
+ return (
+ await dcsFetch<PipedreamCatalogResponse>(
+ `/pipedream/mcp/catalog${query}`,
+ {
+ method: 'GET',
+ }
+ )
+ ).map((result) => result);
+ },
+
async structuredCompletion(args: StructuredCompletionRequest) {
return (
await dcsFetch<StructuredCompletionResponse>(`/structured-completion`, {
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
index 1641be37f8..236125934e 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/client.ts
@@ -6,6 +6,7 @@
*/
import type {
AddServerRequest,
+ BrowsePipedreamMcpCatalogParams,
CallToolRequest,
CallToolResponse,
ChatHistory,
@@ -14,6 +15,7 @@ import type {
CompleteOnboardingRequest,
CreateChatRequest,
DeleteMcpServerParams,
+ DeletePipedreamMcpConnectionParams,
DocumentTextPart,
ErrorBody,
ErrorResponse,
@@ -29,6 +31,11 @@ import type {
OnboardingRow,
OnboardingState,
PatchChatRequest,
+ PipedreamCatalogResponse,
+ PipedreamCompleteRequest,
+ PipedreamConnectionResponse,
+ PipedreamTokenResponse,
+ PipedreamUpdateRequest,
ProjectionStateResponse,
RejectToolCallRequest,
RunImportOutcome,
@@ -1921,6 +1928,420 @@ export const completeHandler = async (
} as completeHandlerResponse;
};
+/**
+ * Curated priority connectors come first (flagged `priority`), followed by
+results from Pipedream's app directory.
+ * @summary Browse or search the catalog of connectable apps.
+ */
+export type browsePipedreamMcpCatalogResponse200 = {
+ data: PipedreamCatalogResponse;
+ status: 200;
+};
+
+export type browsePipedreamMcpCatalogResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type browsePipedreamMcpCatalogResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type browsePipedreamMcpCatalogResponse501 = {
+ data: ErrorResponse;
+ status: 501;
+};
+
+export type browsePipedreamMcpCatalogResponseSuccess =
+ browsePipedreamMcpCatalogResponse200 & {
+ headers: Headers;
+ };
+export type browsePipedreamMcpCatalogResponseError = (
+ | browsePipedreamMcpCatalogResponse401
+ | browsePipedreamMcpCatalogResponse500
+ | browsePipedreamMcpCatalogResponse501
+) & {
+ headers: Headers;
+};
+
+export type browsePipedreamMcpCatalogResponse =
+ | browsePipedreamMcpCatalogResponseSuccess
+ | browsePipedreamMcpCatalogResponseError;
+
+export const getBrowsePipedreamMcpCatalogUrl = (
+ params?: BrowsePipedreamMcpCatalogParams
+) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/pipedream/mcp/catalog?${stringifiedParams}`
+ : `/pipedream/mcp/catalog`;
+};
+
+export const browsePipedreamMcpCatalog = async (
+ params?: BrowsePipedreamMcpCatalogParams,
+ options?: RequestInit
+): Promise<browsePipedreamMcpCatalogResponse> => {
+ const res = await fetch(getBrowsePipedreamMcpCatalogUrl(params), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: browsePipedreamMcpCatalogResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as browsePipedreamMcpCatalogResponse;
+};
+
+/**
+ * Verifies with Pipedream that the account exists and was connected for
+the authenticated user before persisting anything.
+ * @summary Register a connected account reported by the Pipedream Connect UI.
+ */
+export type completePipedreamMcpConnectionResponse200 = {
+ data: PipedreamConnectionResponse;
+ status: 200;
+};
+
+export type completePipedreamMcpConnectionResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type completePipedreamMcpConnectionResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type completePipedreamMcpConnectionResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type completePipedreamMcpConnectionResponse501 = {
+ data: ErrorResponse;
+ status: 501;
+};
+
+export type completePipedreamMcpConnectionResponseSuccess =
+ completePipedreamMcpConnectionResponse200 & {
+ headers: Headers;
+ };
+export type completePipedreamMcpConnectionResponseError = (
+ | completePipedreamMcpConnectionResponse401
+ | completePipedreamMcpConnectionResponse404
+ | completePipedreamMcpConnectionResponse500
+ | completePipedreamMcpConnectionResponse501
+) & {
+ headers: Headers;
+};
+
+export type completePipedreamMcpConnectionResponse =
+ | completePipedreamMcpConnectionResponseSuccess
+ | completePipedreamMcpConnectionResponseError;
+
+export const getCompletePipedreamMcpConnectionUrl = () => {
+ return `/pipedream/mcp/complete`;
+};
+
+export const completePipedreamMcpConnection = async (
+ pipedreamCompleteRequest: PipedreamCompleteRequest,
+ options?: RequestInit
+): Promise<completePipedreamMcpConnectionResponse> => {
+ const res = await fetch(getCompletePipedreamMcpConnectionUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(pipedreamCompleteRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: completePipedreamMcpConnectionResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as completePipedreamMcpConnectionResponse;
+};
+
+/**
+ * @summary List the MCP apps connected by the authenticated user.
+ */
+export type listPipedreamMcpConnectionsResponse200 = {
+ data: PipedreamConnectionResponse[];
+ status: 200;
+};
+
+export type listPipedreamMcpConnectionsResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type listPipedreamMcpConnectionsResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type listPipedreamMcpConnectionsResponseSuccess =
+ listPipedreamMcpConnectionsResponse200 & {
+ headers: Headers;
+ };
+export type listPipedreamMcpConnectionsResponseError = (
+ | listPipedreamMcpConnectionsResponse401
+ | listPipedreamMcpConnectionsResponse500
+) & {
+ headers: Headers;
+};
+
+export type listPipedreamMcpConnectionsResponse =
+ | listPipedreamMcpConnectionsResponseSuccess
+ | listPipedreamMcpConnectionsResponseError;
+
+export const getListPipedreamMcpConnectionsUrl = () => {
+ return `/pipedream/mcp/connections`;
+};
+
+export const listPipedreamMcpConnections = async (
+ options?: RequestInit
+): Promise<listPipedreamMcpConnectionsResponse> => {
+ const res = await fetch(getListPipedreamMcpConnectionsUrl(), {
+ ...options,
+ method: 'GET',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: listPipedreamMcpConnectionsResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as listPipedreamMcpConnectionsResponse;
+};
+
+/**
+ * @summary Rename or enable/disable a connected app.
+ */
+export type updatePipedreamMcpConnectionResponse200 = {
+ data: PipedreamConnectionResponse;
+ status: 200;
+};
+
+export type updatePipedreamMcpConnectionResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type updatePipedreamMcpConnectionResponse404 = {
+ data: ErrorResponse;
+ status: 404;
+};
+
+export type updatePipedreamMcpConnectionResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type updatePipedreamMcpConnectionResponseSuccess =
+ updatePipedreamMcpConnectionResponse200 & {
+ headers: Headers;
+ };
+export type updatePipedreamMcpConnectionResponseError = (
+ | updatePipedreamMcpConnectionResponse401
+ | updatePipedreamMcpConnectionResponse404
+ | updatePipedreamMcpConnectionResponse500
+) & {
+ headers: Headers;
+};
+
+export type updatePipedreamMcpConnectionResponse =
+ | updatePipedreamMcpConnectionResponseSuccess
+ | updatePipedreamMcpConnectionResponseError;
+
+export const getUpdatePipedreamMcpConnectionUrl = () => {
+ return `/pipedream/mcp/connections`;
+};
+
+export const updatePipedreamMcpConnection = async (
+ pipedreamUpdateRequest: PipedreamUpdateRequest,
+ options?: RequestInit
+): Promise<updatePipedreamMcpConnectionResponse> => {
+ const res = await fetch(getUpdatePipedreamMcpConnectionUrl(), {
+ ...options,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(pipedreamUpdateRequest),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: updatePipedreamMcpConnectionResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as updatePipedreamMcpConnectionResponse;
+};
+
+/**
+ * @summary Disconnect an app, revoking its Pipedream account.
+ */
+export type deletePipedreamMcpConnectionResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type deletePipedreamMcpConnectionResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type deletePipedreamMcpConnectionResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type deletePipedreamMcpConnectionResponseSuccess =
+ deletePipedreamMcpConnectionResponse204 & {
+ headers: Headers;
+ };
+export type deletePipedreamMcpConnectionResponseError = (
+ | deletePipedreamMcpConnectionResponse401
+ | deletePipedreamMcpConnectionResponse500
+) & {
+ headers: Headers;
+};
+
+export type deletePipedreamMcpConnectionResponse =
+ | deletePipedreamMcpConnectionResponseSuccess
+ | deletePipedreamMcpConnectionResponseError;
+
+export const getDeletePipedreamMcpConnectionUrl = (
+ params: DeletePipedreamMcpConnectionParams
+) => {
+ const normalizedParams = new URLSearchParams();
+
+ Object.entries(params || {}).forEach(([key, value]) => {
+ if (value !== undefined) {
+ normalizedParams.append(key, value === null ? 'null' : value.toString());
+ }
+ });
+
+ const stringifiedParams = normalizedParams.toString();
+
+ return stringifiedParams.length > 0
+ ? `/pipedream/mcp/connections?${stringifiedParams}`
+ : `/pipedream/mcp/connections`;
+};
+
+export const deletePipedreamMcpConnection = async (
+ params: DeletePipedreamMcpConnectionParams,
+ options?: RequestInit
+): Promise<deletePipedreamMcpConnectionResponse> => {
+ const res = await fetch(getDeletePipedreamMcpConnectionUrl(params), {
+ ...options,
+ method: 'DELETE',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: deletePipedreamMcpConnectionResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as deletePipedreamMcpConnectionResponse;
+};
+
+/**
+ * The frontend opens Pipedream's hosted Connect UI with this token; the
+user picks (or is deep-linked into) an app and authorizes it there.
+ * @summary Create a short-lived Pipedream Connect token for the authenticated user.
+ */
+export type createPipedreamMcpTokenResponse200 = {
+ data: PipedreamTokenResponse;
+ status: 200;
+};
+
+export type createPipedreamMcpTokenResponse401 = {
+ data: string;
+ status: 401;
+};
+
+export type createPipedreamMcpTokenResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type createPipedreamMcpTokenResponse501 = {
+ data: ErrorResponse;
+ status: 501;
+};
+
+export type createPipedreamMcpTokenResponseSuccess =
+ createPipedreamMcpTokenResponse200 & {
+ headers: Headers;
+ };
+export type createPipedreamMcpTokenResponseError = (
+ | createPipedreamMcpTokenResponse401
+ | createPipedreamMcpTokenResponse500
+ | createPipedreamMcpTokenResponse501
+) & {
+ headers: Headers;
+};
+
+export type createPipedreamMcpTokenResponse =
+ | createPipedreamMcpTokenResponseSuccess
+ | createPipedreamMcpTokenResponseError;
+
+export const getCreatePipedreamMcpTokenUrl = () => {
+ return `/pipedream/mcp/token`;
+};
+
+export const createPipedreamMcpToken = async (
+ options?: RequestInit
+): Promise<createPipedreamMcpTokenResponse> => {
+ const res = await fetch(getCreatePipedreamMcpTokenUrl(), {
+ ...options,
+ method: 'POST',
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: createPipedreamMcpTokenResponse['data'] = body
+ ? JSON.parse(body)
+ : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as createPipedreamMcpTokenResponse;
+};
+
export type getBatchPreviewResponse200 = {
data: GetBatchPreviewResponse;
status: 200;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/browsePipedreamMcpCatalogParams.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/browsePipedreamMcpCatalogParams.ts
new file mode 100644
index 0000000000..18ac036499
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/browsePipedreamMcpCatalogParams.ts
@@ -0,0 +1,22 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+export type BrowsePipedreamMcpCatalogParams = {
+ /**
+ * Search query to filter apps by name. Omit to browse.
+ */
+ search?: string;
+ /**
+ * Opaque pagination cursor from a previous response.
+ */
+ cursor?: string;
+ /**
+ * Page size (default 20, max 50).
+ * @minimum 0
+ */
+ limit?: number;
+};
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/deletePipedreamMcpConnectionParams.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/deletePipedreamMcpConnectionParams.ts
new file mode 100644
index 0000000000..9821dadb9f
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/deletePipedreamMcpConnectionParams.ts
@@ -0,0 +1,13 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+export type DeletePipedreamMcpConnectionParams = {
+ /**
+ * The app slug to disconnect.
+ */
+ app_slug: string;
+};
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
index b906a1c707..03b7aa10b6 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/index.ts
@@ -34,6 +34,7 @@ export * from './attachmentMetadataOneOfThree';
export * from './attachmentMetadataOneOfThreeType';
export * from './attachmentMetadataOneOfType';
export * from './attachmentType';
+export * from './browsePipedreamMcpCatalogParams';
export * from './callToolRequest';
export * from './callToolResponse';
export * from './channelSharePermission';
@@ -92,6 +93,7 @@ export * from './createChatRequest';
export * from './createChatRequestName';
export * from './createChatRequestProjectId';
export * from './deleteMcpServerParams';
+export * from './deletePipedreamMcpConnectionParams';
export * from './documentCognitionServiceApiVersion';
export * from './documentReference';
export * from './documentReferenceOneOf';
@@ -162,6 +164,18 @@ export * from './patchChatRequest';
export * from './patchChatRequestName';
export * from './patchChatRequestProjectId';
export * from './patchChatRequestSharePermission';
+export * from './pipedreamCatalogEntryResponse';
+export * from './pipedreamCatalogEntryResponseDescription';
+export * from './pipedreamCatalogEntryResponseIconUrl';
+export * from './pipedreamCatalogResponse';
+export * from './pipedreamCatalogResponseNextCursor';
+export * from './pipedreamCompleteRequest';
+export * from './pipedreamCompleteRequestServerName';
+export * from './pipedreamConnectionResponse';
+export * from './pipedreamTokenResponse';
+export * from './pipedreamUpdateRequest';
+export * from './pipedreamUpdateRequestEnabled';
+export * from './pipedreamUpdateRequestServerName';
export * from './price';
export * from './projectionStateResponse';
export * from './projectionStateResponseData';
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogEntryResponse.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogEntryResponse.ts
new file mode 100644
index 0000000000..9d9cbe5c70
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogEntryResponse.ts
@@ -0,0 +1,25 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { PipedreamCatalogEntryResponseDescription } from './pipedreamCatalogEntryResponseDescription';
+import type { PipedreamCatalogEntryResponseIconUrl } from './pipedreamCatalogEntryResponseIconUrl';
+
+/**
+ * One connectable app in the catalog.
+ */
+export interface PipedreamCatalogEntryResponse {
+ /** Pipedream app name slug — pass this to the connect flow. */
+ app_slug: string;
+ /** One-line description of the app. */
+ description?: PipedreamCatalogEntryResponseDescription;
+ /** Human-readable name to display. */
+ display_name: string;
+ /** URL of the app's icon, when available. */
+ icon_url?: PipedreamCatalogEntryResponseIconUrl;
+ /** Curated priority connectors rank first and may be rendered as their
+own featured section. */
+ priority: boolean;
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogEntryResponseDescription.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogEntryResponseDescription.ts
new file mode 100644
index 0000000000..657750cffe
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogEntryResponseDescription.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * One-line description of the app.
+ */
+export type PipedreamCatalogEntryResponseDescription = string | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogEntryResponseIconUrl.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogEntryResponseIconUrl.ts
new file mode 100644
index 0000000000..9347602f1a
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogEntryResponseIconUrl.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * URL of the app's icon, when available.
+ */
+export type PipedreamCatalogEntryResponseIconUrl = string | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogResponse.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogResponse.ts
new file mode 100644
index 0000000000..6c0b4addc2
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogResponse.ts
@@ -0,0 +1,19 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+import type { PipedreamCatalogEntryResponse } from './pipedreamCatalogEntryResponse';
+import type { PipedreamCatalogResponseNextCursor } from './pipedreamCatalogResponseNextCursor';
+
+/**
+ * A page of the connector catalog.
+ */
+export interface PipedreamCatalogResponse {
+ /** Cursor for the next page. Absent on the last page. */
+ next_cursor?: PipedreamCatalogResponseNextCursor;
+ /** Catalog entries in display order (priority connectors first). */
+ servers: PipedreamCatalogEntryResponse[];
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogResponseNextCursor.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogResponseNextCursor.ts
new file mode 100644
index 0000000000..0a54a32119
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCatalogResponseNextCursor.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Cursor for the next page. Absent on the last page.
+ */
+export type PipedreamCatalogResponseNextCursor = string | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCompleteRequest.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCompleteRequest.ts
new file mode 100644
index 0000000000..0c0663ffaa
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCompleteRequest.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { PipedreamCompleteRequestServerName } from './pipedreamCompleteRequestServerName';
+
+/**
+ * Request body for completing a Pipedream connect flow.
+ */
+export interface PipedreamCompleteRequest {
+ /** The connected-account ID reported by the Connect UI on success. */
+ account_id: string;
+ /** Optional display name for the connector. Defaults to the app's name
+for new connections; existing connections keep their name. */
+ server_name?: PipedreamCompleteRequestServerName;
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCompleteRequestServerName.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCompleteRequestServerName.ts
new file mode 100644
index 0000000000..ba9d367143
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamCompleteRequestServerName.ts
@@ -0,0 +1,12 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Optional display name for the connector. Defaults to the app's name
+for new connections; existing connections keep their name.
+ */
+export type PipedreamCompleteRequestServerName = string | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamConnectionResponse.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamConnectionResponse.ts
new file mode 100644
index 0000000000..357b9dcb31
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamConnectionResponse.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * A connected MCP app as returned by the API.
+ */
+export interface PipedreamConnectionResponse {
+ /** Pipedream app name slug, e.g. `linear`. */
+ app_slug: string;
+ /** Whether the connector is enabled for tool use. */
+ enabled: boolean;
+ /** Human-readable display name. */
+ server_name: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponse.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponse.ts
new file mode 100644
index 0000000000..ba62a9e6b4
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponse.ts
@@ -0,0 +1,18 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Response from creating a Pipedream Connect token.
+ */
+export interface PipedreamTokenResponse {
+ /** Shareable link that opens the same connect flow in a browser tab. */
+ connect_link_url: string;
+ /** RFC 3339 expiry of the token. */
+ expires_at: string;
+ /** Short-lived token to open the Pipedream Connect UI with. */
+ token: string;
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamUpdateRequest.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamUpdateRequest.ts
new file mode 100644
index 0000000000..e524f82bc0
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamUpdateRequest.ts
@@ -0,0 +1,20 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+import type { PipedreamUpdateRequestEnabled } from './pipedreamUpdateRequestEnabled';
+import type { PipedreamUpdateRequestServerName } from './pipedreamUpdateRequestServerName';
+
+/**
+ * Request body for updating a connected app.
+ */
+export interface PipedreamUpdateRequest {
+ /** The app slug to update. */
+ app_slug: string;
+ /** Enable or disable the connector. */
+ enabled?: PipedreamUpdateRequestEnabled;
+ /** New display name for the connector. */
+ server_name?: PipedreamUpdateRequestServerName;
+}
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamUpdateRequestEnabled.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamUpdateRequestEnabled.ts
new file mode 100644
index 0000000000..a2f94b1ac7
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamUpdateRequestEnabled.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * Enable or disable the connector.
+ */
+export type PipedreamUpdateRequestEnabled = boolean | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamUpdateRequestServerName.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamUpdateRequestServerName.ts
new file mode 100644
index 0000000000..f151bb6427
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamUpdateRequestServerName.ts
@@ -0,0 +1,11 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * Document Cognition Service
+ * OpenAPI spec version: 1.0.0
+ */
+
+/**
+ * New display name for the connector.
+ */
+export type PipedreamUpdateRequestServerName = string | null;
diff --git a/apps/web/src/lib/service-clients/service-cognition/openapi.json b/apps/web/src/lib/service-clients/service-cognition/openapi.json
index 236f94b6d0..a0ddefaea7 100644
--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json
+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json
@@ -1562,6 +1562,347 @@
}
}
},
+ "/pipedream/mcp/catalog": {
+ "get": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Browse or search the catalog of connectable apps.",
+ "description": "Curated priority connectors come first (flagged `priority`), followed by\nresults from Pipedream's app directory.",
+ "operationId": "browse_pipedream_mcp_catalog",
+ "parameters": [
+ {
+ "name": "search",
+ "in": "query",
+ "description": "Search query to filter apps by name. Omit to browse.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "cursor",
+ "in": "query",
+ "description": "Opaque pagination cursor from a previous response.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "description": "Page size (default 20, max 50).",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamCatalogResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/pipedream/mcp/complete": {
+ "post": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Register a connected account reported by the Pipedream Connect UI.",
+ "description": "Verifies with Pipedream that the account exists and was connected for\nthe authenticated user before persisting anything.",
+ "operationId": "complete_pipedream_mcp_connection",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamCompleteRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamConnectionResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/pipedream/mcp/connections": {
+ "get": {
+ "tags": ["pipedream-mcp"],
+ "summary": "List the MCP apps connected by the authenticated user.",
+ "operationId": "list_pipedream_mcp_connections",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PipedreamConnectionResponse"
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Rename or enable/disable a connected app.",
+ "operationId": "update_pipedream_mcp_connection",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamUpdateRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamConnectionResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Disconnect an app, revoking its Pipedream account.",
+ "operationId": "delete_pipedream_mcp_connection",
+ "parameters": [
+ {
+ "name": "app_slug",
+ "in": "query",
+ "description": "The app slug to disconnect.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/pipedream/mcp/token": {
+ "post": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Create a short-lived Pipedream Connect token for the authenticated user.",
+ "description": "The frontend opens Pipedream's hosted Connect UI with this token; the\nuser picks (or is deep-linked into) an app and authorizes it there.",
+ "operationId": "create_pipedream_mcp_token",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamTokenResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/preview": {
"post": {
"tags": ["get_batch_preview"],
@@ -3625,6 +3966,123 @@
}
}
},
+ "PipedreamCatalogEntryResponse": {
+ "type": "object",
+ "description": "One connectable app in the catalog.",
+ "required": ["app_slug", "display_name", "priority"],
+ "properties": {
+ "app_slug": {
+ "type": "string",
+ "description": "Pipedream app name slug — pass this to the connect flow."
+ },
+ "description": {
+ "type": ["string", "null"],
+ "description": "One-line description of the app."
+ },
+ "display_name": {
+ "type": "string",
+ "description": "Human-readable name to display."
+ },
+ "icon_url": {
+ "type": ["string", "null"],
+ "description": "URL of the app's icon, when available."
+ },
+ "priority": {
+ "type": "boolean",
+ "description": "Curated priority connectors rank first and may be rendered as their\nown featured section."
+ }
+ }
+ },
+ "PipedreamCatalogResponse": {
+ "type": "object",
+ "description": "A page of the connector catalog.",
+ "required": ["servers"],
+ "properties": {
+ "next_cursor": {
+ "type": ["string", "null"],
+ "description": "Cursor for the next page. Absent on the last page."
+ },
+ "servers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PipedreamCatalogEntryResponse"
+ },
+ "description": "Catalog entries in display order (priority connectors first)."
+ }
+ }
+ },
+ "PipedreamCompleteRequest": {
+ "type": "object",
+ "description": "Request body for completing a Pipedream connect flow.",
+ "required": ["account_id"],
+ "properties": {
+ "account_id": {
+ "type": "string",
+ "description": "The connected-account ID reported by the Connect UI on success."
+ },
+ "server_name": {
+ "type": ["string", "null"],
+ "description": "Optional display name for the connector. Defaults to the app's name\nfor new connections; existing connections keep their name."
+ }
+ }
+ },
+ "PipedreamConnectionResponse": {
+ "type": "object",
+ "description": "A connected MCP app as returned by the API.",
+ "required": ["app_slug", "server_name", "enabled"],
+ "properties": {
+ "app_slug": {
+ "type": "string",
+ "description": "Pipedream app name slug, e.g. `linear`."
+ },
+ "enabled": {
+ "type": "boolean",
+ "description": "Whether the connector is enabled for tool use."
+ },
+ "server_name": {
+ "type": "string",
+ "description": "Human-readable display name."
+ }
+ }
+ },
+ "PipedreamTokenResponse": {
+ "type": "object",
+ "description": "Response from creating a Pipedream Connect token.",
+ "required": ["token", "expires_at", "connect_link_url"],
+ "properties": {
+ "connect_link_url": {
+ "type": "string",
+ "description": "Shareable link that opens the same connect flow in a browser tab."
+ },
+ "expires_at": {
+ "type": "string",
+ "description": "RFC 3339 expiry of the token."
+ },
+ "token": {
+ "type": "string",
+ "description": "Short-lived token to open the Pipedream Connect UI with."
+ }
+ }
+ },
+ "PipedreamUpdateRequest": {
+ "type": "object",
+ "description": "Request body for updating a connected app.",
+ "required": ["app_slug"],
+ "properties": {
+ "app_slug": {
+ "type": "string",
+ "description": "The app slug to update."
+ },
+ "enabled": {
+ "type": ["boolean", "null"],
+ "description": "Enable or disable the connector."
+ },
+ "server_name": {
+ "type": ["string", "null"],
+ "description": "New display name for the connector."
+ }
+ }
+ },
"Price": {
"type": "object",
"description": "Resolved price for one completion.",
diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.toml
index 451f6b014a..78fec9d0a9 100644
--- a/crates/ai_tools/Cargo.toml
+++ b/crates/ai_tools/Cargo.toml
@@ -51,6 +51,8 @@ macro_event_broker = { path = "../macro_event_broker" }
macro_queues = { path = "../macro_queues" }
macro_user_id = { path = "../macro_user_id" }
mcp_client = { path = "../mcp_client" }
+mcp_select = { path = "../mcp_select" }
+pipedream_mcp = { path = "../pipedream_mcp" }
model = { path = "../model" }
model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index 602944c139..53fedf6a0f 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -53,15 +53,16 @@ pub use tool_context::{
ToolCrmToolContext, ToolDocumentService, ToolDocumentToolContext, ToolEmailService,
ToolEmailToolContext, ToolEntityAccessManagementService, ToolEntityAccessService,
ToolEntityCreator, ToolForeignEntityService, ToolFrecencyService, ToolImportService,
- ToolImportToolContext, ToolNotificationQueue, ToolNotificationService,
- ToolNotificationToolContext, ToolProjectService, ToolProjectToolContext, ToolPropertiesService,
- ToolPropertiesToolContext, ToolServiceContext, ToolSkillService, ToolSkillToolContext,
- ToolSoupService, ToolSystemPropertiesService, ToolTeamService, ToolTeamToolContext,
- ToolUserEmailService, build_channel_tool_context_with_dispatcher,
- build_channel_tool_context_with_side_effects, build_channel_tool_context_without_side_effects,
- build_crm_tool_context, build_project_tool_context, build_properties_service,
- build_properties_tool_context, build_skill_tool_context, build_task_properties_adapter,
- build_team_repository, build_team_tool_context,
+ ToolImportToolContext, ToolMcpSelector, ToolNotificationQueue, ToolNotificationService,
+ ToolNotificationToolContext, ToolPipedreamConnection, ToolProjectService,
+ ToolProjectToolContext, ToolPropertiesService, ToolPropertiesToolContext, ToolServiceContext,
+ ToolSkillService, ToolSkillToolContext, ToolSoupService, ToolSystemPropertiesService,
+ ToolTeamService, ToolTeamToolContext, ToolUserEmailService,
+ build_channel_tool_context_with_dispatcher, build_channel_tool_context_with_side_effects,
+ build_channel_tool_context_without_side_effects, build_crm_tool_context,
+ build_project_tool_context, build_properties_service, build_properties_tool_context,
+ build_skill_tool_context, build_task_properties_adapter, build_team_repository,
+ build_team_tool_context,
};
pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 7ae2ca6f72..88755b1b10 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1087,10 +1087,25 @@ impl import::domain::ports::EntityCreator for ToolEntityCreator {
}
}
+/// Type alias for the import service implementation used by AI tools.
+/// The MCP connection to Pipedream's remote server: `None` on deployments
+/// where Pipedream isn't configured (its toolsets then come up empty).
+pub type ToolPipedreamConnection =
+ Option<std::sync::Arc<pipedream_mcp::outbound::api::PipedreamClient>>;
+
+/// The MCP stack selector wired to the concrete DCS stores: the native
+/// server store and the Pipedream connection store. Picks which stack
+/// serves a user's tools (Pipedream connectors win; see `mcp_select`).
+pub type ToolMcpSelector = mcp_select::McpToolSelector<
+ mcp_client::outbound::pg_server_repo::PgServerRepo,
+ pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,
+ ToolPipedreamConnection,
+>;
+
/// Type alias for the import service implementation used by AI tools.
pub type ToolImportService = import::domain::service::ImportServiceImpl<
import::outbound::pg_import_repo::PgImportRepo,
- mcp_client::outbound::pg_server_repo::PgServerRepo,
+ ToolMcpSelector,
ToolEntityCreator,
>;
diff --git a/crates/import/Cargo.toml b/crates/import/Cargo.toml
index 6ef5c29a46..d818e85982 100644
--- a/crates/import/Cargo.toml
+++ b/crates/import/Cargo.toml
@@ -19,7 +19,7 @@ macro_authorization = { path = "../macro_authorization", default-features = fals
"axum",
] }
macro_user_id = { path = "../macro_user_id" }
-mcp_client = { path = "../mcp_client" }
+mcp_select = { path = "../mcp_select" }
model-entity = { path = "../model-entity" }
models_properties = { path = "../models_properties" }
properties = { path = "../properties", default-features = false, features = [
diff --git a/crates/import/src/domain/models.rs b/crates/import/src/domain/models.rs
index 57786d3c06..3f65f9b462 100644
--- a/crates/import/src/domain/models.rs
+++ b/crates/import/src/domain/models.rs
@@ -48,6 +48,23 @@ impl ImportSource {
]
}
+ /// The Pipedream app slug backing this source's connector.
+ pub fn pipedream_app_slug(self) -> &'static str {
+ match self {
+ ImportSource::Linear => "linear",
+ ImportSource::Notion => "notion",
+ ImportSource::Slack => "slack",
+ }
+ }
+
+ /// This source's connector on both MCP stacks.
+ pub fn connector_ref(self) -> mcp_select::ConnectorRef<'static> {
+ mcp_select::ConnectorRef {
+ pipedream_app_slug: self.pipedream_app_slug(),
+ native_server_url: self.mcp_server_url(),
+ }
+ }
+
/// The MCP server URL backing this source's connector.
pub fn mcp_server_url(self) -> &'static str {
match self {
diff --git a/crates/import/src/domain/service.rs b/crates/import/src/domain/service.rs
index 594ed1ae37..e94b419789 100644
--- a/crates/import/src/domain/service.rs
+++ b/crates/import/src/domain/service.rs
@@ -24,9 +24,7 @@ use agent::{AgentLoop, PredefinedModel};
use ai_toolset::{RequestContext, ToolResult, ToolSet, ToolSetError};
use futures::StreamExt;
use macro_user_id::user_id::MacroUserIdStr;
-use mcp_client::domain::models::McpServerRecord;
-use mcp_client::domain::ports::McpServerStore;
-use mcp_client::domain::service::McpToolSet;
+use mcp_select::{ConnectorSelect, UserMcpTools};
use std::collections::HashSet;
use std::pin::Pin;
use std::sync::Arc;
@@ -304,7 +302,7 @@ pub trait NotionPageImporter: Send + Sync + 'static {
/// entity creator, and usage recording together.
pub struct ImportServiceImpl<R, S, C> {
repo: R,
- mcp_store: Arc<S>,
+ mcp_tools: Arc<S>,
creator: Arc<C>,
recorder: Arc<dyn ai_usage::UsageRecorder>,
notifier: Option<ImportNotify>,
@@ -314,7 +312,7 @@ impl<R: Clone, S, C> Clone for ImportServiceImpl<R, S, C> {
fn clone(&self) -> Self {
Self {
repo: self.repo.clone(),
- mcp_store: self.mcp_store.clone(),
+ mcp_tools: self.mcp_tools.clone(),
creator: self.creator.clone(),
recorder: self.recorder.clone(),
notifier: self.notifier.clone(),
@@ -326,13 +324,13 @@ impl<R, S, C> ImportServiceImpl<R, S, C> {
/// Build the orchestrator.
pub fn new(
repo: R,
- mcp_store: Arc<S>,
+ mcp_tools: Arc<S>,
creator: Arc<C>,
recorder: Arc<dyn ai_usage::UsageRecorder>,
) -> Self {
Self {
repo,
- mcp_store,
+ mcp_tools,
creator,
recorder,
notifier: None,
@@ -355,7 +353,7 @@ impl<R, S, C> ImportServiceImpl<R, S, C> {
impl<R, S, C> ImportServiceImpl<R, S, C>
where
R: ImportRepo + Clone,
- S: McpServerStore,
+ S: ConnectorSelect,
C: EntityCreator,
{
/// Spawn the gather session for one source; finishes the run row either
@@ -492,7 +490,7 @@ where
user: &MacroUserIdStr<'static>,
source: ImportSource,
model: &str,
- mcp_tools: Arc<McpToolSet>,
+ mcp_tools: Arc<UserMcpTools>,
) -> anyhow::Result<()> {
let native = gather_toolset::<Self>();
let toolset = NativePlusMcp::new(native, mcp_tools);
@@ -522,7 +520,7 @@ where
async fn import_notion_page_direct(
&self,
user: &MacroUserIdStr<'static>,
- mcp_tools: &McpToolSet,
+ mcp_tools: &UserMcpTools,
row: &ImportEntity,
) -> anyhow::Result<()> {
let fetch_tool = notion_fetch_tool_name(mcp_tools)
@@ -579,7 +577,7 @@ where
async fn connector_tool_call(
&self,
user: &MacroUserIdStr<'static>,
- mcp_tools: &McpToolSet,
+ mcp_tools: &UserMcpTools,
tool_name: &str,
arguments: &serde_json::Value,
) -> anyhow::Result<serde_json::Value> {
@@ -606,7 +604,7 @@ where
async fn gather_slack_direct(
&self,
user: &MacroUserIdStr<'static>,
- mcp_tools: &McpToolSet,
+ mcp_tools: &UserMcpTools,
) -> anyhow::Result<usize> {
let search_tool = slack_channel_search_tool_name(mcp_tools)
.ok_or_else(|| anyhow::anyhow!("connector exposes no channel-search tool"))?;
@@ -691,7 +689,7 @@ where
&self,
user: &MacroUserIdStr<'static>,
rows: &[ImportEntity],
- mcp_tools: Arc<McpToolSet>,
+ mcp_tools: Arc<UserMcpTools>,
) -> anyhow::Result<()> {
let native = notion_import_toolset::<Self>();
let toolset = NativePlusMcp::new(native, mcp_tools);
@@ -718,19 +716,12 @@ where
&self,
user: &MacroUserIdStr<'static>,
source: ImportSource,
- ) -> anyhow::Result<Arc<McpToolSet>> {
- let url = source.mcp_server_url();
- let records: Vec<McpServerRecord> = self
- .mcp_store
- .list(user)
- .await
- .map_err(|e| anyhow::anyhow!("mcp store: {e:?}"))?
- .into_iter()
- .filter(|r| r.url == url)
- .collect();
- anyhow::ensure!(!records.is_empty(), "no {} connection", source.as_ref());
-
- let mcp_tools = McpToolSet::new(&records, self.mcp_store.clone()).await;
+ ) -> anyhow::Result<Arc<UserMcpTools>> {
+ let mcp_tools = self
+ .mcp_tools
+ .connector_toolset(user, source.connector_ref())
+ .await?
+ .ok_or_else(|| anyhow::anyhow!("no {} connection", source.as_ref()))?;
anyhow::ensure!(
!mcp_tools.is_empty(),
"could not load tools from {}",
@@ -874,7 +865,7 @@ where
async fn process_notion_page(
&self,
user: &MacroUserIdStr<'static>,
- mcp_tools: Arc<McpToolSet>,
+ mcp_tools: Arc<UserMcpTools>,
row: &ImportEntity,
) -> anyhow::Result<()> {
let outcome = tokio::time::timeout(NOTION_PAGE_IMPORT_TIMEOUT, async {
@@ -993,7 +984,7 @@ where
impl<R, S, C> ImportService for ImportServiceImpl<R, S, C>
where
R: ImportRepo + Clone,
- S: McpServerStore,
+ S: ConnectorSelect,
C: EntityCreator,
{
#[tracing::instrument(skip(self, user), err)]
@@ -1171,7 +1162,7 @@ where
impl<R, S, C> ImportStager for ImportServiceImpl<R, S, C>
where
R: ImportRepo + Clone,
- S: McpServerStore,
+ S: ConnectorSelect,
C: EntityCreator,
{
#[tracing::instrument(skip(self, user, metadata), err)]
@@ -1314,7 +1305,7 @@ where
impl<R, S, C> NotionPageImporter for ImportServiceImpl<R, S, C>
where
R: ImportRepo + Clone,
- S: McpServerStore,
+ S: ConnectorSelect,
C: EntityCreator,
{
#[tracing::instrument(skip(self, user), fields(page = page_url_or_id), err)]
@@ -1444,7 +1435,7 @@ where
impl<R, S, C> ImportFinalizer for ImportServiceImpl<R, S, C>
where
R: ImportRepo + Clone,
- S: McpServerStore,
+ S: ConnectorSelect,
C: EntityCreator,
{
#[tracing::instrument(skip(self, user, content_markdown), err)]
@@ -1510,7 +1501,7 @@ where
/// The mangled name of the connector's Notion fetch tool. Notion exposes this
/// as `notion-fetch` generally and as `fetch` on OpenAI-compatible surfaces.
-fn notion_fetch_tool_name(mcp_tools: &McpToolSet) -> Option<String> {
+fn notion_fetch_tool_name(mcp_tools: &UserMcpTools) -> Option<String> {
ToolSet::<()>::request_schemas(mcp_tools)?
.into_iter()
.map(|schema| schema.name)
@@ -1527,7 +1518,7 @@ fn is_notion_fetch_tool_name(name: &str) -> bool {
/// The mangled name of the connector's channel-search tool. Slack's hosted
/// MCP has shipped several tool-name spellings, so this matches the shape —
/// a search/list over channels — rather than one literal name.
-fn slack_channel_search_tool_name(mcp_tools: &McpToolSet) -> Option<String> {
+fn slack_channel_search_tool_name(mcp_tools: &UserMcpTools) -> Option<String> {
ToolSet::<()>::request_schemas(mcp_tools)?
.into_iter()
.map(|schema| schema.name)
@@ -2718,11 +2709,11 @@ impl Drop for AbortOnDrop {
struct NativePlusMcp<Context> {
native: ai_toolset::AsyncToolCollection<Context>,
native_names: HashSet<String>,
- mcp: Arc<McpToolSet>,
+ mcp: Arc<UserMcpTools>,
}
impl<Context: Send + Sync + 'static> NativePlusMcp<Context> {
- fn new(native: ai_toolset::AsyncToolCollection<Context>, mcp: Arc<McpToolSet>) -> Self {
+ fn new(native: ai_toolset::AsyncToolCollection<Context>, mcp: Arc<UserMcpTools>) -> Self {
let native_names = native
.request_schemas()
.unwrap_or_default()
diff --git a/crates/macro_db_client/migrations/20260811160239_create_pipedream_mcp_connections.sql b/crates/macro_db_client/migrations/20260811160239_create_pipedream_mcp_connections.sql
new file mode 100644
index 0000000000..3cf53d7a7e
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260811160239_create_pipedream_mcp_connections.sql
@@ -0,0 +1,14 @@
+-- Pipedream-managed MCP connectors, fully separate from the mcp_servers
+-- table used by the native in-house OAuth stack. Pipedream owns
+-- the OAuth grants and tokens; we store only which app a user connected and
+-- the Pipedream connected-account ID the grant lives under.
+CREATE TABLE pipedream_mcp_connections (
+ user_id TEXT NOT NULL,
+ app_slug TEXT NOT NULL,
+ server_name TEXT NOT NULL,
+ account_id TEXT NOT NULL,
+ enabled BOOLEAN NOT NULL DEFAULT TRUE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (user_id, app_slug)
+);
diff --git a/crates/mcp_client/src/domain/service/toolset.rs b/crates/mcp_client/src/domain/service/toolset.rs
index ea1a3123c9..487790d886 100644
--- a/crates/mcp_client/src/domain/service/toolset.rs
+++ b/crates/mcp_client/src/domain/service/toolset.rs
@@ -142,6 +142,12 @@ impl McpToolSet {
self.tools.is_empty()
}
+ /// The full catalog of MCP tools, public for hosts that compose this
+ /// toolset outside [`CombinedToolSet`] (see the `mcp_select` crate).
+ pub fn searchable_catalog(&self) -> Vec<SearchableTool> {
+ self.catalog()
+ }
+
/// The full catalog of MCP tools (mangled name + description + input schema)
/// for on-demand loading via tool search.
fn catalog(&self) -> Vec<SearchableTool> {
diff --git a/crates/mcp_select/Cargo.toml b/crates/mcp_select/Cargo.toml
new file mode 100644
index 0000000000..3b43394cab
--- /dev/null
+++ b/crates/mcp_select/Cargo.toml
@@ -0,0 +1,15 @@
+[package]
+name = "mcp_select"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+ai_toolset = { path = "../ai_toolset" }
+anyhow.workspace = true
+macro_user_id = { path = "../macro_user_id" }
+mcp_client = { path = "../mcp_client" }
+pipedream_mcp = { path = "../pipedream_mcp" }
+serde_json.workspace = true
+tracing.workspace = true
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/mcp_select/src/lib.rs b/crates/mcp_select/src/lib.rs
new file mode 100644
index 0000000000..e570bbc456
--- /dev/null
+++ b/crates/mcp_select/src/lib.rs
@@ -0,0 +1,335 @@
+#![deny(missing_docs)]
+//! Selection between the two MCP connector stacks.
+//!
+//! The native stack (`mcp_client`: in-house OAuth, servers connected
+//! by URL) and the Pipedream stack (`pipedream_mcp`: apps connected through
+//! Pipedream Connect) are deliberately separate — separate endpoints,
+//! tables, and toolsets. The one place they must meet is deciding which
+//! tools a user's agent actually gets. This crate owns that rule:
+//!
+//! 1. Load both stacks' connectors.
+//! 2. If the user has any Pipedream connectors, use only those.
+//! 3. Otherwise, use the native connectors.
+
+use ai_toolset::{
+ AsyncToolCollection, RequestContext, RequestSchema, SearchableTool, ToolInfo, ToolResult,
+ ToolSet, ToolSetError,
+};
+use macro_user_id::user_id::MacroUserIdStr;
+use mcp_client::domain::ports::McpServerStore;
+use mcp_client::domain::service::McpToolSet;
+use pipedream_mcp::domain::ports::{ConnectionStore, McpConnection};
+use pipedream_mcp::domain::service::PipedreamToolSet;
+use std::pin::Pin;
+use std::sync::Arc;
+
+/// Mangled MCP tool names start with this prefix on both stacks.
+const MANGLED_PREFIX: &str = "mcp__";
+
+/// A connector identified in both stacks: the Pipedream app slug and the
+/// native server URL that back the same product (e.g. `linear` /
+/// `https://mcp.linear.app/mcp`).
+#[derive(Clone, Copy, Debug)]
+pub struct ConnectorRef<'a> {
+ /// Pipedream app name slug, e.g. `linear`.
+ pub pipedream_app_slug: &'a str,
+ /// The native stack's MCP server URL for the same product.
+ pub native_server_url: &'a str,
+}
+
+/// The MCP tools loaded for a user — from exactly one stack, per the
+/// selection rule above.
+pub enum UserMcpTools {
+ /// Tools served by Pipedream's remote MCP server.
+ Pipedream(PipedreamToolSet),
+ /// Tools served by directly-connected (native) MCP servers.
+ Native(McpToolSet),
+}
+
+impl UserMcpTools {
+ /// Returns `true` when no tools were discovered.
+ pub fn is_empty(&self) -> bool {
+ match self {
+ UserMcpTools::Pipedream(tools) => tools.is_empty(),
+ UserMcpTools::Native(tools) => tools.is_empty(),
+ }
+ }
+
+ /// The full catalog of MCP tools for on-demand loading via tool search.
+ pub fn catalog(&self) -> Vec<SearchableTool> {
+ match self {
+ UserMcpTools::Pipedream(tools) => tools.searchable_catalog(),
+ UserMcpTools::Native(tools) => tools.searchable_catalog(),
+ }
+ }
+}
+
+impl<Context: Send + Sync + 'static> ToolSet<Context> for UserMcpTools {
+ fn try_tool_call<'a>(
+ &'a self,
+ context: Context,
+ request_context: RequestContext,
+ tool_name: &'a str,
+ json: &'a serde_json::Value,
+ ) -> Pin<
+ Box<dyn Future<Output = Result<ToolResult<serde_json::Value>, ToolSetError>> + 'a + Send>,
+ > {
+ match self {
+ UserMcpTools::Pipedream(tools) => {
+ tools.try_tool_call(context, request_context, tool_name, json)
+ }
+ UserMcpTools::Native(tools) => {
+ tools.try_tool_call(context, request_context, tool_name, json)
+ }
+ }
+ }
+
+ fn request_schemas(&self) -> Option<Vec<RequestSchema>> {
+ match self {
+ UserMcpTools::Pipedream(tools) => ToolSet::<Context>::request_schemas(tools),
+ UserMcpTools::Native(tools) => ToolSet::<Context>::request_schemas(tools),
+ }
+ }
+
+ fn searchable_toolset_names(&self) -> Vec<String> {
+ match self {
+ UserMcpTools::Pipedream(tools) => ToolSet::<Context>::searchable_toolset_names(tools),
+ UserMcpTools::Native(tools) => ToolSet::<Context>::searchable_toolset_names(tools),
+ }
+ }
+
+ fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ToolInfo> {
+ match self {
+ UserMcpTools::Pipedream(tools) => {
+ ToolSet::<Context>::routing_description(tools, tool_name)
+ }
+ UserMcpTools::Native(tools) => {
+ ToolSet::<Context>::routing_description(tools, tool_name)
+ }
+ }
+ }
+}
+
+/// Port for consumers (imports, onboarding) that need per-connector tools
+/// or connection state without knowing which stack serves them.
+pub trait ConnectorSelect: Send + Sync + 'static {
+ /// Load the user's full MCP toolset (all connectors, one stack).
+ fn user_toolset(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = UserMcpTools> + Send;
+
+ /// Load the toolset for one connector. `Ok(None)` when the user has it
+ /// connected on neither stack.
+ fn connector_toolset(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ connector: ConnectorRef<'_>,
+ ) -> impl Future<Output = anyhow::Result<Option<UserMcpTools>>> + Send;
+
+ /// Whether the user has this connector, on whichever stack the
+ /// selection rule picks for them.
+ fn connector_connected(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ connector: ConnectorRef<'_>,
+ ) -> impl Future<Output = anyhow::Result<bool>> + Send;
+}
+
+/// The concrete selector: loads both stacks' stores and applies the rule.
+pub struct McpToolSelector<N, P, C> {
+ native_store: Arc<N>,
+ pipedream_store: Arc<P>,
+ pipedream_connection: Arc<C>,
+}
+
+impl<N, P, C> Clone for McpToolSelector<N, P, C> {
+ fn clone(&self) -> Self {
+ Self {
+ native_store: self.native_store.clone(),
+ pipedream_store: self.pipedream_store.clone(),
+ pipedream_connection: self.pipedream_connection.clone(),
+ }
+ }
+}
+
+impl<N, P, C> McpToolSelector<N, P, C>
+where
+ N: McpServerStore,
+ P: ConnectionStore,
+ C: McpConnection,
+{
+ /// Build a selector over the native store and the Pipedream store +
+ /// remote MCP connection.
+ pub fn new(
+ native_store: Arc<N>,
+ pipedream_store: Arc<P>,
+ pipedream_connection: Arc<C>,
+ ) -> Self {
+ Self {
+ native_store,
+ pipedream_store,
+ pipedream_connection,
+ }
+ }
+
+ /// The user's Pipedream connections, or empty when the store errs
+ /// (an error must degrade to the native stack, not kill the request).
+ async fn pipedream_connections(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ ) -> Vec<pipedream_mcp::domain::models::PipedreamConnection> {
+ self.pipedream_store
+ .list(user)
+ .await
+ .inspect_err(|e| tracing::warn!(error = ?e, "failed to list Pipedream connections"))
+ .unwrap_or_default()
+ }
+}
+
+impl<N, P, C> ConnectorSelect for McpToolSelector<N, P, C>
+where
+ N: McpServerStore,
+ P: ConnectionStore,
+ C: McpConnection,
+{
+ #[tracing::instrument(skip_all)]
+ async fn user_toolset(&self, user: &MacroUserIdStr<'static>) -> UserMcpTools {
+ let pipedream = self.pipedream_connections(user).await;
+ if !pipedream.is_empty() {
+ return UserMcpTools::Pipedream(
+ PipedreamToolSet::new(&pipedream, self.pipedream_connection.clone()).await,
+ );
+ }
+
+ let native = self
+ .native_store
+ .list(user)
+ .await
+ .inspect_err(|e| tracing::warn!(error = ?e, "failed to list native MCP servers"))
+ .unwrap_or_default();
+ UserMcpTools::Native(McpToolSet::new(&native, self.native_store.clone()).await)
+ }
+
+ #[tracing::instrument(skip(self, user), err)]
+ async fn connector_toolset(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ connector: ConnectorRef<'_>,
+ ) -> anyhow::Result<Option<UserMcpTools>> {
+ let pipedream = self.pipedream_connections(user).await;
+ if !pipedream.is_empty() {
+ // The user is on the Pipedream stack: native connectors are
+ // ignored even if this particular app isn't connected there.
+ let matching: Vec<_> = pipedream
+ .into_iter()
+ .filter(|c| c.app_slug == connector.pipedream_app_slug)
+ .collect();
+ if matching.is_empty() {
+ return Ok(None);
+ }
+ return Ok(Some(UserMcpTools::Pipedream(
+ PipedreamToolSet::new(&matching, self.pipedream_connection.clone()).await,
+ )));
+ }
+
+ let matching: Vec<_> = self
+ .native_store
+ .list(user)
+ .await
+ .map_err(|e| anyhow::anyhow!("mcp store: {e:?}"))?
+ .into_iter()
+ .filter(|r| r.url == connector.native_server_url)
+ .collect();
+ if matching.is_empty() {
+ return Ok(None);
+ }
+ Ok(Some(UserMcpTools::Native(
+ McpToolSet::new(&matching, self.native_store.clone()).await,
+ )))
+ }
+
+ #[tracing::instrument(skip(self, user), err)]
+ async fn connector_connected(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ connector: ConnectorRef<'_>,
+ ) -> anyhow::Result<bool> {
+ let pipedream = self.pipedream_connections(user).await;
+ if !pipedream.is_empty() {
+ return Ok(pipedream
+ .iter()
+ .any(|c| c.app_slug == connector.pipedream_app_slug));
+ }
+
+ let native = self
+ .native_store
+ .list(user)
+ .await
+ .map_err(|e| anyhow::anyhow!("mcp store: {e:?}"))?;
+ Ok(native
+ .iter()
+ .any(|r| r.credentials.is_some() && r.url == connector.native_server_url))
+ }
+}
+
+/// Wraps a static [`AsyncToolCollection`] and the user's selected MCP tools,
+/// presenting them as a single toolset to the AI loop.
+pub struct CombinedToolSet<T> {
+ static_tools: Arc<AsyncToolCollection<T>>,
+ mcp_tools: UserMcpTools,
+}
+
+impl<T> CombinedToolSet<T> {
+ /// Combine the static tools with an already-selected MCP toolset.
+ pub fn new(static_tools: Arc<AsyncToolCollection<T>>, mcp_tools: UserMcpTools) -> Self {
+ Self {
+ static_tools,
+ mcp_tools,
+ }
+ }
+}
+
+impl<T: Send + Sync + 'static> ToolSet<T> for CombinedToolSet<T> {
+ fn try_tool_call<'a>(
+ &'a self,
+ context: T,
+ request_context: RequestContext,
+ tool_name: &'a str,
+ json: &'a serde_json::Value,
+ ) -> Pin<
+ Box<dyn Future<Output = Result<ToolResult<serde_json::Value>, ToolSetError>> + 'a + Send>,
+ > {
+ if tool_name.starts_with(MANGLED_PREFIX) {
+ self.mcp_tools
+ .try_tool_call(context, request_context, tool_name, json)
+ } else {
+ self.static_tools
+ .try_tool_call(context, request_context, tool_name, json)
+ }
+ }
+
+ fn request_schemas(&self) -> Option<Vec<RequestSchema>> {
+ // Only the static (first-party) tools are sent on every request. MCP
+ // tools are loaded on demand via the `SearchTools` tool — they are
+ // surfaced through `searchable_catalog`, not here — so a large or
+ // growing MCP catalog never bloats the request.
+ self.static_tools.request_schemas()
+ }
+
+ fn searchable_catalog(&self) -> Vec<SearchableTool> {
+ self.mcp_tools.catalog()
+ }
+
+ fn searchable_toolset_names(&self) -> Vec<String> {
+ ToolSet::<T>::searchable_toolset_names(&self.mcp_tools)
+ }
+
+ fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ToolInfo> {
+ if tool_name.starts_with(MANGLED_PREFIX) {
+ ToolSet::<T>::routing_description(&self.mcp_tools, tool_name)
+ } else {
+ self.static_tools.routing_description(tool_name)
+ }
+ }
+}
diff --git a/crates/onboarding/Cargo.toml b/crates/onboarding/Cargo.toml
index 6bc3e9468d..5f002beb9f 100644
--- a/crates/onboarding/Cargo.toml
+++ b/crates/onboarding/Cargo.toml
@@ -15,6 +15,7 @@ macro_authorization = { path = "../macro_authorization", default-features = fals
] }
macro_user_id = { path = "../macro_user_id" }
mcp_client = { path = "../mcp_client" }
+mcp_select = { path = "../mcp_select" }
serde = { workspace = true }
serde_json = { workspace = true }
sqlx = { workspace = true }
diff --git a/crates/onboarding/src/domain/service.rs b/crates/onboarding/src/domain/service.rs
index 2079723229..30a2b92b32 100644
--- a/crates/onboarding/src/domain/service.rs
+++ b/crates/onboarding/src/domain/service.rs
@@ -59,28 +59,31 @@ pub trait OnboardingService: Send + Sync + 'static {
/// Concrete orchestrator wiring the repo, the user's MCP servers, and the
/// import service together.
-pub struct OnboardingServiceImpl<R, S, I> {
+pub struct OnboardingServiceImpl<R, S, I, M> {
repo: R,
mcp_store: Arc<S>,
import: Arc<I>,
+ mcp_select: Arc<M>,
}
-impl<R, S, I> OnboardingServiceImpl<R, S, I> {
+impl<R, S, I, M> OnboardingServiceImpl<R, S, I, M> {
/// Build the orchestrator.
- pub fn new(repo: R, mcp_store: Arc<S>, import: Arc<I>) -> Self {
+ pub fn new(repo: R, mcp_store: Arc<S>, import: Arc<I>, mcp_select: Arc<M>) -> Self {
Self {
repo,
mcp_store,
import,
+ mcp_select,
}
}
}
-impl<R, S, I> OnboardingServiceImpl<R, S, I>
+impl<R, S, I, M> OnboardingServiceImpl<R, S, I, M>
where
R: OnboardingRepo,
S: McpServerStore,
I: ImportService,
+ M: mcp_select::ConnectorSelect,
{
async fn connected_servers(
&self,
@@ -104,11 +107,22 @@ where
/// Start an auto-importing gather run for every authenticated connector
/// that never had one. A failing source must not block the others (or
/// the read).
- async fn start_due_gathers(&self, user: &MacroUserIdStr<'static>, servers: &[ConnectedServer]) {
+ async fn start_due_gathers(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ _servers: &[ConnectedServer],
+ ) {
for source in ImportSource::all() {
- let connected = servers
- .iter()
- .any(|server| server.authenticated && server.url == source.mcp_server_url());
+ // Which stack backs the connector is the selector's call
+ // (Pipedream connectors win over native ones, see `mcp_select`).
+ let connected = self
+ .mcp_select
+ .connector_connected(user, source.connector_ref())
+ .await
+ .inspect_err(
+ |e| tracing::warn!(source = source.as_ref(), error = ?e, "connected check failed"),
+ )
+ .unwrap_or(false);
if !connected {
continue;
}
@@ -119,11 +133,12 @@ where
}
}
-impl<R, S, I> OnboardingService for OnboardingServiceImpl<R, S, I>
+impl<R, S, I, M> OnboardingService for OnboardingServiceImpl<R, S, I, M>
where
R: OnboardingRepo,
S: McpServerStore,
I: ImportService,
+ M: mcp_select::ConnectorSelect,
{
#[tracing::instrument(skip(self, user), err)]
async fn get_state(&self, user: MacroUserIdStr<'static>) -> Result<OnboardingState> {
diff --git a/crates/onboarding/src/domain/service/test.rs b/crates/onboarding/src/domain/service/test.rs
index 2af0e6aefa..6b75cd6d4d 100644
--- a/crates/onboarding/src/domain/service/test.rs
+++ b/crates/onboarding/src/domain/service/test.rs
@@ -3,6 +3,8 @@ use import::domain::models::ImportState;
use import::domain::ports::Result as ImportResult;
use import::domain::service::RunImportOutcome;
use mcp_client::domain::models::{McpServerRecord, StoredCredentials};
+use mcp_client::domain::service::McpToolSet;
+use mcp_select::{ConnectorRef, ConnectorSelect, UserMcpTools};
use std::sync::Mutex;
use uuid::Uuid;
@@ -180,6 +182,38 @@ impl ImportService for MockImport {
}
}
+/// Selector mock mirroring the native-only rule: no Pipedream connectors in
+/// these tests, so connectivity is the native `credentials && url` match.
+struct MockSelect {
+ store: Arc<MockStore>,
+}
+
+impl ConnectorSelect for MockSelect {
+ async fn user_toolset(&self, _user: &MacroUserIdStr<'static>) -> UserMcpTools {
+ UserMcpTools::Native(McpToolSet::new(&[], self.store.clone()).await)
+ }
+
+ async fn connector_toolset(
+ &self,
+ _user: &MacroUserIdStr<'static>,
+ _connector: ConnectorRef<'_>,
+ ) -> anyhow::Result<Option<UserMcpTools>> {
+ Ok(None)
+ }
+
+ async fn connector_connected(
+ &self,
+ _user: &MacroUserIdStr<'static>,
+ connector: ConnectorRef<'_>,
+ ) -> anyhow::Result<bool> {
+ Ok(self
+ .store
+ .records
+ .iter()
+ .any(|r| r.credentials.is_some() && r.url == connector.native_server_url))
+ }
+}
+
fn record(url: &str, authenticated: bool) -> McpServerRecord {
McpServerRecord {
user_id: user(),
@@ -195,15 +229,20 @@ fn service(
status: OnboardingStatus,
records: Vec<McpServerRecord>,
) -> (
- OnboardingServiceImpl<MockRepo, MockStore, MockImport>,
+ OnboardingServiceImpl<MockRepo, MockStore, MockImport, MockSelect>,
Arc<MockImport>,
) {
let import = Arc::new(MockImport::default());
(
OnboardingServiceImpl::new(
MockRepo::new(status),
- Arc::new(MockStore { records }),
+ Arc::new(MockStore {
+ records: records.clone(),
+ }),
import.clone(),
+ Arc::new(MockSelect {
+ store: Arc::new(MockStore { records }),
+ }),
),
import,
)
@@ -262,12 +301,16 @@ async fn reconcile_ignores_users_who_never_entered_the_flow() {
// connecting a server outside onboarding must not get gathers (or an
// onboarding row) out of it.
let import = Arc::new(MockImport::default());
+ let records = vec![record("https://mcp.linear.app/mcp", true)];
let service = OnboardingServiceImpl::new(
MockRepo::missing(),
Arc::new(MockStore {
- records: vec![record("https://mcp.linear.app/mcp", true)],
+ records: records.clone(),
}),
import.clone(),
+ Arc::new(MockSelect {
+ store: Arc::new(MockStore { records }),
+ }),
);
service.reconcile(user()).await.expect("reconcile");
@@ -292,6 +335,9 @@ async fn get_state_carries_the_suggested_team_domain() {
MockRepo::new(OnboardingStatus::Active),
Arc::new(MockStore { records: vec![] }),
Arc::new(MockImport::default()),
+ Arc::new(MockSelect {
+ store: Arc::new(MockStore { records: vec![] }),
+ }),
);
let state = service.get_state(user()).await.expect("get_state");
diff --git a/crates/pipedream_mcp/Cargo.toml b/crates/pipedream_mcp/Cargo.toml
new file mode 100644
index 0000000000..b02921c696
--- /dev/null
+++ b/crates/pipedream_mcp/Cargo.toml
@@ -0,0 +1,29 @@
+[package]
+name = "pipedream_mcp"
+version = "0.1.0"
+edition = "2024"
+publish = false
+
+[dependencies]
+ai_toolset = { path = "../ai_toolset" }
+anyhow.workspace = true
+axum.workspace = true
+futures.workspace = true
+macro_authorization = { path = "../macro_authorization", default-features = false, features = [
+ "axum",
+] }
+macro_user_id = { path = "../macro_user_id" }
+model-error-response = { path = "../model-error-response" }
+reqwest.workspace = true
+rmcp = { workspace = true, features = ["client", "transport-streamable-http-client-reqwest"] }
+schemars.workspace = true
+serde.workspace = true
+serde_json.workspace = true
+sqlx.workspace = true
+thiserror.workspace = true
+tracing.workspace = true
+utoipa.workspace = true
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+tokio.workspace = true
diff --git a/crates/pipedream_mcp/src/domain/call_tool_result.rs b/crates/pipedream_mcp/src/domain/call_tool_result.rs
new file mode 100644
index 0000000000..488ed5bb67
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/call_tool_result.rs
@@ -0,0 +1,66 @@
+//! Convenience behavior for MCP tool-call results.
+
+use rmcp::model::{CallToolResult, ResourceContents};
+
+#[cfg(test)]
+mod test;
+
+/// Conversion helpers implemented directly on [`CallToolResult`] through an
+/// extension trait.
+pub trait CallToolResultExt {
+ /// Concatenate text-bearing content blocks while preserving block boundaries.
+ fn text_content(&self) -> String;
+
+ /// Convert a successful result into the JSON value exposed to Macro tools.
+ ///
+ /// Structured content is preserved as JSON. Results without structured
+ /// content fall back to their text-bearing content blocks.
+ fn into_value(self) -> serde_json::Value;
+
+ /// Produce a useful error description from text or structured content.
+ fn error_description(&self) -> String;
+}
+
+impl CallToolResultExt for CallToolResult {
+ fn text_content(&self) -> String {
+ self.content
+ .iter()
+ .filter_map(|content| {
+ content
+ .raw
+ .as_text()
+ .map(|text| text.text.clone())
+ .or_else(|| {
+ let resource = content.raw.as_resource()?;
+ match &resource.resource {
+ ResourceContents::TextResourceContents { text, .. }
+ if !text.is_empty() =>
+ {
+ Some(text.clone())
+ }
+ _ => None,
+ }
+ })
+ })
+ .collect::<Vec<_>>()
+ .join("\n")
+ }
+
+ fn into_value(self) -> serde_json::Value {
+ let text = self.text_content();
+ self.structured_content
+ .unwrap_or(serde_json::Value::String(text))
+ }
+
+ fn error_description(&self) -> String {
+ let text = self.text_content();
+ if text.is_empty() {
+ self.structured_content
+ .as_ref()
+ .map(ToString::to_string)
+ .unwrap_or_else(|| "MCP tool returned an error".to_string())
+ } else {
+ text
+ }
+ }
+}
diff --git a/crates/pipedream_mcp/src/domain/call_tool_result/test.rs b/crates/pipedream_mcp/src/domain/call_tool_result/test.rs
new file mode 100644
index 0000000000..e26e068fab
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/call_tool_result/test.rs
@@ -0,0 +1,46 @@
+use super::*;
+use rmcp::model::Content;
+use serde_json::json;
+
+#[test]
+fn structured_tool_results_are_preserved() {
+ let result = CallToolResult::structured(json!({
+ "object": "page_markdown",
+ "markdown": "# Roadmap",
+ "truncated": false,
+ }));
+
+ assert_eq!(
+ result.into_value(),
+ json!({
+ "object": "page_markdown",
+ "markdown": "# Roadmap",
+ "truncated": false,
+ })
+ );
+}
+
+#[test]
+fn unstructured_text_results_preserve_block_boundaries() {
+ let result = CallToolResult::success(vec![Content::text("first"), Content::text("second")]);
+
+ assert_eq!(result.into_value(), json!("first\nsecond"));
+}
+
+#[test]
+fn embedded_text_resources_are_not_discarded() {
+ let result = CallToolResult::success(vec![
+ Content::text("# Page"),
+ Content::embedded_text("notion://page/abc", "Page content"),
+ ]);
+
+ assert_eq!(result.into_value(), json!("# Page\nPage content"));
+}
+
+#[test]
+fn structured_errors_have_a_description_without_text_content() {
+ let mut result = CallToolResult::structured(json!({"message": "not found"}));
+ result.is_error = Some(true);
+
+ assert_eq!(result.error_description(), r#"{"message":"not found"}"#);
+}
diff --git a/crates/pipedream_mcp/src/domain/mod.rs b/crates/pipedream_mcp/src/domain/mod.rs
new file mode 100644
index 0000000000..99030608a3
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/mod.rs
@@ -0,0 +1,8 @@
+mod call_tool_result;
+/// Domain models for Pipedream connections and the app catalog.
+pub mod models;
+pub use call_tool_result::CallToolResultExt;
+/// Port traits consumed by the domain services.
+pub mod ports;
+/// Domain services: connect completion, catalog browsing, and the toolset.
+pub mod service;
diff --git a/crates/pipedream_mcp/src/domain/models.rs b/crates/pipedream_mcp/src/domain/models.rs
new file mode 100644
index 0000000000..eee82f0aee
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/models.rs
@@ -0,0 +1,100 @@
+use rmcp::RoleClient;
+use rmcp::model::{ClientInfo, Implementation};
+use rmcp::service::RunningService;
+
+pub use macro_user_id::user_id::MacroUserIdStr;
+
+/// Our MCP client publishes this name to servers on-connect.
+pub const MCP_CLIENT_NAME: &str = "Macro";
+
+/// A connected MCP server session.
+pub type McpServer = RunningService<RoleClient, ClientInfo>;
+
+/// Build the client info sent to MCP servers during initialization.
+pub fn client_info() -> ClientInfo {
+ ClientInfo::new(
+ Default::default(),
+ Implementation::new(MCP_CLIENT_NAME, env!("CARGO_PKG_VERSION")),
+ )
+}
+
+/// An MCP connector a user has connected through Pipedream.
+///
+/// Pipedream owns the OAuth grant and tokens for the connected account; we
+/// store only which app the user connected and the Pipedream account ID the
+/// grant lives under.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct PipedreamConnection {
+ /// The user who connected the app.
+ pub user_id: MacroUserIdStr<'static>,
+ /// Pipedream app name slug, e.g. `linear` or `notion`.
+ pub app_slug: String,
+ /// Human-readable display name, e.g. `Linear`.
+ pub server_name: String,
+ /// The Pipedream connected-account ID holding the grant.
+ pub account_id: String,
+ /// Whether the connector is enabled for tool use.
+ pub enabled: bool,
+}
+
+/// A short-lived token for opening Pipedream's hosted Connect UI.
+#[derive(Clone, Debug)]
+pub struct ConnectToken {
+ /// The Connect token itself.
+ pub token: String,
+ /// RFC 3339 expiry of the token.
+ pub expires_at: String,
+ /// Shareable link that opens the same connect flow in a browser tab.
+ pub connect_link_url: String,
+}
+
+/// A connected account as reported by Pipedream.
+#[derive(Clone, Debug)]
+pub struct PipedreamAccount {
+ /// Pipedream's connected-account ID (`apn_...`).
+ pub id: String,
+ /// The external user ID the account was connected for (our user ID).
+ pub external_user_id: Option<String>,
+ /// The app the account belongs to (name slug, e.g. `linear`).
+ pub app_slug: String,
+ /// Human-readable app name, e.g. `Linear`.
+ pub app_name: String,
+ /// Whether Pipedream considers the account's credentials healthy.
+ pub healthy: bool,
+}
+
+/// One connectable app advertised in the catalog.
+#[derive(Clone, Debug, PartialEq, Eq)]
+pub struct CatalogEntry {
+ /// Pipedream app name slug, e.g. `linear` — what gets connected.
+ pub app_slug: String,
+ /// Human-readable name to display, e.g. `Linear`.
+ pub display_name: String,
+ /// One-line description of what connecting the app enables.
+ pub description: Option<String>,
+ /// URL of the app's icon, when the directory provides one.
+ pub icon_url: Option<String>,
+ /// Whether this is a curated priority connector, ranked above organic
+ /// directory results (and renderable as its own section).
+ pub priority: bool,
+}
+
+/// One page of catalog results.
+#[derive(Clone, Debug, Default)]
+pub struct CatalogPage {
+ /// The entries on this page, in display order.
+ pub entries: Vec<CatalogEntry>,
+ /// Opaque cursor for fetching the next page. `None` on the last page.
+ pub next_cursor: Option<String>,
+}
+
+/// Errors from Pipedream MCP tool dispatch.
+#[derive(Debug, thiserror::Error)]
+pub enum Error {
+ /// The requested tool was not found on any connected server.
+ #[error("unknown tool: {0}")]
+ UnknownTool(String),
+ /// A tool invocation failed.
+ #[error("tool call failed: {0}")]
+ ToolCall(String),
+}
diff --git a/crates/pipedream_mcp/src/domain/ports.rs b/crates/pipedream_mcp/src/domain/ports.rs
new file mode 100644
index 0000000000..b5cbcd48f0
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/ports.rs
@@ -0,0 +1,101 @@
+use super::models::{
+ CatalogPage, ConnectToken, MacroUserIdStr, McpServer, PipedreamAccount, PipedreamConnection,
+};
+
+/// Port for persisting Pipedream-connected apps, keyed by user and app slug.
+pub trait ConnectionStore: Send + Sync + 'static {
+ /// Error type for store operations.
+ type Err: Send + std::fmt::Debug;
+
+ /// Persist a record, overwriting any existing entry for the same user and app.
+ fn save(
+ &self,
+ record: &PipedreamConnection,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// Load a record for a user and app slug. Returns `None` if not stored.
+ fn load(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ app_slug: &str,
+ ) -> impl Future<Output = Result<Option<PipedreamConnection>, Self::Err>> + Send;
+
+ /// Delete a record for a user and app slug.
+ fn delete(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ app_slug: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
+ /// List all stored records for a user.
+ fn list(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> impl Future<Output = Result<Vec<PipedreamConnection>, Self::Err>> + Send;
+}
+
+/// Port for opening a live MCP connection for a connected app.
+///
+/// The single implementation connects to Pipedream's remote MCP server,
+/// scoped to the record's user and app; Pipedream injects the account's
+/// credentials server-side, so no tokens ever pass through here.
+pub trait McpConnection: Send + Sync + 'static {
+ /// Connect to the MCP server serving `record`'s app for `record.user_id`.
+ fn connect(
+ &self,
+ record: &PipedreamConnection,
+ ) -> impl Future<Output = anyhow::Result<McpServer>> + Send;
+}
+
+/// An unconfigured deployment: `None` connects nothing, so toolsets built
+/// before Pipedream is configured degrade to empty instead of erroring at
+/// composition time.
+impl<P: McpConnection> McpConnection for Option<std::sync::Arc<P>> {
+ async fn connect(&self, record: &PipedreamConnection) -> anyhow::Result<McpServer> {
+ match self {
+ Some(connection) => connection.connect(record).await,
+ None => anyhow::bail!("Pipedream is not configured"),
+ }
+ }
+}
+
+/// Port for Pipedream Connect: managed auth for MCP connectors.
+///
+/// Pipedream owns the whole account lifecycle — the consent flow (hosted
+/// Connect UI), credential storage, and token refresh. The domain only ever
+/// sees short-lived Connect tokens and account metadata.
+pub trait PipedreamConnect: Send + Sync + 'static {
+ /// Create a short-lived Connect token for `external_user_id` (our user
+ /// ID), used by the frontend to open the hosted Connect UI.
+ fn create_connect_token(
+ &self,
+ external_user_id: &str,
+ ) -> impl Future<Output = anyhow::Result<ConnectToken>> + Send;
+
+ /// Fetch a connected account's metadata. Returns `None` if Pipedream
+ /// doesn't know the account ID.
+ fn get_account(
+ &self,
+ account_id: &str,
+ ) -> impl Future<Output = anyhow::Result<Option<PipedreamAccount>>> + Send;
+
+ /// Delete a connected account from Pipedream (revoking our copy of the
+ /// grant).
+ fn delete_account(&self, account_id: &str) -> impl Future<Output = anyhow::Result<()>> + Send;
+}
+
+/// Port for browsing the directory of connectable apps.
+pub trait ConnectorDirectory: Send + Sync + 'static {
+ /// Search the directory.
+ ///
+ /// `search` filters apps by name; `None` browses everything. `cursor` is
+ /// the opaque pagination cursor from a previous page. Implementations
+ /// return only apps that can actually be connected (i.e. apps with an
+ /// auth flow).
+ fn search(
+ &self,
+ search: Option<&str>,
+ cursor: Option<&str>,
+ limit: u32,
+ ) -> impl Future<Output = anyhow::Result<CatalogPage>> + Send;
+}
diff --git a/crates/pipedream_mcp/src/domain/service/catalog.rs b/crates/pipedream_mcp/src/domain/service/catalog.rs
new file mode 100644
index 0000000000..acb5f26336
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/service/catalog.rs
@@ -0,0 +1,122 @@
+//! Browsing the catalog of connectable MCP apps.
+//!
+//! The catalog merges two sources: a curated list of priority connectors we
+//! actively promote, and Pipedream's app directory. Priority connectors rank
+//! above organic directory results (clients may also render them as their
+//! own section, via [`CatalogEntry::priority`]).
+
+use crate::domain::models::{CatalogEntry, CatalogPage};
+use crate::domain::ports::ConnectorDirectory;
+
+#[cfg(test)]
+mod test;
+
+/// A curated connector we promote above organic directory results.
+struct PriorityConnector {
+ /// Pipedream app name slug (see the app's page at pipedream.com/apps).
+ app_slug: &'static str,
+ display_name: &'static str,
+ /// Product-voice tagline shown instead of the directory's description.
+ tagline: &'static str,
+}
+
+/// The promoted connectors, in the order they should rank.
+///
+/// This is the place to "advertise" a connector: entries here are pinned to
+/// the top of the catalog (or shown in a dedicated featured section).
+const PRIORITY_CONNECTORS: &[PriorityConnector] = &[
+ PriorityConnector {
+ app_slug: "linear",
+ display_name: "Linear",
+ tagline: "Create and update issues without leaving Macro.",
+ },
+ PriorityConnector {
+ app_slug: "slack",
+ display_name: "Slack",
+ tagline: "Search conversations and post updates to channels.",
+ },
+ PriorityConnector {
+ app_slug: "notion",
+ display_name: "Notion",
+ tagline: "Search your pages, databases, and wikis.",
+ },
+ PriorityConnector {
+ app_slug: "posthog",
+ display_name: "PostHog",
+ tagline: "Query product analytics and user insights.",
+ },
+ PriorityConnector {
+ app_slug: "github",
+ display_name: "GitHub",
+ tagline: "Give the agent access to your repos, PRs, and issues.",
+ },
+ PriorityConnector {
+ app_slug: "datadog",
+ display_name: "Datadog",
+ tagline: "Query metrics, logs, and monitors.",
+ },
+ PriorityConnector {
+ app_slug: "grafana",
+ display_name: "Grafana",
+ tagline: "Search dashboards and query your data sources.",
+ },
+];
+
+/// Bounds for the page size, applied to whatever the client asks for.
+const MAX_PAGE_SIZE: u32 = 50;
+const DEFAULT_PAGE_SIZE: u32 = 20;
+
+fn matches_priority(entry: &CatalogEntry) -> bool {
+ PRIORITY_CONNECTORS
+ .iter()
+ .any(|p| p.app_slug == entry.app_slug)
+}
+
+fn priority_entry(connector: &PriorityConnector) -> CatalogEntry {
+ CatalogEntry {
+ app_slug: connector.app_slug.to_owned(),
+ display_name: connector.display_name.to_owned(),
+ description: Some(connector.tagline.to_owned()),
+ icon_url: None,
+ priority: true,
+ }
+}
+
+/// Browse the connector catalog: curated priority connectors first, then
+/// organic directory results, deduplicated.
+///
+/// Priority connectors matching `search` (or all of them, when browsing) are
+/// pinned to the front of the first page; directory entries duplicating a
+/// priority connector are dropped on every page so they never show up twice.
+#[tracing::instrument(skip(directory), err)]
+pub async fn browse_catalog<D: ConnectorDirectory>(
+ directory: &D,
+ search: Option<&str>,
+ cursor: Option<&str>,
+ limit: Option<u32>,
+) -> anyhow::Result<CatalogPage> {
+ let search = search.map(str::trim).filter(|s| !s.is_empty());
+ let limit = limit.unwrap_or(DEFAULT_PAGE_SIZE).clamp(1, MAX_PAGE_SIZE);
+
+ let mut page = directory.search(search, cursor, limit).await?;
+ page.entries.retain(|entry| !matches_priority(entry));
+
+ // Priority connectors lead the first page only; on later pages they'd be
+ // repeats of what the client already has.
+ if cursor.is_none() {
+ let needle = search.map(str::to_lowercase);
+ let pinned = PRIORITY_CONNECTORS
+ .iter()
+ .filter(|p| match &needle {
+ Some(needle) => {
+ p.display_name.to_lowercase().contains(needle)
+ || p.app_slug.to_lowercase().contains(needle)
+ }
+ None => true,
+ })
+ .map(priority_entry);
+ page.entries.splice(0..0, pinned);
+ }
+
+ Ok(page)
+}
diff --git a/crates/pipedream_mcp/src/domain/service/catalog/test.rs b/crates/pipedream_mcp/src/domain/service/catalog/test.rs
new file mode 100644
index 0000000000..b4dacdfca6
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/service/catalog/test.rs
@@ -0,0 +1,126 @@
+use super::*;
+use std::sync::Mutex;
+
+/// Fake directory returning a canned page and recording the query it got.
+struct FakeDirectory {
+ page: CatalogPage,
+ seen: Mutex<Vec<(Option<String>, Option<String>, u32)>>,
+}
+
+impl FakeDirectory {
+ fn returning(entries: Vec<CatalogEntry>) -> Self {
+ Self {
+ page: CatalogPage {
+ entries,
+ next_cursor: None,
+ },
+ seen: Mutex::new(Vec::new()),
+ }
+ }
+}
+
+impl ConnectorDirectory for FakeDirectory {
+ async fn search(
+ &self,
+ search: Option<&str>,
+ cursor: Option<&str>,
+ limit: u32,
+ ) -> anyhow::Result<CatalogPage> {
+ self.seen.lock().unwrap().push((
+ search.map(str::to_owned),
+ cursor.map(str::to_owned),
+ limit,
+ ));
+ Ok(self.page.clone())
+ }
+}
+
+fn directory_entry(app_slug: &str) -> CatalogEntry {
+ CatalogEntry {
+ app_slug: app_slug.to_owned(),
+ display_name: app_slug.to_owned(),
+ description: Some("from the directory".to_owned()),
+ icon_url: None,
+ priority: false,
+ }
+}
+
+#[tokio::test]
+async fn first_page_pins_priority_connectors_before_directory_results() {
+ let directory = FakeDirectory::returning(vec![directory_entry("airtable")]);
+
+ let page = browse_catalog(&directory, None, None, None).await.unwrap();
+
+ let split = page.entries.iter().position(|e| !e.priority).unwrap();
+ assert_eq!(split, PRIORITY_CONNECTORS.len());
+ assert!(page.entries[..split].iter().all(|e| e.priority));
+ assert_eq!(page.entries[split].app_slug, "airtable");
+}
+
+#[tokio::test]
+async fn directory_duplicates_of_priority_connectors_are_dropped() {
+ let directory =
+ FakeDirectory::returning(vec![directory_entry("linear"), directory_entry("airtable")]);
+
+ let page = browse_catalog(&directory, None, None, None).await.unwrap();
+
+ let linear: Vec<_> = page
+ .entries
+ .iter()
+ .filter(|e| e.app_slug == "linear")
+ .collect();
+ assert_eq!(linear.len(), 1, "Linear must appear exactly once");
+ assert!(linear[0].priority);
+ assert_eq!(
+ linear[0].description.as_deref(),
+ Some("Create and update issues without leaving Macro."),
+ "priority tagline wins over the directory description"
+ );
+}
+
+#[tokio::test]
+async fn search_filters_priority_connectors_and_marks_them() {
+ let directory = FakeDirectory::returning(vec![directory_entry("linear_helper")]);
+
+ let page = browse_catalog(&directory, Some("linear"), None, None)
+ .await
+ .unwrap();
+
+ assert_eq!(page.entries[0].display_name, "Linear");
+ assert!(page.entries[0].priority);
+ assert_eq!(
+ page.entries.iter().filter(|e| e.priority).count(),
+ 1,
+ "only the matching priority connector is pinned"
+ );
+ assert_eq!(page.entries[1].app_slug, "linear_helper");
+}
+
+#[tokio::test]
+async fn later_pages_never_repeat_priority_connectors() {
+ let directory = FakeDirectory::returning(vec![directory_entry("linear")]);
+
+ let page = browse_catalog(&directory, None, Some("cursor-1"), None)
+ .await
+ .unwrap();
+
+ assert!(
+ page.entries.is_empty(),
+ "priority connectors are neither pinned nor repeated on later pages"
+ );
+}
+
+#[tokio::test]
+async fn blank_search_browses_and_limit_is_clamped() {
+ let directory = FakeDirectory::returning(vec![]);
+
+ browse_catalog(&directory, Some(" "), None, Some(9999))
+ .await
+ .unwrap();
+
+ let seen = directory.seen.lock().unwrap();
+ let (search, cursor, limit) = seen[0].clone();
+ assert_eq!(search, None, "whitespace-only search means browse");
+ assert_eq!(cursor, None);
+ assert_eq!(limit, MAX_PAGE_SIZE);
+}
diff --git a/crates/pipedream_mcp/src/domain/service/connect.rs b/crates/pipedream_mcp/src/domain/service/connect.rs
new file mode 100644
index 0000000000..09891ebb36
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/service/connect.rs
@@ -0,0 +1,111 @@
+//! Completing and revoking Pipedream-managed MCP connections.
+//!
+//! The hosted Connect UI reports a connected-account ID to the frontend on
+//! success; nothing about that ID proves it belongs to the calling user.
+//! [`complete_pipedream_connection`] owns that policy: it verifies with
+//! Pipedream that the account exists and was connected for this user before
+//! any local record is written.
+
+use crate::domain::models::{MacroUserIdStr, PipedreamConnection};
+use crate::domain::ports::{ConnectionStore, PipedreamConnect};
+
+#[cfg(test)]
+mod test;
+
+/// Errors from completing a Pipedream connection.
+#[derive(Debug, thiserror::Error)]
+pub enum PipedreamConnectError {
+ /// The account doesn't exist, or wasn't connected for this user.
+ #[error("connected account not found for this user")]
+ NotFound,
+ /// Anything else.
+ #[error(transparent)]
+ Internal(#[from] anyhow::Error),
+}
+
+/// Verify a finished Connect flow and persist the connected app.
+///
+/// Confirms with Pipedream that `account_id` exists and belongs to `user_id`
+/// (accounts are minted for our user IDs via the Connect token), then
+/// upserts the app record. Reconnecting an app the user already has simply
+/// points its record at the new account.
+#[tracing::instrument(skip(store, pipedream), err)]
+pub async fn complete_pipedream_connection<S, P>(
+ store: &S,
+ pipedream: &P,
+ user_id: &MacroUserIdStr<'static>,
+ account_id: &str,
+ server_name: Option<&str>,
+) -> Result<PipedreamConnection, PipedreamConnectError>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect,
+ anyhow::Error: From<S::Err>,
+{
+ let account = pipedream
+ .get_account(account_id)
+ .await?
+ .ok_or(PipedreamConnectError::NotFound)?;
+
+ // The account must have been connected for this user. Connect tokens are
+ // minted per user, so a mismatch means the caller is trying to attach
+ // someone else's account (or a stale/foreign ID).
+ if account.external_user_id.as_deref() != Some(user_id.as_ref()) {
+ return Err(PipedreamConnectError::NotFound);
+ }
+
+ let existing = store
+ .load(user_id, &account.app_slug)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ let record = PipedreamConnection {
+ user_id: user_id.clone(),
+ app_slug: account.app_slug.clone(),
+ server_name: server_name
+ .map(str::to_owned)
+ .or_else(|| existing.as_ref().map(|r| r.server_name.clone()))
+ .unwrap_or(account.app_name),
+ account_id: account.id,
+ enabled: existing.as_ref().is_none_or(|r| r.enabled),
+ };
+
+ store.save(&record).await.map_err(anyhow::Error::from)?;
+
+ Ok(record)
+}
+
+/// Remove a connected app, revoking its Pipedream account.
+///
+/// The Pipedream deletion is best effort: failing to clean up remotely must
+/// not strand the local row, so remote failures are logged and the local
+/// delete proceeds.
+#[tracing::instrument(skip(store, pipedream), err)]
+pub async fn disconnect_mcp_server<S, P>(
+ store: &S,
+ pipedream: &P,
+ user_id: &MacroUserIdStr<'static>,
+ app_slug: &str,
+) -> anyhow::Result<()>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect,
+ anyhow::Error: From<S::Err>,
+{
+ let record = store
+ .load(user_id, app_slug)
+ .await
+ .map_err(anyhow::Error::from)?;
+ if let Some(record) = record
+ && let Err(e) = pipedream.delete_account(&record.account_id).await
+ {
+ tracing::warn!(error = ?e, account_id = %record.account_id, "failed to delete Pipedream account");
+ }
+
+ store
+ .delete(user_id, app_slug)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok(())
+}
diff --git a/crates/pipedream_mcp/src/domain/service/connect/test.rs b/crates/pipedream_mcp/src/domain/service/connect/test.rs
new file mode 100644
index 0000000000..495c1ee915
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/service/connect/test.rs
@@ -0,0 +1,265 @@
+use super::*;
+use crate::domain::models::{ConnectToken, PipedreamAccount};
+use macro_user_id::cowlike::CowLike;
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+fn user(id: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str(id).unwrap().into_owned()
+}
+
+#[derive(Default)]
+struct FakeStore {
+ records: Mutex<HashMap<(String, String), PipedreamConnection>>,
+}
+
+impl ConnectionStore for FakeStore {
+ type Err = anyhow::Error;
+
+ async fn save(&self, record: &PipedreamConnection) -> Result<(), Self::Err> {
+ self.records.lock().unwrap().insert(
+ (record.user_id.to_string(), record.app_slug.clone()),
+ record.clone(),
+ );
+ Ok(())
+ }
+
+ async fn load(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ app_slug: &str,
+ ) -> Result<Option<PipedreamConnection>, Self::Err> {
+ Ok(self
+ .records
+ .lock()
+ .unwrap()
+ .get(&(user_id.to_string(), app_slug.to_owned()))
+ .cloned())
+ }
+
+ async fn delete(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ app_slug: &str,
+ ) -> Result<(), Self::Err> {
+ self.records
+ .lock()
+ .unwrap()
+ .remove(&(user_id.to_string(), app_slug.to_owned()));
+ Ok(())
+ }
+
+ async fn list(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<PipedreamConnection>, Self::Err> {
+ Ok(self
+ .records
+ .lock()
+ .unwrap()
+ .values()
+ .filter(|r| &r.user_id == user_id)
+ .cloned()
+ .collect())
+ }
+}
+
+#[derive(Default)]
+struct FakePipedream {
+ accounts: HashMap<String, PipedreamAccount>,
+ deleted: Mutex<Vec<String>>,
+}
+
+impl PipedreamConnect for FakePipedream {
+ async fn create_connect_token(&self, _external_user_id: &str) -> anyhow::Result<ConnectToken> {
+ Ok(ConnectToken {
+ token: "ctok_test".into(),
+ expires_at: "2099-01-01T00:00:00Z".into(),
+ connect_link_url: "https://pipedream.com/_static/connect.html?token=ctok_test".into(),
+ })
+ }
+
+ async fn get_account(&self, account_id: &str) -> anyhow::Result<Option<PipedreamAccount>> {
+ Ok(self.accounts.get(account_id).cloned())
+ }
+
+ async fn delete_account(&self, account_id: &str) -> anyhow::Result<()> {
+ self.deleted.lock().unwrap().push(account_id.to_owned());
+ Ok(())
+ }
+}
+
+fn account(id: &str, external_user_id: Option<&str>, app_slug: &str) -> PipedreamAccount {
+ PipedreamAccount {
+ id: id.to_owned(),
+ external_user_id: external_user_id.map(str::to_owned),
+ app_slug: app_slug.to_owned(),
+ app_name: "Linear".to_owned(),
+ healthy: true,
+ }
+}
+
+#[tokio::test]
+async fn completing_verifies_and_stores_the_connected_app() {
+ let store = FakeStore::default();
+ let mut pd = FakePipedream::default();
+ pd.accounts.insert(
+ "apn_1".into(),
+ account("apn_1", Some("macro|[email protected]"), "linear"),
+ );
+
+ let record = complete_pipedream_connection(
+ &store,
+ &pd,
+ &user("macro|[email protected]"),
+ "apn_1",
+ None,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(record.app_slug, "linear");
+ assert_eq!(record.account_id, "apn_1");
+ assert_eq!(record.server_name, "Linear");
+ assert!(record.enabled);
+ assert!(
+ store
+ .load(&user("macro|[email protected]"), "linear")
+ .await
+ .unwrap()
+ .is_some()
+ );
+}
+
+#[tokio::test]
+async fn completing_rejects_accounts_owned_by_someone_else() {
+ let store = FakeStore::default();
+ let mut pd = FakePipedream::default();
+ pd.accounts.insert(
+ "apn_1".into(),
+ account("apn_1", Some("macro|[email protected]"), "linear"),
+ );
+
+ let err = complete_pipedream_connection(
+ &store,
+ &pd,
+ &user("macro|[email protected]"),
+ "apn_1",
+ None,
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, PipedreamConnectError::NotFound));
+ assert!(store.records.lock().unwrap().is_empty(), "nothing stored");
+}
+
+#[tokio::test]
+async fn completing_rejects_unknown_accounts() {
+ let store = FakeStore::default();
+ let pd = FakePipedream::default();
+
+ let err = complete_pipedream_connection(
+ &store,
+ &pd,
+ &user("macro|[email protected]"),
+ "apn_missing",
+ None,
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(err, PipedreamConnectError::NotFound));
+}
+
+#[tokio::test]
+async fn reconnecting_keeps_name_and_enabled_state_but_swaps_the_account() {
+ let store = FakeStore::default();
+ store
+ .save(&PipedreamConnection {
+ user_id: user("macro|[email protected]"),
+ app_slug: "linear".into(),
+ server_name: "My Linear".into(),
+ account_id: "apn_old".into(),
+ enabled: false,
+ })
+ .await
+ .unwrap();
+
+ let mut pd = FakePipedream::default();
+ pd.accounts.insert(
+ "apn_new".into(),
+ account("apn_new", Some("macro|[email protected]"), "linear"),
+ );
+
+ let record = complete_pipedream_connection(
+ &store,
+ &pd,
+ &user("macro|[email protected]"),
+ "apn_new",
+ None,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(record.server_name, "My Linear", "explicit name preserved");
+ assert_eq!(record.account_id, "apn_new");
+ assert!(!record.enabled, "user's disabled state preserved");
+}
+
+#[tokio::test]
+async fn explicit_server_name_wins() {
+ let store = FakeStore::default();
+ let mut pd = FakePipedream::default();
+ pd.accounts.insert(
+ "apn_1".into(),
+ account("apn_1", Some("macro|[email protected]"), "linear"),
+ );
+
+ let record = complete_pipedream_connection(
+ &store,
+ &pd,
+ &user("macro|[email protected]"),
+ "apn_1",
+ Some("Work Linear"),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(record.server_name, "Work Linear");
+}
+
+#[tokio::test]
+async fn disconnect_revokes_the_pipedream_account_and_deletes_the_row() {
+ let store = FakeStore::default();
+ store
+ .save(&PipedreamConnection {
+ user_id: user("macro|[email protected]"),
+ app_slug: "linear".into(),
+ server_name: "Linear".into(),
+ account_id: "apn_1".into(),
+ enabled: true,
+ })
+ .await
+ .unwrap();
+ let pd = FakePipedream::default();
+
+ disconnect_mcp_server(&store, &pd, &user("macro|[email protected]"), "linear")
+ .await
+ .unwrap();
+
+ assert_eq!(*pd.deleted.lock().unwrap(), vec!["apn_1".to_owned()]);
+ assert!(store.records.lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn disconnect_of_unknown_app_is_a_quiet_noop() {
+ let store = FakeStore::default();
+ let pd = FakePipedream::default();
+
+ disconnect_mcp_server(&store, &pd, &user("macro|[email protected]"), "linear")
+ .await
+ .unwrap();
+
+ assert!(pd.deleted.lock().unwrap().is_empty());
+}
diff --git a/crates/pipedream_mcp/src/domain/service/mod.rs b/crates/pipedream_mcp/src/domain/service/mod.rs
new file mode 100644
index 0000000000..bf04315320
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/service/mod.rs
@@ -0,0 +1,10 @@
+/// Browsing the catalog of connectable apps.
+pub mod catalog;
+/// Completion and revocation of Pipedream connections.
+pub mod connect;
+/// The Pipedream MCP tool set.
+pub mod toolset;
+
+pub use catalog::browse_catalog;
+pub use connect::{PipedreamConnectError, complete_pipedream_connection, disconnect_mcp_server};
+pub use toolset::PipedreamToolSet;
diff --git a/crates/pipedream_mcp/src/domain/service/toolset.rs b/crates/pipedream_mcp/src/domain/service/toolset.rs
new file mode 100644
index 0000000000..0e4533ff8a
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/service/toolset.rs
@@ -0,0 +1,287 @@
+use crate::domain::CallToolResultExt;
+use crate::domain::models::{Error, MacroUserIdStr, McpServer, PipedreamConnection};
+use crate::domain::ports::McpConnection;
+use ai_toolset::{
+ RequestContext, RequestSchema, SearchableTool, ToolCallError, ToolInfo, ToolResult, ToolSet,
+ ToolSetError,
+};
+use rmcp::RoleClient;
+use rmcp::model::{CallToolRequestParams, CallToolResult, Tool};
+use rmcp::service::Peer;
+use schemars::Schema;
+use std::collections::BTreeMap;
+use std::pin::Pin;
+use std::sync::Arc;
+
+const MANGLED_PREFIX: &str = "mcp__";
+const MANGLED_SEPARATOR: &str = "__";
+
+/// A mangled tool name in the format `mcp__<server>__<tool>`.
+#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
+struct MangledName(String);
+
+impl MangledName {
+ fn new(server_name: &str, tool_name: &str) -> Self {
+ Self(format!(
+ "{MANGLED_PREFIX}{server_name}{MANGLED_SEPARATOR}{tool_name}"
+ ))
+ }
+
+ fn parse(s: &str) -> Option<(&str, &str)> {
+ s.strip_prefix(MANGLED_PREFIX)?
+ .split_once(MANGLED_SEPARATOR)
+ }
+
+ fn as_str(&self) -> &str {
+ &self.0
+ }
+}
+
+impl std::fmt::Display for MangledName {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str(&self.0)
+ }
+}
+
+struct RegisteredTool {
+ peer: Peer<RoleClient>,
+ tool: Tool,
+}
+
+/// Dispatches tool calls to connected MCP servers using name-mangled routing.
+///
+/// Every tool is exposed as `mcp__<server_name>__<tool_name>` to guarantee
+/// uniqueness across servers.
+pub struct PipedreamToolSet {
+ tools: BTreeMap<MangledName, RegisteredTool>,
+ /// Kept alive so the background transport tasks aren't cancelled.
+ _connections: Vec<McpServer>,
+ /// The owning user, for correlating tool-call failures in logs. All
+ /// records passed to [`PipedreamToolSet::new`] belong to one user in practice.
+ user_id: Option<MacroUserIdStr<'static>>,
+}
+
+impl PipedreamToolSet {
+ /// Connect to every app in `records` concurrently, discover tools, and
+ /// register them. Connections go through `connection` (Pipedream's
+ /// remote MCP server), which injects each account's credentials
+ /// server-side.
+ ///
+ /// Apps that fail to connect or list tools are silently skipped.
+ #[tracing::instrument(skip_all)]
+ pub async fn new<C: McpConnection>(
+ records: &[PipedreamConnection],
+ connection: Arc<C>,
+ ) -> Self {
+ let user_id = records.first().map(|r| r.user_id.clone());
+
+ let futs = records.iter().filter(|r| r.enabled).map(|record| {
+ let connection = connection.clone();
+ async move {
+ let client = connection
+ .connect(record)
+ .await
+ .inspect_err(|e| {
+ tracing::warn!(
+ user_id = %record.user_id,
+ server = %record.server_name,
+ app = %record.app_slug,
+ error = ?e,
+ "failed to connect"
+ );
+ })
+ .ok()?;
+
+ let server_tools = match client.list_all_tools().await {
+ Ok(t) => t,
+ Err(e) => {
+ tracing::warn!(
+ user_id = %record.user_id,
+ server = %record.server_name,
+ app = %record.app_slug,
+ error = ?e,
+ "failed to list tools"
+ );
+ let _ = client.cancel().await;
+ return None;
+ }
+ };
+
+ Some((record.server_name.clone(), client, server_tools))
+ }
+ });
+
+ let results = futures::future::join_all(futs).await;
+
+ let mut tools = BTreeMap::new();
+ let mut connections = Vec::new();
+ for (server_name, client, server_tools) in results.into_iter().flatten() {
+ for tool in server_tools {
+ let mangled = MangledName::new(&server_name, &tool.name);
+
+ if tools.contains_key(&mangled) {
+ tracing::warn!(%mangled, "skipping duplicate tool");
+ continue;
+ }
+
+ tools.insert(
+ mangled,
+ RegisteredTool {
+ peer: client.peer().clone(),
+ tool,
+ },
+ );
+ }
+ connections.push(client);
+ }
+
+ Self {
+ tools,
+ _connections: connections,
+ user_id,
+ }
+ }
+
+ /// Returns `true` when no tools were discovered.
+ pub fn is_empty(&self) -> bool {
+ self.tools.is_empty()
+ }
+
+ /// The full catalog of MCP tools, public for hosts that compose this
+ /// toolset (see the `mcp_select` crate).
+ pub fn searchable_catalog(&self) -> Vec<SearchableTool> {
+ self.catalog()
+ }
+
+ /// The full catalog of MCP tools (mangled name + description + input schema)
+ /// for on-demand loading via tool search.
+ fn catalog(&self) -> Vec<SearchableTool> {
+ self.tools
+ .iter()
+ .map(|(mangled, entry)| SearchableTool {
+ name: mangled.as_str().to_string(),
+ description: entry
+ .tool
+ .description
+ .as_deref()
+ .unwrap_or_default()
+ .to_string(),
+ schema: Schema::from((*entry.tool.input_schema).clone()),
+ })
+ .collect()
+ }
+
+ /// Distinct names of the connected MCP servers that contributed tools,
+ /// sorted for a stable prompt. Derived from the mangled tool keys so it
+ /// reflects the servers actually serving searchable tools this request.
+ fn toolset_names(&self) -> Vec<String> {
+ let mut names: Vec<String> = self
+ .tools
+ .keys()
+ .filter_map(|mangled| MangledName::parse(mangled.as_str()))
+ .map(|(server, _tool)| server.to_string())
+ .collect();
+ names.sort();
+ names.dedup();
+ names
+ }
+
+ #[tracing::instrument(skip(self, arguments), err, fields(user_id = ?self.user_id))]
+ async fn call_tool(
+ &self,
+ name: &str,
+ arguments: serde_json::Map<String, serde_json::Value>,
+ ) -> Result<CallToolResult, Error> {
+ let key = MangledName(name.to_owned());
+ let entry = self
+ .tools
+ .get(&key)
+ .ok_or_else(|| Error::UnknownTool(name.to_owned()))?;
+
+ let params = CallToolRequestParams::new(entry.tool.name.clone()).with_arguments(arguments);
+
+ entry
+ .peer
+ .call_tool(params)
+ .await
+ .map_err(|e| Error::ToolCall(e.to_string()))
+ }
+}
+
+impl<Context: Send + Sync + 'static> ToolSet<Context> for PipedreamToolSet {
+ fn try_tool_call<'a>(
+ &'a self,
+ _context: Context,
+ _request_context: RequestContext,
+ tool_name: &'a str,
+ json: &'a serde_json::Value,
+ ) -> Pin<
+ Box<dyn Future<Output = Result<ToolResult<serde_json::Value>, ToolSetError>> + 'a + Send>,
+ > {
+ Box::pin(async move {
+ let arguments = match json {
+ serde_json::Value::Object(map) => map.clone(),
+ _ => serde_json::Map::new(),
+ };
+
+ let result = match self.call_tool(tool_name, arguments).await {
+ Ok(result) => result,
+ Err(Error::UnknownTool(name)) => {
+ return Err(ToolSetError::NotFound(name));
+ }
+ Err(e) => {
+ let description = e.to_string();
+ return Ok(Err(ToolCallError {
+ internal_error: anyhow::anyhow!("{}", &description),
+ description,
+ }));
+ }
+ };
+
+ if result.is_error.unwrap_or(false) {
+ let description = result.error_description();
+ Ok(Err(ToolCallError {
+ internal_error: anyhow::anyhow!("{}", &description),
+ description,
+ }))
+ } else {
+ Ok(Ok(result.into_value()))
+ }
+ })
+ }
+
+ fn request_schemas(&self) -> Option<Vec<RequestSchema>> {
+ let schemas: Vec<_> = self
+ .tools
+ .iter()
+ .map(|(mangled, entry)| RequestSchema {
+ name: mangled.as_str().to_string(),
+ schema: Schema::from((*entry.tool.input_schema).clone()),
+ })
+ .collect();
+
+ if schemas.is_empty() {
+ None
+ } else {
+ Some(schemas)
+ }
+ }
+
+ fn searchable_toolset_names(&self) -> Vec<String> {
+ self.toolset_names()
+ }
+
+ fn routing_description<'a>(&'a self, tool_name: &'a str) -> Option<ToolInfo> {
+ let (server_name, original_name) = MangledName::parse(tool_name)?;
+ let key = MangledName(tool_name.to_owned());
+ let display_name = self
+ .tools
+ .get(&key)
+ .and_then(|entry| entry.tool.title.clone());
+ Some(ToolInfo::ExternalTool {
+ service_name: server_name.to_owned(),
+ tool_name: original_name.to_owned(),
+ display_name,
+ })
+ }
+}
diff --git a/crates/pipedream_mcp/src/inbound/axum_router.rs b/crates/pipedream_mcp/src/inbound/axum_router.rs
new file mode 100644
index 0000000000..f825ca5b52
--- /dev/null
+++ b/crates/pipedream_mcp/src/inbound/axum_router.rs
@@ -0,0 +1,555 @@
+use crate::domain::{
+ models::{CatalogEntry, PipedreamConnection},
+ ports::{ConnectionStore, ConnectorDirectory, PipedreamConnect},
+ service::{
+ catalog::browse_catalog,
+ connect::{PipedreamConnectError, complete_pipedream_connection, disconnect_mcp_server},
+ },
+};
+use axum::{
+ Json, Router,
+ extract::{FromRef, Query, State},
+ http::StatusCode,
+ response::IntoResponse,
+ routing::{delete, get, post, put},
+};
+use macro_authorization::{
+ MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
+};
+use model_error_response::ErrorResponse;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+use utoipa::{IntoParams, ToSchema};
+
+/// Hook invoked after a connect flow completes and the record is saved.
+/// Hosts use this to react to a connection the moment it exists (e.g. start
+/// import gather jobs); implementations must be quick or spawn.
+pub type PipedreamAuthCompletedHook = Arc<
+ dyn Fn(PipedreamConnection) -> std::pin::Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
+>;
+
+/// Shared state for the MCP router.
+///
+/// `pipedream` is the single connect path. When it is `None` (deployment not
+/// configured), the connect and catalog endpoints answer 501; there is no
+/// fallback flow.
+pub struct PipedreamRouterState<S, P, Auth> {
+ store: Arc<S>,
+ pipedream: Option<Arc<P>>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ on_auth_completed: Option<PipedreamAuthCompletedHook>,
+}
+
+impl<S, P, Auth> Clone for PipedreamRouterState<S, P, Auth> {
+ fn clone(&self) -> Self {
+ Self {
+ store: self.store.clone(),
+ pipedream: self.pipedream.clone(),
+ authorization_state: self.authorization_state.clone(),
+ on_auth_completed: self.on_auth_completed.clone(),
+ }
+ }
+}
+
+impl<S, P, Auth> FromRef<PipedreamRouterState<S, P, Auth>> for MacroAuthorizationState<Auth> {
+ fn from_ref(state: &PipedreamRouterState<S, P, Auth>) -> Self {
+ state.authorization_state.clone()
+ }
+}
+
+impl<S, P, Auth> PipedreamRouterState<S, P, Auth>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect + ConnectorDirectory,
+ Auth: MacroAuthorizationService,
+{
+ /// Create a new router state from a server store, the Pipedream client
+ /// (None when the deployment has no Pipedream configured), and
+ /// authorization state.
+ pub fn new(
+ store: S,
+ pipedream: Option<Arc<P>>,
+ authorization_state: MacroAuthorizationState<Auth>,
+ ) -> Self {
+ Self {
+ store: Arc::new(store),
+ pipedream,
+ authorization_state,
+ on_auth_completed: None,
+ }
+ }
+
+ /// Invoke `hook` whenever a connect flow completes (see
+ /// [`PipedreamAuthCompletedHook`]).
+ pub fn with_auth_completed_hook(mut self, hook: PipedreamAuthCompletedHook) -> Self {
+ self.on_auth_completed = Some(hook);
+ self
+ }
+
+ /// Access the underlying server store.
+ pub fn store(&self) -> Arc<S> {
+ self.store.clone()
+ }
+
+ fn pipedream(&self) -> Result<&Arc<P>, PipedreamHandlerErr> {
+ self.pipedream
+ .as_ref()
+ .ok_or(PipedreamHandlerErr::PipedreamNotConfigured)
+ }
+}
+
+/// Authenticated MCP routes: connected-app CRUD, the Pipedream connect flow,
+/// and the connector catalog.
+pub fn pipedream_mcp_router<S, P, Auth, Global>(
+ state: PipedreamRouterState<S, P, Auth>,
+) -> Router<Global>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect + ConnectorDirectory,
+ Auth: MacroAuthorizationService,
+ anyhow::Error: From<S::Err>,
+ Global: Send + Sync,
+{
+ Router::new()
+ .route(
+ "/pipedream/mcp/connections",
+ get(list_connections::<S, P, Auth>),
+ )
+ .route(
+ "/pipedream/mcp/connections",
+ put(update_connection::<S, P, Auth>),
+ )
+ .route(
+ "/pipedream/mcp/connections",
+ delete(delete_connection::<S, P, Auth>),
+ )
+ .route(
+ "/pipedream/mcp/token",
+ post(create_connect_token::<S, P, Auth>),
+ )
+ .route(
+ "/pipedream/mcp/complete",
+ post(complete_connection::<S, P, Auth>),
+ )
+ .route(
+ "/pipedream/mcp/catalog",
+ get(browse_catalog_handler::<S, P, Auth>),
+ )
+ .with_state(state)
+}
+
+// -- request / response types ------------------------------------------------
+
+/// Request body for updating a connected app.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct PipedreamUpdateRequest {
+ /// The app slug to update.
+ app_slug: String,
+ /// New display name for the connector.
+ #[serde(default)]
+ server_name: Option<String>,
+ /// Enable or disable the connector.
+ #[serde(default)]
+ enabled: Option<bool>,
+}
+
+/// Query parameters for deleting a connected app.
+#[derive(Debug, Deserialize, IntoParams)]
+#[into_params(parameter_in = Query)]
+pub struct PipedreamDeleteParams {
+ /// The app slug to disconnect.
+ app_slug: String,
+}
+
+/// Response from creating a Pipedream Connect token.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct PipedreamTokenResponse {
+ /// Short-lived token to open the Pipedream Connect UI with.
+ token: String,
+ /// RFC 3339 expiry of the token.
+ expires_at: String,
+ /// Shareable link that opens the same connect flow in a browser tab.
+ connect_link_url: String,
+}
+
+/// Request body for completing a Pipedream connect flow.
+#[derive(Debug, Deserialize, ToSchema)]
+pub struct PipedreamCompleteRequest {
+ /// The connected-account ID reported by the Connect UI on success.
+ account_id: String,
+ /// Optional display name for the connector. Defaults to the app's name
+ /// for new connections; existing connections keep their name.
+ #[serde(default)]
+ server_name: Option<String>,
+}
+
+/// A connected MCP app as returned by the API.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct PipedreamConnectionResponse {
+ /// Pipedream app name slug, e.g. `linear`.
+ app_slug: String,
+ /// Human-readable display name.
+ server_name: String,
+ /// Whether the connector is enabled for tool use.
+ enabled: bool,
+}
+
+impl PipedreamConnectionResponse {
+ fn from_record(record: &PipedreamConnection) -> Self {
+ Self {
+ app_slug: record.app_slug.clone(),
+ server_name: record.server_name.clone(),
+ enabled: record.enabled,
+ }
+ }
+}
+
+/// Query parameters for browsing the connector catalog.
+#[derive(Debug, Deserialize, IntoParams)]
+#[into_params(parameter_in = Query)]
+pub struct PipedreamCatalogParams {
+ /// Search query to filter apps by name. Omit to browse.
+ #[serde(default)]
+ search: Option<String>,
+ /// Opaque pagination cursor from a previous response.
+ #[serde(default)]
+ cursor: Option<String>,
+ /// Page size (default 20, max 50).
+ #[serde(default)]
+ limit: Option<u32>,
+}
+
+/// One connectable app in the catalog.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct PipedreamCatalogEntryResponse {
+ /// Pipedream app name slug — pass this to the connect flow.
+ app_slug: String,
+ /// Human-readable name to display.
+ display_name: String,
+ /// One-line description of the app.
+ description: Option<String>,
+ /// URL of the app's icon, when available.
+ icon_url: Option<String>,
+ /// Curated priority connectors rank first and may be rendered as their
+ /// own featured section.
+ priority: bool,
+}
+
+impl From<CatalogEntry> for PipedreamCatalogEntryResponse {
+ fn from(entry: CatalogEntry) -> Self {
+ Self {
+ app_slug: entry.app_slug,
+ display_name: entry.display_name,
+ description: entry.description,
+ icon_url: entry.icon_url,
+ priority: entry.priority,
+ }
+ }
+}
+
+/// A page of the connector catalog.
+#[derive(Debug, Serialize, ToSchema)]
+pub struct PipedreamCatalogResponse {
+ /// Catalog entries in display order (priority connectors first).
+ servers: Vec<PipedreamCatalogEntryResponse>,
+ /// Cursor for the next page. Absent on the last page.
+ next_cursor: Option<String>,
+}
+
+// -- error --------------------------------------------------------------------
+
+/// Error type for MCP HTTP handlers.
+#[derive(Debug, thiserror::Error)]
+pub enum PipedreamHandlerErr {
+ /// The requested record was not found.
+ #[error("not found")]
+ NotFound,
+ /// Pipedream is not configured for this deployment.
+ #[error("Pipedream is not configured")]
+ PipedreamNotConfigured,
+ /// An internal error occurred.
+ #[error("{0}")]
+ Internal(#[from] anyhow::Error),
+}
+
+impl From<PipedreamConnectError> for PipedreamHandlerErr {
+ fn from(err: PipedreamConnectError) -> Self {
+ match err {
+ PipedreamConnectError::NotFound => PipedreamHandlerErr::NotFound,
+ PipedreamConnectError::Internal(e) => PipedreamHandlerErr::Internal(e),
+ }
+ }
+}
+
+impl IntoResponse for PipedreamHandlerErr {
+ fn into_response(self) -> axum::response::Response {
+ let status = match &self {
+ PipedreamHandlerErr::NotFound => StatusCode::NOT_FOUND,
+ PipedreamHandlerErr::PipedreamNotConfigured => StatusCode::NOT_IMPLEMENTED,
+ PipedreamHandlerErr::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
+ };
+ (
+ status,
+ Json(ErrorResponse {
+ message: self.to_string().into(),
+ }),
+ )
+ .into_response()
+ }
+}
+
+// -- handlers -----------------------------------------------------------------
+
+#[utoipa::path(
+ get,
+ path = "/pipedream/mcp/connections",
+ tag = "pipedream-mcp",
+ operation_id = "list_pipedream_mcp_connections",
+ responses(
+ (status = 200, body = Vec<PipedreamConnectionResponse>),
+ (status = 401, body = String),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// List the MCP apps connected by the authenticated user.
+#[tracing::instrument(skip_all, err)]
+pub async fn list_connections<S, P, Auth>(
+ State(state): State<PipedreamRouterState<S, P, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+) -> Result<Json<Vec<PipedreamConnectionResponse>>, PipedreamHandlerErr>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect + ConnectorDirectory,
+ Auth: MacroAuthorizationService,
+ anyhow::Error: From<S::Err>,
+{
+ let user = &authorization.authorization.user;
+ let records = state
+ .store
+ .list(&user.macro_user_id)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok(Json(
+ records
+ .iter()
+ .map(PipedreamConnectionResponse::from_record)
+ .collect(),
+ ))
+}
+
+#[utoipa::path(
+ put,
+ path = "/pipedream/mcp/connections",
+ tag = "pipedream-mcp",
+ operation_id = "update_pipedream_mcp_connection",
+ request_body = PipedreamUpdateRequest,
+ responses(
+ (status = 200, body = PipedreamConnectionResponse),
+ (status = 401, body = String),
+ (status = 404, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// Rename or enable/disable a connected app.
+#[tracing::instrument(skip_all, err)]
+pub async fn update_connection<S, P, Auth>(
+ State(state): State<PipedreamRouterState<S, P, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Json(body): Json<PipedreamUpdateRequest>,
+) -> Result<Json<PipedreamConnectionResponse>, PipedreamHandlerErr>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect + ConnectorDirectory,
+ Auth: MacroAuthorizationService,
+ anyhow::Error: From<S::Err>,
+{
+ let user = &authorization.authorization.user;
+ let mut record = state
+ .store
+ .load(&user.macro_user_id, &body.app_slug)
+ .await
+ .map_err(anyhow::Error::from)?
+ .ok_or(PipedreamHandlerErr::NotFound)?;
+
+ if let Some(name) = body.server_name {
+ record.server_name = name;
+ }
+ if let Some(enabled) = body.enabled {
+ record.enabled = enabled;
+ }
+
+ state
+ .store
+ .save(&record)
+ .await
+ .map_err(anyhow::Error::from)?;
+
+ Ok(Json(PipedreamConnectionResponse::from_record(&record)))
+}
+
+#[utoipa::path(
+ delete,
+ path = "/pipedream/mcp/connections",
+ tag = "pipedream-mcp",
+ operation_id = "delete_pipedream_mcp_connection",
+ params(PipedreamDeleteParams),
+ responses(
+ (status = 204),
+ (status = 401, body = String),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// Disconnect an app, revoking its Pipedream account.
+#[tracing::instrument(skip_all, err)]
+pub async fn delete_connection<S, P, Auth>(
+ State(state): State<PipedreamRouterState<S, P, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Query(params): Query<PipedreamDeleteParams>,
+) -> Result<StatusCode, PipedreamHandlerErr>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect + ConnectorDirectory,
+ Auth: MacroAuthorizationService,
+ anyhow::Error: From<S::Err>,
+{
+ let user = &authorization.authorization.user;
+ let pipedream = state.pipedream()?;
+ disconnect_mcp_server(
+ state.store.as_ref(),
+ pipedream.as_ref(),
+ &user.macro_user_id,
+ &params.app_slug,
+ )
+ .await?;
+
+ Ok(StatusCode::NO_CONTENT)
+}
+
+#[utoipa::path(
+ post,
+ path = "/pipedream/mcp/token",
+ tag = "pipedream-mcp",
+ operation_id = "create_pipedream_mcp_token",
+ responses(
+ (status = 200, body = PipedreamTokenResponse),
+ (status = 401, body = String),
+ (status = 501, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// Create a short-lived Pipedream Connect token for the authenticated user.
+///
+/// The frontend opens Pipedream's hosted Connect UI with this token; the
+/// user picks (or is deep-linked into) an app and authorizes it there.
+#[tracing::instrument(skip_all, err)]
+pub async fn create_connect_token<S, P, Auth>(
+ State(state): State<PipedreamRouterState<S, P, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+) -> Result<Json<PipedreamTokenResponse>, PipedreamHandlerErr>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect + ConnectorDirectory,
+ Auth: MacroAuthorizationService,
+{
+ let user = &authorization.authorization.user;
+ let token = state
+ .pipedream()?
+ .create_connect_token(user.macro_user_id.as_ref())
+ .await?;
+
+ Ok(Json(PipedreamTokenResponse {
+ token: token.token,
+ expires_at: token.expires_at,
+ connect_link_url: token.connect_link_url,
+ }))
+}
+
+#[utoipa::path(
+ post,
+ path = "/pipedream/mcp/complete",
+ tag = "pipedream-mcp",
+ operation_id = "complete_pipedream_mcp_connection",
+ request_body = PipedreamCompleteRequest,
+ responses(
+ (status = 200, body = PipedreamConnectionResponse),
+ (status = 401, body = String),
+ (status = 404, body = ErrorResponse),
+ (status = 501, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// Register a connected account reported by the Pipedream Connect UI.
+///
+/// Verifies with Pipedream that the account exists and was connected for
+/// the authenticated user before persisting anything.
+#[tracing::instrument(skip_all, err)]
+pub async fn complete_connection<S, P, Auth>(
+ State(state): State<PipedreamRouterState<S, P, Auth>>,
+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Json(body): Json<PipedreamCompleteRequest>,
+) -> Result<Json<PipedreamConnectionResponse>, PipedreamHandlerErr>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect + ConnectorDirectory,
+ Auth: MacroAuthorizationService,
+ anyhow::Error: From<S::Err>,
+{
+ let user = &authorization.authorization.user;
+ let record = complete_pipedream_connection(
+ state.store.as_ref(),
+ state.pipedream()?.as_ref(),
+ &user.macro_user_id,
+ &body.account_id,
+ body.server_name.as_deref(),
+ )
+ .await?;
+
+ if let Some(hook) = &state.on_auth_completed {
+ hook(record.clone()).await;
+ }
+
+ Ok(Json(PipedreamConnectionResponse::from_record(&record)))
+}
+
+#[utoipa::path(
+ get,
+ path = "/pipedream/mcp/catalog",
+ tag = "pipedream-mcp",
+ operation_id = "browse_pipedream_mcp_catalog",
+ params(PipedreamCatalogParams),
+ responses(
+ (status = 200, body = PipedreamCatalogResponse),
+ (status = 401, body = String),
+ (status = 501, body = ErrorResponse),
+ (status = 500, body = ErrorResponse),
+ )
+)]
+/// Browse or search the catalog of connectable apps.
+///
+/// Curated priority connectors come first (flagged `priority`), followed by
+/// results from Pipedream's app directory.
+#[tracing::instrument(skip_all, err)]
+pub async fn browse_catalog_handler<S, P, Auth>(
+ State(state): State<PipedreamRouterState<S, P, Auth>>,
+ _authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,
+ Query(params): Query<PipedreamCatalogParams>,
+) -> Result<Json<PipedreamCatalogResponse>, PipedreamHandlerErr>
+where
+ S: ConnectionStore,
+ P: PipedreamConnect + ConnectorDirectory,
+ Auth: MacroAuthorizationService,
+{
+ let page = browse_catalog(
+ state.pipedream()?.as_ref(),
+ params.search.as_deref(),
+ params.cursor.as_deref(),
+ params.limit,
+ )
+ .await?;
+
+ Ok(Json(PipedreamCatalogResponse {
+ servers: page.entries.into_iter().map(Into::into).collect(),
+ next_cursor: page.next_cursor,
+ }))
+}
diff --git a/crates/pipedream_mcp/src/inbound/mod.rs b/crates/pipedream_mcp/src/inbound/mod.rs
new file mode 100644
index 0000000000..16683f0b08
--- /dev/null
+++ b/crates/pipedream_mcp/src/inbound/mod.rs
@@ -0,0 +1,4 @@
+/// Axum HTTP adapter for Pipedream MCP connector management.
+pub mod axum_router;
+
+pub use axum_router::{PipedreamRouterState, pipedream_mcp_router};
diff --git a/crates/pipedream_mcp/src/lib.rs b/crates/pipedream_mcp/src/lib.rs
new file mode 100644
index 0000000000..e6072d3152
--- /dev/null
+++ b/crates/pipedream_mcp/src/lib.rs
@@ -0,0 +1,18 @@
+#![deny(missing_docs)]
+//! Pipedream-managed MCP connectors: users connect apps through Pipedream
+//! Connect (Pipedream owns grants, tokens, and refresh), and the AI loop
+//! calls their tools through Pipedream's remote MCP server.
+//!
+//! This crate is fully separate from the native `mcp_client` stack — its own
+//! endpoints (`/pipedream/mcp/*`), its own `pipedream_mcp_connections`
+//! table, and its own toolset. Which stack serves a user's tools is decided
+//! at load time by the `mcp_select` crate.
+
+/// Domain layer: models, ports, and services.
+pub mod domain;
+
+/// Inbound adapters (HTTP/axum).
+pub mod inbound;
+
+/// Outbound adapters for the Pipedream API and Postgres.
+pub mod outbound;
diff --git a/crates/pipedream_mcp/src/outbound/api.rs b/crates/pipedream_mcp/src/outbound/api.rs
new file mode 100644
index 0000000000..2183836b85
--- /dev/null
+++ b/crates/pipedream_mcp/src/outbound/api.rs
@@ -0,0 +1,363 @@
+use crate::domain::models::{
+ CatalogEntry, CatalogPage, ConnectToken, McpServer, PipedreamAccount, PipedreamConnection,
+ client_info,
+};
+use crate::domain::ports::{ConnectorDirectory, McpConnection, PipedreamConnect};
+use anyhow::Context;
+use rmcp::service::ServiceExt;
+use rmcp::transport::StreamableHttpClientTransport;
+use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
+use serde::Deserialize;
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+/// Default base URL of the Pipedream REST API.
+pub const DEFAULT_API_URL: &str = "https://api.pipedream.com";
+
+/// Default URL of Pipedream's hosted remote MCP server.
+pub const DEFAULT_MCP_URL: &str = "https://remote.mcp.pipedream.net";
+
+/// Safety margin subtracted from an access token's lifetime, so we never
+/// present a token about to expire mid-request.
+const TOKEN_EXPIRY_MARGIN: Duration = Duration::from_secs(60);
+
+/// Configuration for [`PipedreamClient`].
+#[derive(Clone, Debug)]
+pub struct PipedreamConfig {
+ /// OAuth client ID for the Pipedream API (project settings → API keys).
+ pub client_id: String,
+ /// OAuth client secret for the Pipedream API.
+ pub client_secret: String,
+ /// The Pipedream Connect project ID (`proj_...`).
+ pub project_id: String,
+ /// The Pipedream project environment: `development` or `production`.
+ pub environment: String,
+ /// Base URL of the Pipedream API. [`DEFAULT_API_URL`] unless overridden.
+ pub api_url: String,
+ /// URL of Pipedream's remote MCP server. [`DEFAULT_MCP_URL`] unless
+ /// overridden.
+ pub mcp_url: String,
+}
+
+/// HTTP adapter for Pipedream Connect and Pipedream's remote MCP server.
+///
+/// Implements [`PipedreamConnect`] (Connect tokens + account lifecycle),
+/// [`ConnectorDirectory`] (the app directory backing the catalog), and
+/// [`McpConnection`] (per-user, per-app MCP sessions). API access tokens are
+/// obtained via the OAuth client-credentials grant and cached until shortly
+/// before expiry.
+pub struct PipedreamClient {
+ http: reqwest::Client,
+ config: PipedreamConfig,
+ access_token: Mutex<Option<CachedToken>>,
+}
+
+#[derive(Clone)]
+struct CachedToken {
+ token: String,
+ valid_until: Instant,
+}
+
+impl PipedreamClient {
+ /// Build a client from config. Fails only if the underlying HTTP client
+ /// can't be constructed.
+ pub fn new(config: PipedreamConfig) -> anyhow::Result<Self> {
+ let http = reqwest::Client::builder()
+ .timeout(Duration::from_secs(30))
+ .build()
+ .context("building Pipedream HTTP client")?;
+ Ok(Self {
+ http,
+ config,
+ access_token: Mutex::new(None),
+ })
+ }
+
+ fn api(&self, path: &str) -> String {
+ format!("{}/v1{path}", self.config.api_url.trim_end_matches('/'))
+ }
+
+ fn connect_api(&self, path: &str) -> String {
+ self.api(&format!("/connect/{}{path}", self.config.project_id))
+ }
+
+ /// A valid API access token, fetched via the client-credentials grant
+ /// and cached until shortly before expiry.
+ async fn access_token(&self) -> anyhow::Result<String> {
+ if let Some(cached) = self.access_token.lock().unwrap().as_ref()
+ && cached.valid_until > Instant::now()
+ {
+ return Ok(cached.token.clone());
+ }
+
+ let response = self
+ .http
+ .post(self.api("/oauth/token"))
+ .form(&[
+ ("grant_type", "client_credentials"),
+ ("client_id", self.config.client_id.as_str()),
+ ("client_secret", self.config.client_secret.as_str()),
+ ])
+ .send()
+ .await
+ .context("requesting Pipedream access token")?;
+ let response = error_for_status(response).await?;
+
+ let token: TokenResponse = response
+ .json()
+ .await
+ .context("decoding Pipedream token response")?;
+
+ let ttl = Duration::from_secs(token.expires_in.unwrap_or(3600))
+ .saturating_sub(TOKEN_EXPIRY_MARGIN);
+ *self.access_token.lock().unwrap() = Some(CachedToken {
+ token: token.access_token.clone(),
+ valid_until: Instant::now() + ttl,
+ });
+
+ Ok(token.access_token)
+ }
+
+ async fn authed(
+ &self,
+ req: reqwest::RequestBuilder,
+ ) -> anyhow::Result<reqwest::RequestBuilder> {
+ Ok(req
+ .bearer_auth(self.access_token().await?)
+ .header("X-PD-Environment", &self.config.environment))
+ }
+}
+
+impl PipedreamConnect for PipedreamClient {
+ #[tracing::instrument(skip(self), err)]
+ async fn create_connect_token(&self, external_user_id: &str) -> anyhow::Result<ConnectToken> {
+ let body = serde_json::json!({
+ "external_user_id": external_user_id,
+ "external_id": external_user_id,
+ });
+
+ let response = self
+ .authed(self.http.post(self.connect_api("/tokens")))
+ .await?
+ .json(&body)
+ .send()
+ .await
+ .context("creating Pipedream connect token")?;
+ let response = error_for_status(response).await?;
+
+ let token: ConnectTokenResponse = response
+ .json()
+ .await
+ .context("decoding Pipedream connect token response")?;
+
+ Ok(ConnectToken {
+ token: token.token,
+ expires_at: token.expires_at,
+ connect_link_url: token.connect_link_url,
+ })
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn get_account(&self, account_id: &str) -> anyhow::Result<Option<PipedreamAccount>> {
+ let response = self
+ .authed(
+ self.http
+ .get(self.connect_api(&format!("/accounts/{account_id}"))),
+ )
+ .await?
+ .send()
+ .await
+ .context("fetching Pipedream account")?;
+
+ if response.status() == reqwest::StatusCode::NOT_FOUND {
+ return Ok(None);
+ }
+ let response = error_for_status(response).await?;
+
+ // Tolerate both a bare account object and a `{"data": ...}` envelope.
+ let body: serde_json::Value = response
+ .json()
+ .await
+ .context("decoding Pipedream account response")?;
+ let account = body.get("data").unwrap_or(&body).clone();
+ let account: AccountResponse =
+ serde_json::from_value(account).context("parsing Pipedream account")?;
+
+ Ok(Some(PipedreamAccount {
+ id: account.id,
+ external_user_id: account.external_id,
+ app_slug: account.app.name_slug,
+ app_name: account.app.name,
+ healthy: account.healthy.unwrap_or(true),
+ }))
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn delete_account(&self, account_id: &str) -> anyhow::Result<()> {
+ let response = self
+ .authed(
+ self.http
+ .delete(self.connect_api(&format!("/accounts/{account_id}"))),
+ )
+ .await?
+ .send()
+ .await
+ .context("deleting Pipedream account")?;
+
+ if response.status() == reqwest::StatusCode::NOT_FOUND {
+ // Already gone remotely — nothing left to revoke.
+ return Ok(());
+ }
+ error_for_status(response).await?;
+ Ok(())
+ }
+}
+
+impl ConnectorDirectory for PipedreamClient {
+ #[tracing::instrument(skip(self), err)]
+ async fn search(
+ &self,
+ search: Option<&str>,
+ cursor: Option<&str>,
+ limit: u32,
+ ) -> anyhow::Result<CatalogPage> {
+ let mut query: Vec<(&str, String)> = vec![("limit", limit.to_string())];
+ if let Some(search) = search {
+ query.push(("q", search.to_owned()));
+ }
+ if let Some(cursor) = cursor {
+ query.push(("after", cursor.to_owned()));
+ }
+
+ let response = self
+ .authed(self.http.get(self.api("/apps")))
+ .await?
+ .query(&query)
+ .send()
+ .await
+ .context("querying Pipedream app directory")?;
+ let response = error_for_status(response).await?;
+
+ let body: AppsResponse = response
+ .json()
+ .await
+ .context("decoding Pipedream apps response")?;
+
+ // The page is exhausted when it comes back short; `end_cursor` alone
+ // can't tell us, since it's present on the last page too.
+ let next_cursor = if body.data.len() < limit as usize {
+ None
+ } else {
+ body.page_info.and_then(|p| p.end_cursor)
+ };
+
+ let entries = body
+ .data
+ .into_iter()
+ // Apps without an auth flow have nothing to connect.
+ .filter(|app| app.auth_type.as_deref() != Some("none"))
+ .map(|app| CatalogEntry {
+ app_slug: app.name_slug,
+ display_name: app.name,
+ description: Some(app.description).filter(|d| !d.is_empty()),
+ icon_url: Some(app.img_src).filter(|u| u.starts_with("https://")),
+ priority: false,
+ })
+ .collect();
+
+ Ok(CatalogPage {
+ entries,
+ next_cursor,
+ })
+ }
+}
+
+impl McpConnection for PipedreamClient {
+ #[tracing::instrument(skip_all, err, fields(app = %record.app_slug, user_id = %record.user_id))]
+ async fn connect(&self, record: &PipedreamConnection) -> anyhow::Result<McpServer> {
+ let token = self.access_token().await?;
+
+ let mut headers = reqwest::header::HeaderMap::new();
+ let mut auth = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))
+ .map_err(|e| anyhow::anyhow!("invalid bearer token: {e}"))?;
+ auth.set_sensitive(true);
+ headers.insert(reqwest::header::AUTHORIZATION, auth);
+ let header = |v: &str| reqwest::header::HeaderValue::from_str(v);
+ headers.insert("x-pd-project-id", header(&self.config.project_id)?);
+ headers.insert("x-pd-environment", header(&self.config.environment)?);
+ headers.insert("x-pd-external-user-id", header(record.user_id.as_ref())?);
+ headers.insert("x-pd-app-slug", header(&record.app_slug)?);
+ // Flat per-app tools; no configuration meta-tools.
+ headers.insert("x-pd-tool-mode", header("tools-only")?);
+
+ let client = reqwest::Client::builder()
+ .default_headers(headers)
+ .build()
+ .context("building Pipedream MCP HTTP client")?;
+
+ let config = StreamableHttpClientTransportConfig::with_uri(&*self.config.mcp_url.clone());
+ let transport = StreamableHttpClientTransport::with_client(client, config);
+ Ok(client_info().serve(transport).await?)
+ }
+}
+
+async fn error_for_status(response: reqwest::Response) -> anyhow::Result<reqwest::Response> {
+ let status = response.status();
+ if status.is_success() {
+ return Ok(response);
+ }
+ let body = response.text().await.unwrap_or_default();
+ anyhow::bail!("Pipedream API returned {status}: {body}");
+}
+
+// -- wire types ---------------------------------------------------------------
+
+#[derive(Deserialize)]
+struct TokenResponse {
+ access_token: String,
+ expires_in: Option<u64>,
+}
+
+#[derive(Deserialize)]
+struct ConnectTokenResponse {
+ token: String,
+ expires_at: String,
+ connect_link_url: String,
+}
+
+#[derive(Deserialize)]
+struct AccountResponse {
+ id: String,
+ external_id: Option<String>,
+ healthy: Option<bool>,
+ app: AccountApp,
+}
+
+#[derive(Deserialize)]
+struct AccountApp {
+ name_slug: String,
+ name: String,
+}
+
+#[derive(Deserialize)]
+struct AppsResponse {
+ data: Vec<AppResponse>,
+ page_info: Option<PageInfo>,
+}
+
+#[derive(Deserialize)]
+struct PageInfo {
+ end_cursor: Option<String>,
+}
+
+#[derive(Deserialize)]
+struct AppResponse {
+ name_slug: String,
+ name: String,
+ #[serde(default)]
+ description: String,
+ #[serde(default)]
+ auth_type: Option<String>,
+ #[serde(default)]
+ img_src: String,
+}
diff --git a/crates/pipedream_mcp/src/outbound/mod.rs b/crates/pipedream_mcp/src/outbound/mod.rs
new file mode 100644
index 0000000000..5c7a38b8e7
--- /dev/null
+++ b/crates/pipedream_mcp/src/outbound/mod.rs
@@ -0,0 +1,4 @@
+/// HTTP adapter for the Pipedream API, the app directory, and the remote MCP server.
+pub mod api;
+/// Postgres repository implementing [`ConnectionStore`](crate::domain::ports::ConnectionStore).
+pub mod pg_connection_repo;
diff --git a/crates/pipedream_mcp/src/outbound/pg_connection_repo.rs b/crates/pipedream_mcp/src/outbound/pg_connection_repo.rs
new file mode 100644
index 0000000000..ea57597cc9
--- /dev/null
+++ b/crates/pipedream_mcp/src/outbound/pg_connection_repo.rs
@@ -0,0 +1,140 @@
+use crate::domain::models::{MacroUserIdStr, PipedreamConnection};
+use crate::domain::ports::ConnectionStore;
+use macro_user_id::cowlike::CowLike;
+use sqlx::PgPool;
+
+/// Postgres-backed [`ConnectionStore`] over the `pipedream_mcp_connections` table.
+///
+/// Rows hold no secrets: Pipedream owns the OAuth grants, we persist only
+/// the app, its display name, and the Pipedream account ID.
+#[derive(Clone)]
+pub struct PgConnectionRepo {
+ pool: PgPool,
+}
+
+impl PgConnectionRepo {
+ /// Create a repository over `pool`.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl ConnectionStore for PgConnectionRepo {
+ type Err = anyhow::Error;
+
+ #[tracing::instrument(skip(self), err)]
+ async fn save(&self, record: &PipedreamConnection) -> Result<(), Self::Err> {
+ sqlx::query!(
+ r#"
+ INSERT INTO pipedream_mcp_connections (user_id, app_slug, server_name, account_id, enabled)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (user_id, app_slug) DO UPDATE SET
+ server_name = EXCLUDED.server_name,
+ account_id = EXCLUDED.account_id,
+ enabled = EXCLUDED.enabled,
+ updated_at = NOW()
+ "#,
+ record.user_id.as_ref(),
+ record.app_slug,
+ record.server_name,
+ record.account_id,
+ record.enabled,
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn load(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ app_slug: &str,
+ ) -> Result<Option<PipedreamConnection>, Self::Err> {
+ let row = sqlx::query!(
+ r#"
+ SELECT user_id, app_slug, server_name, account_id, enabled
+ FROM pipedream_mcp_connections
+ WHERE user_id = $1 AND app_slug = $2
+ "#,
+ user_id.as_ref(),
+ app_slug,
+ )
+ .fetch_optional(&self.pool)
+ .await?;
+
+ row.map(|row| {
+ to_record(
+ row.user_id,
+ row.app_slug,
+ row.server_name,
+ row.account_id,
+ row.enabled,
+ )
+ })
+ .transpose()
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn delete(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ app_slug: &str,
+ ) -> Result<(), Self::Err> {
+ sqlx::query!(
+ "DELETE FROM pipedream_mcp_connections WHERE user_id = $1 AND app_slug = $2",
+ user_id.as_ref(),
+ app_slug,
+ )
+ .execute(&self.pool)
+ .await?;
+ Ok(())
+ }
+
+ #[tracing::instrument(skip(self), err)]
+ async fn list(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ ) -> Result<Vec<PipedreamConnection>, Self::Err> {
+ let rows = sqlx::query!(
+ r#"
+ SELECT user_id, app_slug, server_name, account_id, enabled
+ FROM pipedream_mcp_connections
+ WHERE user_id = $1
+ ORDER BY server_name
+ "#,
+ user_id.as_ref(),
+ )
+ .fetch_all(&self.pool)
+ .await?;
+
+ rows.into_iter()
+ .map(|row| {
+ to_record(
+ row.user_id,
+ row.app_slug,
+ row.server_name,
+ row.account_id,
+ row.enabled,
+ )
+ })
+ .collect()
+ }
+}
+
+fn to_record(
+ user_id: String,
+ app_slug: String,
+ server_name: String,
+ account_id: String,
+ enabled: bool,
+) -> anyhow::Result<PipedreamConnection> {
+ let user_id = MacroUserIdStr::parse_from_str(&user_id)?.into_owned();
+ Ok(PipedreamConnection {
+ user_id,
+ app_slug,
+ server_name,
+ account_id,
+ enabled,
+ })
+}
diff --git a/packages/sdk/generated/cognition/index.ts b/packages/sdk/generated/cognition/index.ts
index 91417dde36..e55b6f99d1 100644
--- a/packages/sdk/generated/cognition/index.ts
+++ b/packages/sdk/generated/cognition/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponse, DismissRunHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, NewAttachment, NewChatMessage, NewMessageAttachment, NotionDocMeta, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, Price, ProjectionStateResponse, ProjectionStatus, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerErrors, RetryGatherHandlerResponse, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, TargetType, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId } from './types.gen';
+export type { AccessLevel, AddMcpServerData, AddMcpServerError, AddMcpServerErrors, AddMcpServerResponse, AddMcpServerResponses, AddServerRequest, AiFeature, AssistantMessagePart, AttachmentMetadata, AttachmentType, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogError, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponse, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolError, CallToolErrors, CallToolRequest, CallToolResponse, CallToolResponse2, CallToolResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponse, DismissRunHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, GenericErrorResponse, GetBatchPreviewData, GetBatchPreviewError, GetBatchPreviewErrors, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchPreviewResponse2, GetBatchPreviewResponses, GetChatData, GetChatError, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerError, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponse, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerError, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponse, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsError, GetChatPermissionsErrors, GetChatPermissionsResponse, GetChatPermissionsResponse2, GetChatPermissionsResponses, GetChatResponse, GetChatResponse2, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerError, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponse, GetChatsForAttachmentHandlerResponses, GetChatsForAttachmentResponse, GetCitationHandlerData, GetCitationHandlerError, GetCitationHandlerErrors, GetCitationHandlerResponse, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerError, GetMemoryHandlerErrors, GetMemoryHandlerResponse, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Response, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponse, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerError, GetUsageHandlerErrors, GetUsageHandlerResponse, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HttpSendChatMessageRequest, ImportEntity, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, NewAttachment, NewChatMessage, NewMessageAttachment, NotionDocMeta, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerErrors, RetryGatherHandlerResponse, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, SendChatMessageData, SendChatMessageError, SendChatMessageErrors, SendChatMessagePayload, SendChatMessageResponse, SendChatMessageResponse2, SendChatMessageResponses, ServerResponse, SetPricingHandlerData, SetPricingHandlerError, SetPricingHandlerErrors, SetPricingHandlerResponses, SetPricingRequest, SharePermissionV2, SlackChannelMeta, SlackParticipant, StartAuthRequest, StartAuthResponse, StartMcpAuthData, StartMcpAuthError, StartMcpAuthErrors, StartMcpAuthResponse, StartMcpAuthResponses, StopChatStreamData, StopChatStreamError, StopChatStreamError2, StopChatStreamErrors, StopChatStreamRequest, StopChatStreamResponse, StopChatStreamResponse2, StopChatStreamResponses, StreamError, StringIdResponse, StructuredCompletionData, StructuredCompletionError, StructuredCompletionError2, StructuredCompletionErrors, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, TargetType, ToolSet, UpdateChannelSharePermission, UpdateMcpServerData, UpdateMcpServerError, UpdateMcpServerErrors, UpdateMcpServerResponse, UpdateMcpServerResponses, UpdateOperation, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionError, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponse, UpdatePipedreamMcpConnectionResponses, UpdateServerRequest, UpdateSharePermissionRequestV2, UpdateToolCallData, UpdateToolCallError, UpdateToolCallErrors, UpdateToolCallRequest, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseError, UpdateToolResponseErrors, UpdateToolResponseRequest, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionError, UpsertAiProjectionErrors, UpsertAiProjectionResponse, UpsertAiProjectionResponses, UpsertProjectionRequest, Usage, UsageRequest, UsageSummary, UserPdfRect, UserToolResponseValue, WebCitation, WithChatId } from './types.gen';
diff --git a/packages/sdk/generated/cognition/sdk.gen.ts b/packages/sdk/generated/cognition/sdk.gen.ts
index d3ca9d61b7..1a7fd72632 100644
--- a/packages/sdk/generated/cognition/sdk.gen.ts
+++ b/packages/sdk/generated/cognition/sdk.gen.ts
@@ -2,7 +2,7 @@
import type { Client, ClientMeta, Options as Options2, RequestResult, TDataShape } from './client';
import { client } from './client.gen';
-import type { AddMcpServerData, AddMcpServerErrors, AddMcpServerResponses, CallToolData, CallToolErrors, CallToolResponses, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponses, CopyChatData, CopyChatErrors, CopyChatResponses, CreateChatData, CreateChatErrors, CreateChatResponses, DeleteChatData, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerErrors, DeleteMcpServerResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponses, GetBatchPreviewData, GetBatchPreviewErrors, GetBatchPreviewResponses, GetChatData, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsErrors, GetChatPermissionsResponses, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponses, GetCitationHandlerData, GetCitationHandlerErrors, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerErrors, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerErrors, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponses, ListMcpServersData, ListMcpServersErrors, ListMcpServersResponses, McpAuthCallbackData, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, PatchChatData, PatchChatErrors, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, RejectToolCallData, RejectToolCallErrors, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerErrors, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatErrors, RevertDeleteChatResponses, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponses, SendChatMessageData, SendChatMessageErrors, SendChatMessageResponses, SetPricingHandlerData, SetPricingHandlerErrors, SetPricingHandlerResponses, StartMcpAuthData, StartMcpAuthErrors, StartMcpAuthResponses, StopChatStreamData, StopChatStreamErrors, StopChatStreamResponses, StructuredCompletionData, StructuredCompletionErrors, StructuredCompletionResponses, UpdateMcpServerData, UpdateMcpServerErrors, UpdateMcpServerResponses, UpdateToolCallData, UpdateToolCallErrors, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseErrors, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionErrors, UpsertAiProjectionResponses } from './types.gen';
+import type { AddMcpServerData, AddMcpServerErrors, AddMcpServerResponses, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolErrors, CallToolResponses, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponses, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponses, CopyChatData, CopyChatErrors, CopyChatResponses, CreateChatData, CreateChatErrors, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponses, DeleteChatData, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerErrors, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponses, DismissRunHandlerData, DismissRunHandlerErrors, DismissRunHandlerResponses, GetBatchPreviewData, GetBatchPreviewErrors, GetBatchPreviewResponses, GetChatData, GetChatErrors, GetChatHistoryBatchMessagesHandlerData, GetChatHistoryBatchMessagesHandlerErrors, GetChatHistoryBatchMessagesHandlerResponses, GetChatHistoryHandlerData, GetChatHistoryHandlerErrors, GetChatHistoryHandlerResponses, GetChatPermissionsData, GetChatPermissionsErrors, GetChatPermissionsResponses, GetChatResponses, GetChatsForAttachmentHandlerData, GetChatsForAttachmentHandlerErrors, GetChatsForAttachmentHandlerResponses, GetCitationHandlerData, GetCitationHandlerErrors, GetCitationHandlerResponses, GetMemoryHandlerData, GetMemoryHandlerErrors, GetMemoryHandlerResponses, GetStateHandler2Data, GetStateHandler2Errors, GetStateHandler2Responses, GetStateHandlerData, GetStateHandlerErrors, GetStateHandlerResponses, GetUsageHandlerData, GetUsageHandlerErrors, GetUsageHandlerResponses, HealthHandlerData, HealthHandlerResponses, ListMcpServersData, ListMcpServersErrors, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponses, McpAuthCallbackData, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, PatchChatData, PatchChatErrors, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, RejectToolCallData, RejectToolCallErrors, RejectToolCallResponses, RetryGatherHandlerData, RetryGatherHandlerErrors, RetryGatherHandlerResponses, RevertDeleteChatData, RevertDeleteChatErrors, RevertDeleteChatResponses, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponses, SendChatMessageData, SendChatMessageErrors, SendChatMessageResponses, SetPricingHandlerData, SetPricingHandlerErrors, SetPricingHandlerResponses, StartMcpAuthData, StartMcpAuthErrors, StartMcpAuthResponses, StopChatStreamData, StopChatStreamErrors, StopChatStreamResponses, StructuredCompletionData, StructuredCompletionErrors, StructuredCompletionResponses, UpdateMcpServerData, UpdateMcpServerErrors, UpdateMcpServerResponses, UpdatePipedreamMcpConnectionData, UpdatePipedreamMcpConnectionErrors, UpdatePipedreamMcpConnectionResponses, UpdateToolCallData, UpdateToolCallErrors, UpdateToolCallResponses, UpdateToolResponseData, UpdateToolResponseErrors, UpdateToolResponseResponses, UpsertAiProjectionData, UpsertAiProjectionErrors, UpsertAiProjectionResponses } from './types.gen';
export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {
/**
@@ -404,6 +404,71 @@ export class Sdk extends HeyApiClient {
});
}
+ /**
+ * Browse or search the catalog of connectable apps.
+ *
+ * Curated priority connectors come first (flagged `priority`), followed by
+ * results from Pipedream's app directory.
+ */
+ public browsePipedreamMcpCatalog<ThrowOnError extends boolean = false>(options?: Options<BrowsePipedreamMcpCatalogData, ThrowOnError>): RequestResult<BrowsePipedreamMcpCatalogResponses, BrowsePipedreamMcpCatalogErrors, ThrowOnError> {
+ return (options?.client ?? this.client).get<BrowsePipedreamMcpCatalogResponses, BrowsePipedreamMcpCatalogErrors, ThrowOnError>({ url: '/pipedream/mcp/catalog', ...options });
+ }
+
+ /**
+ * Register a connected account reported by the Pipedream Connect UI.
+ *
+ * Verifies with Pipedream that the account exists and was connected for
+ * the authenticated user before persisting anything.
+ */
+ public completePipedreamMcpConnection<ThrowOnError extends boolean = false>(options: Options<CompletePipedreamMcpConnectionData, ThrowOnError>): RequestResult<CompletePipedreamMcpConnectionResponses, CompletePipedreamMcpConnectionErrors, ThrowOnError> {
+ return (options.client ?? this.client).post<CompletePipedreamMcpConnectionResponses, CompletePipedreamMcpConnectionErrors, ThrowOnError>({
+ url: '/pipedream/mcp/complete',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Disconnect an app, revoking its Pipedream account.
+ */
+ public deletePipedreamMcpConnection<ThrowOnError extends boolean = false>(options: Options<DeletePipedreamMcpConnectionData, ThrowOnError>): RequestResult<DeletePipedreamMcpConnectionResponses, DeletePipedreamMcpConnectionErrors, ThrowOnError> {
+ return (options.client ?? this.client).delete<DeletePipedreamMcpConnectionResponses, DeletePipedreamMcpConnectionErrors, ThrowOnError>({ url: '/pipedream/mcp/connections', ...options });
+ }
+
+ /**
+ * List the MCP apps connected by the authenticated user.
+ */
+ public listPipedreamMcpConnections<ThrowOnError extends boolean = false>(options?: Options<ListPipedreamMcpConnectionsData, ThrowOnError>): RequestResult<ListPipedreamMcpConnectionsResponses, ListPipedreamMcpConnectionsErrors, ThrowOnError> {
+ return (options?.client ?? this.client).get<ListPipedreamMcpConnectionsResponses, ListPipedreamMcpConnectionsErrors, ThrowOnError>({ url: '/pipedream/mcp/connections', ...options });
+ }
+
+ /**
+ * Rename or enable/disable a connected app.
+ */
+ public updatePipedreamMcpConnection<ThrowOnError extends boolean = false>(options: Options<UpdatePipedreamMcpConnectionData, ThrowOnError>): RequestResult<UpdatePipedreamMcpConnectionResponses, UpdatePipedreamMcpConnectionErrors, ThrowOnError> {
+ return (options.client ?? this.client).put<UpdatePipedreamMcpConnectionResponses, UpdatePipedreamMcpConnectionErrors, ThrowOnError>({
+ url: '/pipedream/mcp/connections',
+ ...options,
+ headers: {
+ 'Content-Type': 'application/json',
+ ...options.headers
+ }
+ });
+ }
+
+ /**
+ * Create a short-lived Pipedream Connect token for the authenticated user.
+ *
+ * The frontend opens Pipedream's hosted Connect UI with this token; the
+ * user picks (or is deep-linked into) an app and authorizes it there.
+ */
+ public createPipedreamMcpToken<ThrowOnError extends boolean = false>(options?: Options<CreatePipedreamMcpTokenData, ThrowOnError>): RequestResult<CreatePipedreamMcpTokenResponses, CreatePipedreamMcpTokenErrors, ThrowOnError> {
+ return (options?.client ?? this.client).post<CreatePipedreamMcpTokenResponses, CreatePipedreamMcpTokenErrors, ThrowOnError>({ url: '/pipedream/mcp/token', ...options });
+ }
+
public getBatchPreview<ThrowOnError extends boolean = false>(options: Options<GetBatchPreviewData, ThrowOnError>): RequestResult<GetBatchPreviewResponses, GetBatchPreviewErrors, ThrowOnError> {
return (options.client ?? this.client).post<GetBatchPreviewResponses, GetBatchPreviewErrors, ThrowOnError>({
url: '/preview',
diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.ts
index 714683704e..8b64edcdef 100644
--- a/packages/sdk/generated/cognition/types.gen.ts
+++ b/packages/sdk/generated/cognition/types.gen.ts
@@ -967,6 +967,116 @@ export type PatchChatRequest = {
sharePermission?: null | UpdateSharePermissionRequestV2;
};
+/**
+ * One connectable app in the catalog.
+ */
+export type PipedreamCatalogEntryResponse = {
+ /**
+ * Pipedream app name slug — pass this to the connect flow.
+ */
+ app_slug: string;
+ /**
+ * One-line description of the app.
+ */
+ description?: string | null;
+ /**
+ * Human-readable name to display.
+ */
+ display_name: string;
+ /**
+ * URL of the app's icon, when available.
+ */
+ icon_url?: string | null;
+ /**
+ * Curated priority connectors rank first and may be rendered as their
+ * own featured section.
+ */
+ priority: boolean;
+};
+
+/**
+ * A page of the connector catalog.
+ */
+export type PipedreamCatalogResponse = {
+ /**
+ * Cursor for the next page. Absent on the last page.
+ */
+ next_cursor?: string | null;
+ /**
+ * Catalog entries in display order (priority connectors first).
+ */
+ servers: Array<PipedreamCatalogEntryResponse>;
+};
+
+/**
+ * Request body for completing a Pipedream connect flow.
+ */
+export type PipedreamCompleteRequest = {
+ /**
+ * The connected-account ID reported by the Connect UI on success.
+ */
+ account_id: string;
+ /**
+ * Optional display name for the connector. Defaults to the app's name
+ * for new connections; existing connections keep their name.
+ */
+ server_name?: string | null;
+};
+
+/**
+ * A connected MCP app as returned by the API.
+ */
+export type PipedreamConnectionResponse = {
+ /**
+ * Pipedream app name slug, e.g. `linear`.
+ */
+ app_slug: string;
+ /**
+ * Whether the connector is enabled for tool use.
+ */
+ enabled: boolean;
+ /**
+ * Human-readable display name.
+ */
+ server_name: string;
+};
+
+/**
+ * Response from creating a Pipedream Connect token.
+ */
+export type PipedreamTokenResponse = {
+ /**
+ * Shareable link that opens the same connect flow in a browser tab.
+ */
+ connect_link_url: string;
+ /**
+ * RFC 3339 expiry of the token.
+ */
+ expires_at: string;
+ /**
+ * Short-lived token to open the Pipedream Connect UI with.
+ */
+ token: string;
+};
+
+/**
+ * Request body for updating a connected app.
+ */
+export type PipedreamUpdateRequest = {
+ /**
+ * The app slug to update.
+ */
+ app_slug: string;
+ /**
+ * Enable or disable the connector.
+ */
+ enabled?: boolean | null;
+ /**
+ * New display name for the connector.
+ */
+ server_name?: string | null;
+};
+
/**
* Resolved price for one completion.
*/
@@ -2432,6 +2542,149 @@ export type CompleteHandlerResponses = {
export type CompleteHandlerResponse = CompleteHandlerResponses[keyof CompleteHandlerResponses];
+export type BrowsePipedreamMcpCatalogData = {
+ body?: never;
+ path?: never;
+ query?: {
+ /**
+ * Search query to filter apps by name. Omit to browse.
+ */
+ search?: string;
+ /**
+ * Opaque pagination cursor from a previous response.
+ */
+ cursor?: string;
+ /**
+ * Page size (default 20, max 50).
+ */
+ limit?: number;
+ };
+ url: '/pipedream/mcp/catalog';
+};
+
+export type BrowsePipedreamMcpCatalogErrors = {
+ 401: string;
+ 500: ErrorResponse;
+ 501: ErrorResponse;
+};
+
+export type BrowsePipedreamMcpCatalogError = BrowsePipedreamMcpCatalogErrors[keyof BrowsePipedreamMcpCatalogErrors];
+
+export type BrowsePipedreamMcpCatalogResponses = {
+ 200: PipedreamCatalogResponse;
+};
+
+export type BrowsePipedreamMcpCatalogResponse = BrowsePipedreamMcpCatalogResponses[keyof BrowsePipedreamMcpCatalogResponses];
+
+export type CompletePipedreamMcpConnectionData = {
+ body: PipedreamCompleteRequest;
+ path?: never;
+ query?: never;
+ url: '/pipedream/mcp/complete';
+};
+
+export type CompletePipedreamMcpConnectionErrors = {
+ 401: string;
+ 404: ErrorResponse;
+ 500: ErrorResponse;
+ 501: ErrorResponse;
+};
+
+export type CompletePipedreamMcpConnectionError = CompletePipedreamMcpConnectionErrors[keyof CompletePipedreamMcpConnectionErrors];
+
+export type CompletePipedreamMcpConnectionResponses = {
+ 200: PipedreamConnectionResponse;
+};
+
+export type CompletePipedreamMcpConnectionResponse = CompletePipedreamMcpConnectionResponses[keyof CompletePipedreamMcpConnectionResponses];
+
+export type DeletePipedreamMcpConnectionData = {
+ body?: never;
+ path?: never;
+ query: {
+ /**
+ * The app slug to disconnect.
+ */
+ app_slug: string;
+ };
+ url: '/pipedream/mcp/connections';
+};
+
+export type DeletePipedreamMcpConnectionErrors = {
+ 401: string;
+ 500: ErrorResponse;
+};
+
+export type DeletePipedreamMcpConnectionError = DeletePipedreamMcpConnectionErrors[keyof DeletePipedreamMcpConnectionErrors];
+
+export type DeletePipedreamMcpConnectionResponses = {
+ 204: void;
+};
+
+export type DeletePipedreamMcpConnectionResponse = DeletePipedreamMcpConnectionResponses[keyof DeletePipedreamMcpConnectionResponses];
+
+export type ListPipedreamMcpConnectionsData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/pipedream/mcp/connections';
+};
+
+export type ListPipedreamMcpConnectionsErrors = {
+ 401: string;
+ 500: ErrorResponse;
+};
+
+export type ListPipedreamMcpConnectionsError = ListPipedreamMcpConnectionsErrors[keyof ListPipedreamMcpConnectionsErrors];
+
+export type ListPipedreamMcpConnectionsResponses = {
+ 200: Array<PipedreamConnectionResponse>;
+};
+
+export type ListPipedreamMcpConnectionsResponse = ListPipedreamMcpConnectionsResponses[keyof ListPipedreamMcpConnectionsResponses];
+
+export type UpdatePipedreamMcpConnectionData = {
+ body: PipedreamUpdateRequest;
+ path?: never;
+ query?: never;
+ url: '/pipedream/mcp/connections';
+};
+
+export type UpdatePipedreamMcpConnectionErrors = {
+ 401: string;
+ 404: ErrorResponse;
+ 500: ErrorResponse;
+};
+
+export type UpdatePipedreamMcpConnectionError = UpdatePipedreamMcpConnectionErrors[keyof UpdatePipedreamMcpConnectionErrors];
+
+export type UpdatePipedreamMcpConnectionResponses = {
+ 200: PipedreamConnectionResponse;
+};
+
+export type UpdatePipedreamMcpConnectionResponse = UpdatePipedreamMcpConnectionResponses[keyof UpdatePipedreamMcpConnectionResponses];
+
+export type CreatePipedreamMcpTokenData = {
+ body?: never;
+ path?: never;
+ query?: never;
+ url: '/pipedream/mcp/token';
+};
+
+export type CreatePipedreamMcpTokenErrors = {
+ 401: string;
+ 500: ErrorResponse;
+ 501: ErrorResponse;
+};
+
+export type CreatePipedreamMcpTokenError = CreatePipedreamMcpTokenErrors[keyof CreatePipedreamMcpTokenErrors];
+
+export type CreatePipedreamMcpTokenResponses = {
+ 200: PipedreamTokenResponse;
+};
+
+export type CreatePipedreamMcpTokenResponse = CreatePipedreamMcpTokenResponses[keyof CreatePipedreamMcpTokenResponses];
+
export type GetBatchPreviewData = {
body: GetBatchPreviewRequest;
path?: never;
diff --git a/packages/sdk/scripts/webhook.ts b/packages/sdk/scripts/webhook.ts
index b026a4a8b4..3fa7db283a 100644
--- a/packages/sdk/scripts/webhook.ts
+++ b/packages/sdk/scripts/webhook.ts
@@ -47,7 +47,8 @@ async function register(): Promise<void> {
const name = required(values.name, '--name');
const events = parseEvents(values.events ?? fail('--events is required'));
const scope = values.scope ?? fail('--scope is required');
- if (scope !== 'user' && scope !== 'team') fail('--scope must be user or team');
+ if (scope !== 'user' && scope !== 'team')
+ fail('--scope must be user or team');
const userId =
scope === 'user'
? required(values['user-id'], '--user-id')
@@ -63,7 +64,8 @@ async function register(): Promise<void> {
filters: [{ events }],
scope,
});
- const secret = webhook.signingSecret ?? fail('webhook signing secret missing');
+ const secret =
+ webhook.signingSecret ?? fail('webhook signing secret missing');
console.log(`
Webhook registered.
diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.json
index 236f94b6d0..a0ddefaea7 100644
--- a/packages/sdk/specs/cognition.json
+++ b/packages/sdk/specs/cognition.json
@@ -1562,6 +1562,347 @@
}
}
},
+ "/pipedream/mcp/catalog": {
+ "get": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Browse or search the catalog of connectable apps.",
+ "description": "Curated priority connectors come first (flagged `priority`), followed by\nresults from Pipedream's app directory.",
+ "operationId": "browse_pipedream_mcp_catalog",
+ "parameters": [
+ {
+ "name": "search",
+ "in": "query",
+ "description": "Search query to filter apps by name. Omit to browse.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "cursor",
+ "in": "query",
+ "description": "Opaque pagination cursor from a previous response.",
+ "required": false,
+ "schema": {
+ "type": "string"
+ }
+ },
+ {
+ "name": "limit",
+ "in": "query",
+ "description": "Page size (default 20, max 50).",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamCatalogResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/pipedream/mcp/complete": {
+ "post": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Register a connected account reported by the Pipedream Connect UI.",
+ "description": "Verifies with Pipedream that the account exists and was connected for\nthe authenticated user before persisting anything.",
+ "operationId": "complete_pipedream_mcp_connection",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamCompleteRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamConnectionResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/pipedream/mcp/connections": {
+ "get": {
+ "tags": ["pipedream-mcp"],
+ "summary": "List the MCP apps connected by the authenticated user.",
+ "operationId": "list_pipedream_mcp_connections",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PipedreamConnectionResponse"
+ }
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "put": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Rename or enable/disable a connected app.",
+ "operationId": "update_pipedream_mcp_connection",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamUpdateRequest"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamConnectionResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ },
+ "delete": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Disconnect an app, revoking its Pipedream account.",
+ "operationId": "delete_pipedream_mcp_connection",
+ "parameters": [
+ {
+ "name": "app_slug",
+ "in": "query",
+ "description": "The app slug to disconnect.",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "204": {
+ "description": ""
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/pipedream/mcp/token": {
+ "post": {
+ "tags": ["pipedream-mcp"],
+ "summary": "Create a short-lived Pipedream Connect token for the authenticated user.",
+ "description": "The frontend opens Pipedream's hosted Connect UI with this token; the\nuser picks (or is deep-linked into) an app and authorizes it there.",
+ "operationId": "create_pipedream_mcp_token",
+ "responses": {
+ "200": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/PipedreamTokenResponse"
+ }
+ }
+ }
+ },
+ "401": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ },
+ "501": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/preview": {
"post": {
"tags": ["get_batch_preview"],
@@ -3625,6 +3966,123 @@
}
}
},
+ "PipedreamCatalogEntryResponse": {
+ "type": "object",
+ "description": "One connectable app in the catalog.",
+ "required": ["app_slug", "display_name", "priority"],
+ "properties": {
+ "app_slug": {
+ "type": "string",
+ "description": "Pipedream app name slug — pass this to the connect flow."
+ },
+ "description": {
+ "type": ["string", "null"],
+ "description": "One-line description of the app."
+ },
+ "display_name": {
+ "type": "string",
+ "description": "Human-readable name to display."
+ },
+ "icon_url": {
+ "type": ["string", "null"],
+ "description": "URL of the app's icon, when available."
+ },
+ "priority": {
+ "type": "boolean",
+ "description": "Curated priority connectors rank first and may be rendered as their\nown featured section."
+ }
+ }
+ },
+ "PipedreamCatalogResponse": {
+ "type": "object",
+ "description": "A page of the connector catalog.",
+ "required": ["servers"],
+ "properties": {
+ "next_cursor": {
+ "type": ["string", "null"],
+ "description": "Cursor for the next page. Absent on the last page."
+ },
+ "servers": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/PipedreamCatalogEntryResponse"
+ },
+ "description": "Catalog entries in display order (priority connectors first)."
+ }
+ }
+ },
+ "PipedreamCompleteRequest": {
+ "type": "object",
+ "description": "Request body for completing a Pipedream connect flow.",
+ "required": ["account_id"],
+ "properties": {
+ "account_id": {
+ "type": "string",
+ "description": "The connected-account ID reported by the Connect UI on success."
+ },
+ "server_name": {
+ "type": ["string", "null"],
+ "description": "Optional display name for the connector. Defaults to the app's name\nfor new connections; existing connections keep their name."
+ }
+ }
+ },
+ "PipedreamConnectionResponse": {
+ "type": "object",
+ "description": "A connected MCP app as returned by the API.",
+ "required": ["app_slug", "server_name", "enabled"],
+ "properties": {
+ "app_slug": {
+ "type": "string",
+ "description": "Pipedream app name slug, e.g. `linear`."
+ },
+ "enabled": {
+ "type": "boolean",
+ "description": "Whether the connector is enabled for tool use."
+ },
+ "server_name": {
+ "type": "string",
+ "description": "Human-readable display name."
+ }
+ }
+ },
+ "PipedreamTokenResponse": {
+ "type": "object",
+ "description": "Response from creating a Pipedream Connect token.",
+ "required": ["token", "expires_at", "connect_link_url"],
+ "properties": {
+ "connect_link_url": {
+ "type": "string",
+ "description": "Shareable link that opens the same connect flow in a browser tab."
+ },
+ "expires_at": {
+ "type": "string",
+ "description": "RFC 3339 expiry of the token."
+ },
+ "token": {
+ "type": "string",
+ "description": "Short-lived token to open the Pipedream Connect UI with."
+ }
+ }
+ },
+ "PipedreamUpdateRequest": {
+ "type": "object",
+ "description": "Request body for updating a connected app.",
+ "required": ["app_slug"],
+ "properties": {
+ "app_slug": {
+ "type": "string",
+ "description": "The app slug to update."
+ },
+ "enabled": {
+ "type": ["boolean", "null"],
+ "description": "Enable or disable the connector."
+ },
+ "server_name": {
+ "type": ["string", "null"],
+ "description": "New display name for the connector."
+ }
+ }
+ },
"Price": {
"type": "object",
"description": "Resolved price for one completion.",
diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.ts
index 3f4f59bb74..9910fd2d01 100644
--- a/packages/sdk/src/coverage/skipped.ts
+++ b/packages/sdk/src/coverage/skipped.ts
@@ -91,7 +91,11 @@ export const authBacklog = [
export const cognitionExcluded = [
'addMcpServer',
+ 'browsePipedreamMcpCatalog',
'callTool',
+ 'completePipedreamMcpConnection',
+ 'createPipedreamMcpToken',
+ 'deletePipedreamMcpConnection',
'deleteMcpServer',
'getBatchPreview',
'getChatHistoryBatchMessagesHandler',
@@ -101,6 +105,7 @@ export const cognitionExcluded = [
'getMemoryHandler',
'healthHandler',
'listMcpServers',
+ 'listPipedreamMcpConnections',
'mcpAuthCallback',
'mcpOauthClientMetadata',
'rejectToolCall',
@@ -113,6 +118,7 @@ export const cognitionExcluded = [
'setPricingHandler',
'startMcpAuth',
'updateMcpServer',
+ 'updatePipedreamMcpConnection',
'updateToolCall',
'updateToolResponse',
'upsertAiProjection',
diff --git a/services/document_cognition_service/Cargo.toml b/services/document_cognition_service/Cargo.toml
index 75f6e74fa5..0db8ab19ce 100644
--- a/services/document_cognition_service/Cargo.toml
+++ b/services/document_cognition_service/Cargo.toml
@@ -84,6 +84,8 @@ macro_user_id = { path = "../../crates/macro_user_id" }
macro_uuid = { path = "../../crates/macro_uuid" }
import = { path = "../../crates/import" }
mcp_client = { path = "../../crates/mcp_client" }
+mcp_select = { path = "../../crates/mcp_select" }
+pipedream_mcp = { path = "../../crates/pipedream_mcp" }
model-error-response = { path = "../../crates/model-error-response" }
memory = { path = "../../crates/memory" }
onboarding = { path = "../../crates/onboarding" }
diff --git a/services/document_cognition_service/src/api/context/mod.rs b/services/document_cognition_service/src/api/context/mod.rs
index c0893c2bab..4f6e5d93fa 100644
--- a/services/document_cognition_service/src/api/context/mod.rs
+++ b/services/document_cognition_service/src/api/context/mod.rs
@@ -111,6 +111,16 @@ pub type DcsOnboardingService = onboarding::domain::service::OnboardingServiceIm
onboarding::outbound::pg_onboarding_repo::PgOnboardingRepo,
mcp_client::outbound::pg_server_repo::PgServerRepo,
DcsImportService,
+ ai_tools::ToolMcpSelector,
+>;
+
+/// Concrete Pipedream MCP router state for DCS: the Postgres connection
+/// store plus the Pipedream client (None when not configured — endpoints
+/// answer 501).
+pub type DcsPipedreamRouterState = pipedream_mcp::inbound::PipedreamRouterState<
+ pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,
+ pipedream_mcp::outbound::api::PipedreamClient,
+ DcsAuthorizationService,
>;
#[derive(Clone, FromRef)]
@@ -144,6 +154,9 @@ pub struct ApiContext {
pub message_service: Arc<DcsMessageService>,
pub ai_stream_registry: AiStreamRegistry,
pub mcp_state: DcsMcpRouterState,
+ pub pipedream_state: DcsPipedreamRouterState,
+ /// Selects which MCP stack (Pipedream vs native) serves a user's tools.
+ pub mcp_selector: Arc<ai_tools::ToolMcpSelector>,
pub import_service: Arc<DcsImportService>,
pub onboarding_service: Arc<DcsOnboardingService>,
/// Kafka-backed macro event broker for publishing domain events.
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index 37f07c8cda..4349dd6f24 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -386,7 +386,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
let all_tools_prompt: Arc<dyn std::fmt::Display + Send + Sync> =
Arc::new(all_tools.prompt.to_string());
- let (import_service, onboarding_service) = {
+ let (import_service, onboarding_service, mcp_selector) = {
let mcp_key =
mcp_client::domain::models::AesKey::try_from(vec![0u8; 32]).expect("valid test key");
let mcp_repo =
@@ -406,9 +406,19 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
),
team_repository: ai_tools::build_team_repository(pool.clone()),
};
+ let mcp_selector: Arc<ai_tools::ToolMcpSelector> =
+ Arc::new(mcp_select::McpToolSelector::new(
+ Arc::new(mcp_repo.clone()),
+ Arc::new(
+ pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo::new(
+ pool.clone(),
+ ),
+ ),
+ Arc::new(None),
+ ));
let import_service = Arc::new(import::domain::service::ImportServiceImpl::new(
import::outbound::pg_import_repo::PgImportRepo::new(pool.clone()),
- Arc::new(mcp_repo.clone()),
+ mcp_selector.clone(),
Arc::new(creator),
ai_usage::pg_recorder(pool.clone()),
));
@@ -416,8 +426,9 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
onboarding::outbound::pg_onboarding_repo::PgOnboardingRepo::new(pool.clone()),
Arc::new(mcp_repo),
import_service.clone(),
+ mcp_selector.clone(),
));
- (import_service, onboarding_service)
+ (import_service, onboarding_service, mcp_selector)
};
let memory_repo = memory::outbound::pg_memory_repo::PgMemoryRepo::new(pool.clone());
@@ -541,6 +552,12 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
ai_stream_registry: crate::service::ai_stream_registry::AiStreamRegistry::new(Arc::new(
redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"),
)),
+ pipedream_state: pipedream_mcp::inbound::PipedreamRouterState::new(
+ pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo::new(pool.clone()),
+ None,
+ authorization_state.clone(),
+ ),
+ mcp_selector,
mcp_state: {
let redis_client =
Arc::new(redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"));
diff --git a/services/document_cognition_service/src/api/mod.rs b/services/document_cognition_service/src/api/mod.rs
index 3ae5728ecb..f3ac7b0607 100644
--- a/services/document_cognition_service/src/api/mod.rs
+++ b/services/document_cognition_service/src/api/mod.rs
@@ -123,6 +123,9 @@ fn api_router(api_context: ApiContext) -> Router {
},
))
.merge(mcp_client::inbound::mcp_router(mcp_state.clone()))
+ .merge(pipedream_mcp::inbound::pipedream_mcp_router(
+ api_context.pipedream_state.clone(),
+ ))
.with_state(api_context.clone());
Router::new()
diff --git a/services/document_cognition_service/src/api/stream/chat_message/mod.rs b/services/document_cognition_service/src/api/stream/chat_message/mod.rs
index e3f1ccb9c9..8caa671b06 100644
--- a/services/document_cognition_service/src/api/stream/chat_message/mod.rs
+++ b/services/document_cognition_service/src/api/stream/chat_message/mod.rs
@@ -30,7 +30,6 @@ use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
use macro_db_client::dcs::create_chat;
use macro_event_broker::MacroEventBroker;
use macro_user_id::user_id::MacroUserIdStr;
-use mcp_client::domain::ports::McpServerStore;
use memory::domain::MemoryService;
use model_entity::{Entity, EntityType};
use models_permissions::share_permission::SharePermissionV2;
@@ -493,7 +492,7 @@ fn stream_and_save_message(
tracing::trace!(request=?request, "streaming chat request");
let tool_context = ctx.tool_service_context.clone();
let static_tools = ctx.all_tools.clone();
- let mcp_store = ctx.mcp_state.store();
+ let mcp_selector = ctx.mcp_selector.clone();
let ctx_outer = ctx.clone();
// Pull the token out so the select below can reference it without moving
@@ -520,15 +519,12 @@ fn stream_and_save_message(
yield json;
}
- let mcp_records = mcp_store.list(&user_id).await.unwrap_or_default();
- let toolset: Arc<dyn ai_toolset::ToolSet<_> + Send + Sync> = Arc::new(
- mcp_client::domain::service::CombinedToolSet::new(
- static_tools,
- &mcp_records,
- mcp_store.clone(),
- )
- .await,
- );
+ let mcp_tools = {
+ use mcp_select::ConnectorSelect;
+ mcp_selector.user_toolset(&user_id).await
+ };
+ let toolset: Arc<dyn ai_toolset::ToolSet<_> + Send + Sync> =
+ Arc::new(mcp_select::CombinedToolSet::new(static_tools, mcp_tools));
let agent_loop =
AgentLoop::new(tool_context.recorder.clone()).with_model(&model);
diff --git a/services/document_cognition_service/src/api/structured_completion.rs b/services/document_cognition_service/src/api/structured_completion.rs
index d79117a221..aaeb2d781e 100644
--- a/services/document_cognition_service/src/api/structured_completion.rs
+++ b/services/document_cognition_service/src/api/structured_completion.rs
@@ -9,7 +9,6 @@ use axum::http::StatusCode;
use axum::response::IntoResponse;
use futures::StreamExt;
use macro_authorization::{MacroAuthorizationExtractor, UserOrInternal};
-use mcp_client::domain::ports::McpServerStore;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::sync::Arc;
@@ -85,15 +84,12 @@ pub async fn structured_completion(
};
// Phase 1: Run agent loop to gather information
- let mcp_store = ctx.mcp_state.store();
- let mcp_records = mcp_store.list(&user_id).await.unwrap_or_default();
+ let mcp_tools = {
+ use mcp_select::ConnectorSelect;
+ ctx.mcp_selector.user_toolset(&user_id).await
+ };
let toolset: Arc<dyn ai_toolset::ToolSet<_> + Send + Sync> = Arc::new(
- mcp_client::domain::service::CombinedToolSet::new(
- ctx.all_tools.clone(),
- &mcp_records,
- mcp_store.clone(),
- )
- .await,
+ mcp_select::CombinedToolSet::new(ctx.all_tools.clone(), mcp_tools),
);
let user_message = ChatMessage {
diff --git a/services/document_cognition_service/src/api/swagger.rs b/services/document_cognition_service/src/api/swagger.rs
index f75aa1d439..7f51459e3a 100644
--- a/services/document_cognition_service/src/api/swagger.rs
+++ b/services/document_cognition_service/src/api/swagger.rs
@@ -29,6 +29,11 @@ use mcp_client::inbound::axum_router::{
};
use memory::inbound::axum_router::{self as memory_api, MemoryErrorBody, MemoryResponse};
use onboarding::inbound::axum_router::{self as onboarding_api, CompleteOnboardingRequest};
+use pipedream_mcp::inbound::axum_router::{
+ self as pipedream_api, PipedreamCatalogEntryResponse, PipedreamCatalogResponse,
+ PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamTokenResponse,
+ PipedreamUpdateRequest,
+};
use crate::api::preview::get_batch_preview::{GetBatchPreviewRequest, GetBatchPreviewResponse};
@@ -101,7 +106,13 @@ use utoipa::OpenApi;
mcp_api::delete_server,
mcp_api::start_auth,
mcp_api::client_metadata,
- mcp_api::auth_callback
+ mcp_api::auth_callback,
+ pipedream_api::list_connections,
+ pipedream_api::update_connection,
+ pipedream_api::delete_connection,
+ pipedream_api::create_connect_token,
+ pipedream_api::complete_connection,
+ pipedream_api::browse_catalog_handler
),
components(
schemas(
@@ -229,6 +240,14 @@ use utoipa::OpenApi;
UpdateServerRequest,
StartAuthRequest,
StartAuthResponse,
+
+ // Pipedream MCP connectors
+ PipedreamConnectionResponse,
+ PipedreamUpdateRequest,
+ PipedreamTokenResponse,
+ PipedreamCompleteRequest,
+ PipedreamCatalogResponse,
+ PipedreamCatalogEntryResponse,
model_error_response::ErrorResponse,
),
),
diff --git a/services/document_cognition_service/src/config.rs b/services/document_cognition_service/src/config.rs
index f23dad4560..346fb0e757 100644
--- a/services/document_cognition_service/src/config.rs
+++ b/services/document_cognition_service/src/config.rs
@@ -27,6 +27,23 @@ env_vars!(
maybe_env_vars!(
pub struct DocumentBatchLimit;
+ /// OAuth client ID for the Pipedream API (Pipedream project settings).
+ /// When unset (along with the other Pipedream credentials), the
+ /// Pipedream MCP endpoints answer 501 and its toolsets come up empty.
+ pub struct PipedreamClientId;
+ /// OAuth client secret for the Pipedream API.
+ pub struct PipedreamClientSecret;
+ /// The Pipedream Connect project ID (`proj_...`).
+ pub struct PipedreamProjectId;
+ /// The Pipedream project environment (`development` or `production`).
+ /// Defaults by deploy environment: production in prd, development
+ /// elsewhere.
+ pub struct PipedreamEnvironment;
+ /// Base URL of the Pipedream API. Defaults to `https://api.pipedream.com`.
+ pub struct PipedreamApiUrl;
+ /// URL of Pipedream's remote MCP server. Defaults to
+ /// `https://remote.mcp.pipedream.net`.
+ pub struct PipedreamMcpUrl;
);
/// The configuration parameters for the application.
@@ -66,6 +83,18 @@ pub struct Config {
LocalOrRemoteSecret<DocumentStorageServiceCloudfrontSignerPrivateKey>,
/// MCP credentials encryption key (base64-encoded, secret name or value)
pub mcp_credentials_key_secret_name: LocalOrRemoteSecret<McpCredentialsKeySecretName>,
+ /// OAuth client ID for the Pipedream API.
+ pub pipedream_client_id: PipedreamClientId,
+ /// OAuth client secret for the Pipedream API.
+ pub pipedream_client_secret: PipedreamClientSecret,
+ /// The Pipedream Connect project ID.
+ pub pipedream_project_id: PipedreamProjectId,
+ /// The Pipedream project environment.
+ pub pipedream_environment: PipedreamEnvironment,
+ /// Base URL of the Pipedream API.
+ pub pipedream_api_url: PipedreamApiUrl,
+ /// URL of Pipedream's remote MCP server.
+ pub pipedream_mcp_url: PipedreamMcpUrl,
/// The internal api key
pub internal_api_key: InternalApiKey,
/// AI editing worker URL
@@ -120,6 +149,12 @@ impl Config {
mcp_credentials_key_secret_name: LocalOrRemoteSecret::Local(
McpCredentialsKeySecretName::Comptime("MCP_CREDENTIALS_KEY_SECRET_NAME"),
),
+ pipedream_client_id: PipedreamClientId::Unset,
+ pipedream_client_secret: PipedreamClientSecret::Unset,
+ pipedream_project_id: PipedreamProjectId::Unset,
+ pipedream_environment: PipedreamEnvironment::Unset,
+ pipedream_api_url: PipedreamApiUrl::Unset,
+ pipedream_mcp_url: PipedreamMcpUrl::Unset,
internal_api_key: InternalApiKey::Comptime(""),
ai_editing_worker_url: AiEditingWorkerUrl::unwrap_new().to_string(),
document_permission_jwt: DocumentPermissionJwt::Comptime("DOCUMENT_PERMISSION_JWT"),
diff --git a/services/document_cognition_service/src/main.rs b/services/document_cognition_service/src/main.rs
index 93fa1841f5..d3774b34b1 100644
--- a/services/document_cognition_service/src/main.rs
+++ b/services/document_cognition_service/src/main.rs
@@ -455,6 +455,59 @@ async fn main() -> anyhow::Result<()> {
let mcp_server_repo =
mcp_client::outbound::pg_server_repo::PgServerRepo::new(db.clone(), mcp_encryption_key);
+ // The Pipedream MCP stack, fully separate from the native one above
+ // (own endpoints, own table, own toolset). Without credentials its
+ // endpoints answer 501 and its toolsets come up empty.
+ let pipedream_client: ai_tools::ToolPipedreamConnection = match (
+ config.pipedream_client_id.value(),
+ config.pipedream_client_secret.value(),
+ config.pipedream_project_id.value(),
+ ) {
+ (Some(client_id), Some(client_secret), Some(project_id)) => Some(Arc::new(
+ pipedream_mcp::outbound::api::PipedreamClient::new(
+ pipedream_mcp::outbound::api::PipedreamConfig {
+ client_id: client_id.to_owned(),
+ client_secret: client_secret.to_owned(),
+ project_id: project_id.to_owned(),
+ environment: config
+ .pipedream_environment
+ .value()
+ .unwrap_or(match config.environment {
+ Environment::Production => "production",
+ _ => "development",
+ })
+ .to_owned(),
+ api_url: config
+ .pipedream_api_url
+ .value()
+ .unwrap_or(pipedream_mcp::outbound::api::DEFAULT_API_URL)
+ .to_owned(),
+ mcp_url: config
+ .pipedream_mcp_url
+ .value()
+ .unwrap_or(pipedream_mcp::outbound::api::DEFAULT_MCP_URL)
+ .to_owned(),
+ },
+ )
+ .context("failed to build Pipedream client")?,
+ )),
+ _ => {
+ tracing::info!("Pipedream credentials not set; Pipedream MCP connectors disabled");
+ None
+ }
+ };
+ let pipedream_repo =
+ pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo::new(db.clone());
+
+ // The one sanctioned meeting point of the two MCP stacks: agents load
+ // tools through this selector, which prefers a user's Pipedream
+ // connectors and falls back to the native ones (see `mcp_select`).
+ let mcp_selector: Arc<ai_tools::ToolMcpSelector> = Arc::new(mcp_select::McpToolSelector::new(
+ Arc::new(mcp_server_repo.clone()),
+ Arc::new(pipedream_repo.clone()),
+ Arc::new(pipedream_client.clone()),
+ ));
+
// Nudges the user's connected clients when import rows flip, so setup
// sections and chat surfaces update immediately instead of on the next
// poll (see import::outbound::gateway_notifier).
@@ -472,7 +525,7 @@ async fn main() -> anyhow::Result<()> {
let import_service = Arc::new(
import::domain::service::ImportServiceImpl::new(
import::outbound::pg_import_repo::PgImportRepo::new(db.clone()),
- Arc::new(mcp_server_repo.clone()),
+ mcp_selector.clone(),
Arc::new(entity_creator),
recorder.clone(),
)
@@ -596,6 +649,7 @@ async fn main() -> anyhow::Result<()> {
onboarding::outbound::pg_onboarding_repo::PgOnboardingRepo::new(db.clone()),
Arc::new(mcp_server_repo.clone()),
import_service.clone(),
+ mcp_selector.clone(),
));
tracing::info!("initialized onboarding service");
@@ -639,6 +693,30 @@ async fn main() -> anyhow::Result<()> {
)
.with_auth_completed_hook(mcp_auth_hook);
+ // The Pipedream stack gets the same post-connect reconcile hook as the
+ // native one: a finished Connect flow starts gather jobs immediately.
+ let onboarding_for_pipedream_hook = onboarding_service.clone();
+ let pipedream_auth_hook: pipedream_mcp::inbound::axum_router::PipedreamAuthCompletedHook =
+ Arc::new(
+ move |connection: pipedream_mcp::domain::models::PipedreamConnection| {
+ let service = onboarding_for_pipedream_hook.clone();
+ Box::pin(async move {
+ tokio::spawn(async move {
+ use onboarding::domain::service::OnboardingService;
+ if let Err(e) = service.reconcile(connection.user_id).await {
+ tracing::warn!(error = ?e, "post-connect onboarding reconcile failed");
+ }
+ });
+ })
+ },
+ );
+ let pipedream_state = pipedream_mcp::inbound::PipedreamRouterState::new(
+ pipedream_repo,
+ pipedream_client,
+ authorization_state.clone(),
+ )
+ .with_auth_completed_hook(pipedream_auth_hook);
+
let user_permissions_service = Arc::new(
roles_and_permissions::domain::service::UserRolesAndPermissionsServiceImpl::new(
roles_and_permissions::outbound::pgpool::MacroDB::new(db.clone()),
@@ -678,6 +756,8 @@ async fn main() -> anyhow::Result<()> {
redis_client.clone(),
),
mcp_state,
+ pipedream_state,
+ mcp_selector,
import_service,
onboarding_service,
macro_event_broker: macro_event_broker.clone(),