Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(mcp): connect apps through Macro Connect behind the macro-connect flag (#9437)
Eric Hayes026a9be5d950
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex 1e87f399db..c1292cb5d9 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -433,6 +433,7 @@"crates/channel_sender","crates/channels","crates/comms_db_client",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -585,6 +586,7 @@"crates/codex_cloud_agents","crates/codex_connection","crates/comms_db_client",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -747,6 +749,7 @@"crates/cognition","crates/collab_surface","crates/comms_db_client",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -946,6 +949,7 @@"crates/cognition","crates/collab_surface","crates/comms_db_client",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -1826,6 +1830,7 @@"crates/cognition","crates/collab_surface","crates/comms_db_client",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -2006,6 +2011,7 @@"crates/cognition","crates/collab_surface","crates/comms_db_client",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -3133,6 +3139,7 @@"crates/cognition","crates/collab_surface","crates/comms_db_client",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -4263,6 +4270,11 @@"crates/work_feed","crates/workspace-hack"],+ "connect_client": [+ "crates/connect_client",+ "crates/macro_tower_layers",+ "crates/workspace-hack"+ ],"connection": ["crates/agent","crates/ai_toolset",@@ -5253,6 +5265,7 @@"crates/collab_surface","crates/comms_db_client","crates/complete_graph",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -7520,6 +7533,7 @@"crates/call","crates/channel_sender","crates/channels",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -9448,6 +9462,7 @@"crates/call","crates/channel_sender","crates/channels",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -9548,6 +9563,7 @@"crates/ai_toolset","crates/bot_id","crates/bot_token",+ "crates/connect_client","crates/cowlike","crates/genai_telemetry","crates/harness_id",@@ -9558,6 +9574,7 @@"crates/macro_authorization","crates/macro_env","crates/macro_env_var",+ "crates/macro_tower_layers","crates/macro_user_id","crates/mcp_toolset","crates/model-error-response",@@ -9570,6 +9587,7 @@"crates/ai_toolset","crates/bot_id","crates/bot_token",+ "crates/connect_client","crates/cowlike","crates/genai_telemetry","crates/harness_id",@@ -9580,6 +9598,7 @@"crates/macro_authorization","crates/macro_env","crates/macro_env_var",+ "crates/macro_tower_layers","crates/macro_user_id","crates/mcp_toolset","crates/model-error-response",@@ -9592,6 +9611,7 @@"crates/ai_toolset","crates/bot_id","crates/bot_token",+ "crates/connect_client","crates/cowlike","crates/genai_telemetry","crates/harness_id",@@ -9601,6 +9621,7 @@"crates/macro_authorization","crates/macro_env","crates/macro_env_var",+ "crates/macro_tower_layers","crates/macro_user_id","crates/mcp_toolset","crates/model-error-response",@@ -9613,6 +9634,7 @@"crates/ai_toolset","crates/bot_id","crates/bot_token",+ "crates/connect_client","crates/cowlike","crates/genai_telemetry","crates/harness_id",@@ -9622,6 +9644,7 @@"crates/macro_authorization","crates/macro_env","crates/macro_env_var",+ "crates/macro_tower_layers","crates/macro_user_id","crates/mcp_toolset","crates/model-error-response",@@ -10464,6 +10487,7 @@"crates/authentication_service_client","crates/bot_id","crates/bot_token",+ "crates/connect_client","crates/cowlike","crates/document_sub_type","crates/genai_telemetry",@@ -10473,6 +10497,7 @@"crates/macro_authorization","crates/macro_env","crates/macro_env_var",+ "crates/macro_tower_layers","crates/macro_user_id","crates/macro_uuid","crates/mcp_client",@@ -11647,6 +11672,7 @@"crates/ai_toolset","crates/bot_id","crates/bot_token",+ "crates/connect_client","crates/cowlike","crates/genai_telemetry","crates/harness_id",@@ -11655,6 +11681,7 @@"crates/macro_authorization","crates/macro_env","crates/macro_env_var",+ "crates/macro_tower_layers","crates/macro_user_id","crates/mcp_toolset","crates/model-error-response",@@ -12985,6 +13012,7 @@"crates/call","crates/channel_sender","crates/channels",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",@@ -13105,6 +13133,7 @@"crates/call","crates/channel_sender","crates/channels",+ "crates/connect_client","crates/connection","crates/connection_gateway_client","crates/connection_gateway_models",diff --git a/.sqlx/query-c3707d03d63e155f111c0f9120d96f3ccdcfcc68426cef82c54ff04e2d64c161.json b/.sqlx/query-1b4ba52ab6f25493e9435de63c974e819c4d1e7b3023c05c2ee7639f865ed52a.jsonsimilarity index 63%rename from .sqlx/query-c3707d03d63e155f111c0f9120d96f3ccdcfcc68426cef82c54ff04e2d64c161.jsonrename to .sqlx/query-1b4ba52ab6f25493e9435de63c974e819c4d1e7b3023c05c2ee7639f865ed52a.jsonindex 7e297ca514..3034799862 100644--- a/.sqlx/query-c3707d03d63e155f111c0f9120d96f3ccdcfcc68426cef82c54ff04e2d64c161.json+++ b/.sqlx/query-1b4ba52ab6f25493e9435de63c974e819c4d1e7b3023c05c2ee7639f865ed52a.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT user_id, app_slug, server_name, account_id, enabled\n FROM pipedream_mcp_connections c\n WHERE user_id = $1\n AND NOT EXISTS (SELECT 1 FROM mcp_overlays o WHERE o.app_slug = c.app_slug)\n ORDER BY server_name\n ",+ "query": "\n SELECT user_id, app_slug, server_name, account_id, enabled, provider\n FROM pipedream_mcp_connections c\n WHERE user_id = $1\n AND NOT EXISTS (SELECT 1 FROM mcp_overlays o WHERE o.app_slug = c.app_slug)\n ORDER BY server_name\n ","describe": {"columns": [{@@ -27,6 +27,11 @@"ordinal": 4,"name": "enabled","type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "provider",+ "type_info": "Text"}],"parameters": {@@ -39,8 +44,9 @@false,false,false,+ false,false]},- "hash": "c3707d03d63e155f111c0f9120d96f3ccdcfcc68426cef82c54ff04e2d64c161"+ "hash": "1b4ba52ab6f25493e9435de63c974e819c4d1e7b3023c05c2ee7639f865ed52a"}diff --git a/.sqlx/query-4c32958c36e27ce1c888c698d4a9acab528633579fa562f4b287cb4ee7c7fa2e.json b/.sqlx/query-4c32958c36e27ce1c888c698d4a9acab528633579fa562f4b287cb4ee7c7fa2e.jsonnew file mode 100644index 0000000000..16492a93d5--- /dev/null+++ b/.sqlx/query-4c32958c36e27ce1c888c698d4a9acab528633579fa562f4b287cb4ee7c7fa2e.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO pipedream_mcp_connections (user_id, app_slug, server_name, account_id)\n VALUES ($1, 'linear', 'Linear', 'apn_linear')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "4c32958c36e27ce1c888c698d4a9acab528633579fa562f4b287cb4ee7c7fa2e"+}diff --git a/.sqlx/query-96b06d2aa00d3a1a0e0975ba9d27381f2ca50a3aeee0da22069a00c5c14769fe.json b/.sqlx/query-5059c329fd5116f716830e3a47e7a2b30d592fa6aa9a732915efd93e42dd7f64.jsonsimilarity index 65%rename from .sqlx/query-96b06d2aa00d3a1a0e0975ba9d27381f2ca50a3aeee0da22069a00c5c14769fe.jsonrename to .sqlx/query-5059c329fd5116f716830e3a47e7a2b30d592fa6aa9a732915efd93e42dd7f64.jsonindex 92ddf1c802..3d1ae89223 100644--- a/.sqlx/query-96b06d2aa00d3a1a0e0975ba9d27381f2ca50a3aeee0da22069a00c5c14769fe.json+++ b/.sqlx/query-5059c329fd5116f716830e3a47e7a2b30d592fa6aa9a732915efd93e42dd7f64.json@@ -1,6 +1,6 @@{"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 AND NOT EXISTS (SELECT 1 FROM mcp_overlays o WHERE o.app_slug = $2)\n ",+ "query": "\n SELECT user_id, app_slug, server_name, account_id, enabled, provider\n FROM pipedream_mcp_connections\n WHERE user_id = $1 AND app_slug = $2\n AND NOT EXISTS (SELECT 1 FROM mcp_overlays o WHERE o.app_slug = $2)\n ","describe": {"columns": [{@@ -27,6 +27,11 @@"ordinal": 4,"name": "enabled","type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "provider",+ "type_info": "Text"}],"parameters": {@@ -40,8 +45,9 @@false,false,false,+ false,false]},- "hash": "96b06d2aa00d3a1a0e0975ba9d27381f2ca50a3aeee0da22069a00c5c14769fe"+ "hash": "5059c329fd5116f716830e3a47e7a2b30d592fa6aa9a732915efd93e42dd7f64"}diff --git a/.sqlx/query-9bb0c84cfdbb24adebbe1b353b2e7eca014bcee5d23b98848be98e730fda35dc.json b/.sqlx/query-9bb0c84cfdbb24adebbe1b353b2e7eca014bcee5d23b98848be98e730fda35dc.jsondeleted file mode 100644index 461e85d094..0000000000--- a/.sqlx/query-9bb0c84cfdbb24adebbe1b353b2e7eca014bcee5d23b98848be98e730fda35dc.json+++ /dev/null@@ -1,18 +0,0 @@-{- "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-aba2b4289c2cbc48d57a2f4f41c4af93afa7c2b993296ac2c5b93fa5dadadd7b.json b/.sqlx/query-aba2b4289c2cbc48d57a2f4f41c4af93afa7c2b993296ac2c5b93fa5dadadd7b.jsonnew file mode 100644index 0000000000..4cdb4aefa7--- /dev/null+++ b/.sqlx/query-aba2b4289c2cbc48d57a2f4f41c4af93afa7c2b993296ac2c5b93fa5dadadd7b.json@@ -0,0 +1,19 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO pipedream_mcp_connections (user_id, app_slug, server_name, account_id, enabled, provider)\n VALUES ($1, $2, $3, $4, $5, $6)\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 provider = EXCLUDED.provider,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text",+ "Text",+ "Bool",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "aba2b4289c2cbc48d57a2f4f41c4af93afa7c2b993296ac2c5b93fa5dadadd7b"+}diff --git a/.sqlx/query-b3d092e08c04b80153179a25d557f47d30e12564210656a527637e64a7568af3.json b/.sqlx/query-b3d092e08c04b80153179a25d557f47d30e12564210656a527637e64a7568af3.jsonnew file mode 100644index 0000000000..17281dbb67--- /dev/null+++ b/.sqlx/query-b3d092e08c04b80153179a25d557f47d30e12564210656a527637e64a7568af3.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE \"User\" SET id = $1 WHERE id = $2",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "b3d092e08c04b80153179a25d557f47d30e12564210656a527637e64a7568af3"+}diff --git a/.sqlx/query-0b7dc8cc80a488395f529ad634f8e3452bdf649842ef7c9ca7322cf52541d885.json b/.sqlx/query-b8954cc95877b61dd1046a100e6314b5f8df7a490af3e598a452cd2f7d4f7c31.jsonsimilarity index 65%rename from .sqlx/query-0b7dc8cc80a488395f529ad634f8e3452bdf649842ef7c9ca7322cf52541d885.jsonrename to .sqlx/query-b8954cc95877b61dd1046a100e6314b5f8df7a490af3e598a452cd2f7d4f7c31.jsonindex 84be485ec9..40a8004329 100644--- a/.sqlx/query-0b7dc8cc80a488395f529ad634f8e3452bdf649842ef7c9ca7322cf52541d885.json+++ b/.sqlx/query-b8954cc95877b61dd1046a100e6314b5f8df7a490af3e598a452cd2f7d4f7c31.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT user_id, app_slug, server_name, account_id, enabled\n FROM pipedream_mcp_connections\n WHERE app_slug = $1 AND enabled\n AND NOT EXISTS (SELECT 1 FROM mcp_overlays o WHERE o.app_slug = $1)\n ",+ "query": "\n SELECT user_id, app_slug, server_name, account_id, enabled, provider\n FROM pipedream_mcp_connections\n WHERE app_slug = $1 AND enabled\n AND NOT EXISTS (SELECT 1 FROM mcp_overlays o WHERE o.app_slug = $1)\n ","describe": {"columns": [{@@ -27,6 +27,11 @@"ordinal": 4,"name": "enabled","type_info": "Bool"+ },+ {+ "ordinal": 5,+ "name": "provider",+ "type_info": "Text"}],"parameters": {@@ -39,8 +44,9 @@false,false,false,+ false,false]},- "hash": "0b7dc8cc80a488395f529ad634f8e3452bdf649842ef7c9ca7322cf52541d885"+ "hash": "b8954cc95877b61dd1046a100e6314b5f8df7a490af3e598a452cd2f7d4f7c31"}diff --git a/Cargo.lock b/Cargo.lockindex 85fff06018..7f4fcac614 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1165,6 +1165,7 @@ dependencies = ["entity_registry","entity_registry_db_utils","favorites",+ "feature_flags","foreign_entity","forms","frecency",@@ -1241,6 +1242,7 @@ dependencies = ["tokio-util","tracing","unicode-segmentation",+ "url","utoipa","uuid","workspace-hack",@@ -4879,6 +4881,27 @@ dependencies = ["crossbeam-utils",]+[[package]]+name = "connect_client"+version = "0.1.0"+dependencies = [+ "chrono",+ "macro_tower_layers",+ "reqwest 0.13.4",+ "rootcause",+ "serde",+ "serde_json",+ "strum 0.27.2",+ "thiserror 2.0.18",+ "tokio",+ "tracing",+ "url",+ "utoipa",+ "wiremock",+ "workspace-hack",+ "zeroize",+]+[[package]]name = "connection"version = "0.1.0"@@ -15273,6 +15296,7 @@ dependencies = ["axum","base64 0.22.1","chrono",+ "connect_client","futures","http 1.4.0","macro_authorization",diff --git a/Cargo.toml b/Cargo.tomlindex 2c8a0d5c7d..fb6322bea4 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -37,6 +37,7 @@ members = ["crates/cognition","crates/codex_cloud_agents","crates/codex_connection",+ "crates/connect_client","crates/collab_surface","crates/complete_graph","crates/cowlike",diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.tsindex 4ed4803428..c671550ac8 100644--- a/apps/web/src/lib/core/constant/featureFlags.ts+++ b/apps/web/src/lib/core/constant/featureFlags.ts@@ -150,6 +150,17 @@ export const PROD_MODE_ENV = import.meta.env.MODE === 'production';const onInDev = DEV_MODE_ENV || undefined;+/**+ * Connect apps Macro Connect serves through it instead of Pipedream. The+ * backend reads the same PostHog key and decides per app; this side only+ * reserves the consent popup inside the click. Off in dev too: dev has no+ * Connect customer key until one is added to Doppler.+ */+export const macroConnect = defineFlag({+ key: 'macro-connect',+ env: 'ENABLE_MACRO_CONNECT',+});+/** Browser-style tabs in the macOS desktop title bar; each tab holds a split layout. */export const enableDesktopTabs = defineFlag({key: 'enable-desktop-tabs',diff --git a/apps/web/src/lib/queries/pipedream-connectors.test.ts b/apps/web/src/lib/queries/pipedream-connectors.test.tsindex 2822b7efdd..2ebf9db4f9 100644--- a/apps/web/src/lib/queries/pipedream-connectors.test.ts+++ b/apps/web/src/lib/queries/pipedream-connectors.test.ts@@ -18,6 +18,8 @@ const mocks = vi.hoisted(() => ({reservePopup: vi.fn(),assignUrl: vi.fn(),linkGithub: vi.fn(),+ completeConnect: vi.fn(),+ macroConnect: false,overlays: [] as { app_slug: string; server_url: string }[],overlaysUnavailable: false,cachedOverlays: undefined as@@ -25,6 +27,10 @@ const mocks = vi.hoisted(() => ({| undefined,}));vi.mock('@core/util/platform', () => ({ isTauri: () => mocks.native }));+vi.mock('@core/constant/featureFlags', () => ({+ macroConnect: { key: 'macro-connect' },+ isFeatureEnabled: () => mocks.macroConnect,+}));vi.mock('@core/auth/authorize-github', () => ({linkGithubAccount: mocks.linkGithub,}));@@ -58,6 +64,7 @@ vi.mock('@service-cognition/client', () => ({completePipedreamConnection: mocks.complete,startMcpAuth: mocks.startAuth,recoverPipedreamConnection: mocks.recover,+ completeMacroConnect: mocks.completeConnect,},}));@@ -70,6 +77,7 @@ beforeEach(() => {mocks.overlays = [];mocks.overlaysUnavailable = false;mocks.cachedOverlays = undefined;+ mocks.macroConnect = false;mocks.token.mockImplementation(async () => ok({ token: 'fixture' }));mocks.open.mockImplementation(() => ({ close: mocks.close }));mocks.openNative.mockImplementation(() => ({ close: mocks.close }));@@ -320,3 +328,71 @@ describe('overlaidAppSlug', () => {).toBeUndefined();});});++describe('apps Macro Connect serves', () => {+ const popup = { closed: false, close: vi.fn() };+ const notYet = err([{ code: 'NOT_FOUND', message: 'Resource not found' }]);++ beforeEach(() => {+ vi.useFakeTimers();+ popup.closed = false;+ mocks.macroConnect = true;+ mocks.reservePopup.mockReturnValue(popup);+ mocks.token.mockResolvedValue(+ ok({ provider: 'connect', connect_url: 'https://connect.test/c/tok' })+ );+ return () => vi.useRealTimers();+ });++ it('opens Connect in the reserved tab and records the app once Connect confirms it', async () => {+ mocks.completeConnect+ .mockResolvedValueOnce(notYet)+ .mockResolvedValueOnce(+ ok({ app_slug: 'linear', server_name: 'Linear', enabled: true })+ );++ const pending = connectPipedreamApp({ appSlug: 'linear' });+ await vi.runAllTimersAsync();++ await expect(pending).resolves.toBe('connected');+ expect(mocks.token).toHaveBeenCalledWith({ app_slug: 'linear' });+ expect(mocks.assignUrl).toHaveBeenCalledWith(+ popup,+ 'https://connect.test/c/tok'+ );+ expect(mocks.completeConnect).toHaveBeenCalledTimes(2);+ expect(mocks.open).not.toHaveBeenCalled();+ expect(mocks.setData).toHaveBeenCalled();+ });++ it('reports closed when the tab closes before Connect has the app', async () => {+ mocks.completeConnect.mockImplementation(async () => {+ popup.closed = true;+ return notYet;+ });++ const pending = connectPipedreamApp({ appSlug: 'linear' });+ await vi.runAllTimersAsync();++ await expect(pending).resolves.toBe('closed');+ expect(mocks.setData).not.toHaveBeenCalled();+ });++ it('closes the reserved tab and uses Pipedream when the backend answers with a token', async () => {+ mocks.token.mockResolvedValue(ok({ provider: 'pipedream', token: 'pd' }));+ mocks.open.mockImplementation(({ onEvent }) => {+ onEvent({ type: 'close' });+ return { close: mocks.close };+ });++ const pending = connectPipedreamApp({ appSlug: 'linear' });+ await vi.runAllTimersAsync();++ await expect(pending).resolves.toBe('closed');+ expect(popup.close).toHaveBeenCalled();+ expect(mocks.open).toHaveBeenCalledWith(+ expect.objectContaining({ token: 'pd', app: 'linear' })+ );+ expect(mocks.completeConnect).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/queries/pipedream-connectors.ts b/apps/web/src/lib/queries/pipedream-connectors.tsindex 487f8f8947..6e05d81a12 100644--- a/apps/web/src/lib/queries/pipedream-connectors.ts+++ b/apps/web/src/lib/queries/pipedream-connectors.ts@@ -1,4 +1,5 @@import { linkGithubAccount } from '@core/auth/authorize-github';+import { isFeatureEnabled, macroConnect } from '@core/constant/featureFlags';import {openPipedreamConnectUI,type PipedreamConnectEvent,@@ -304,6 +305,11 @@ let pipedreamUnsupported = false;* GitHub's server is authorized by the Macro GitHub account link, so GitHub* links the account instead.*+ * With the `macro-connect` flag, the backend may route the app through Macro+ * Connect instead of Pipedream: consent then runs on Connect's page in a+ * popup (web) or the system browser (native), and the connection is+ * recorded once Connect confirms 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@@ -323,8 +329,13 @@ export async function connectPipedreamApp(args: {const cachedOverlay = queryClient.getQueryData<PipedreamOverlayResponse[]>(KEYS.overlays)?.find((overlay) => overlay.app_slug === args.appSlug);+ // A Macro Connect consent page also needs its tab reserved now; it is+ // closed again if the backend answers with a Pipedream token.const popup =- cachedOverlay && !linksGithub(cachedOverlay) ? reserveOauthPopup() : null;+ (cachedOverlay && !linksGithub(cachedOverlay)) ||+ (!cachedOverlay && isFeatureEnabled(macroConnect))+ ? reserveOauthPopup()+ : null;return Telemetry.span('pipedream.connect', async (span) => {span.setAttr('connector.app_slug', args.appSlug);span.setAttr('connector.native', isTauri());@@ -333,7 +344,7 @@ export async function connectPipedreamApp(args: {cachedOverlay ?? (await lookUpOverlay(args.appSlug, span));span.setAttr('connector.overlaid', overlay !== undefined);const outcome = !overlay- ? await connectPipedreamAccount(args, span)+ ? await connectPipedreamAccount(args, popup, span): linksGithub(overlay)? await connectGithubLink(span): await connectOverlaidApp(overlay, args, popup, span);@@ -453,21 +464,38 @@ async function connectOverlaidApp(async function connectPipedreamAccount(args: Parameters<typeof connectPipedreamApp>[0],+ popup: Window | null,span: Span): Promise<PipedreamConnectOutcome> {- if (pipedreamUnsupported) return 'unsupported';+ if (pipedreamUnsupported) {+ popup?.close();+ return 'unsupported';+ }const userId = currentUserId();const token = await span.span('pipedream.token', async () =>- cognitionApiServiceClient.createPipedreamToken()+ cognitionApiServiceClient.createPipedreamToken({ app_slug: args.appSlug }));if (token.isErr()) {+ popup?.close();if (token.error.some((e) => e.code === PIPEDREAM_DISABLED)) {pipedreamUnsupported = true;return 'unsupported';}throw new ThrownResultError(token.error);}+ span.setAttr('connector.provider', token.value.provider);+ if (token.value.provider === 'connect' && token.value.connect_url) {+ return connectThroughMacroConnect(+ args,+ token.value.connect_url,+ popup,+ span+ );+ }+ popup?.close();+ const connectToken = token.value.token;+ if (!connectToken) throw new Error('Pipedream returned no connect token');const openConnectUI = isTauri()? (await import('@core/pipedream/connect-native'))@@ -480,7 +508,7 @@ async function connectPipedreamAccount(async () =>new Promise<ConsentResult>((resolve) => {ui = openConnectUI({- token: token.value.token,+ token: connectToken,app: args.appSlug,container: args.container,// 'error' events are shown inside the Connect UI itself; the user@@ -522,6 +550,50 @@ async function connectPipedreamAccount(type ConsentResult = Exclude<PipedreamConnectEvent, { type: 'error' }>;+const MACRO_CONNECT_POLL_MS = 2000;+// Matches Connect's session lifetime.+const MACRO_CONNECT_TIMEOUT_MS = 10 * 60 * 1000;++/**+ * Run Macro Connect's consent page in `popup` (or the system browser), then+ * ask the backend to record the connection until Connect confirms it, the+ * tab is closed, or the session expires. Connect's redirect page cannot+ * message this tab, so completion is polled, as for overlaid apps.+ */+async function connectThroughMacroConnect(+ args: Parameters<typeof connectPipedreamApp>[0],+ connectUrl: string,+ popup: Window | null,+ span: Span+): Promise<PipedreamConnectOutcome> {+ const userId = currentUserId();+ assignOauthUrl(popup, connectUrl);+ return span.span('macro_connect.consent', async () => {+ const deadline = Date.now() + MACRO_CONNECT_TIMEOUT_MS;+ while (Date.now() < deadline && currentUserId() === userId) {+ const closed = popup?.closed ?? false;+ const result = await cognitionApiServiceClient.completeMacroConnect({+ app_slug: args.appSlug,+ server_name: args.serverName,+ });+ if (result.isOk()) {+ if (currentUserId() !== userId) return 'closed';+ upsertConnection(result.value);+ await invalidateConnections();+ return 'connected';+ }+ if (!result.error.some((e) => e.code === 'NOT_FOUND')) {+ throw new ThrownResultError(result.error);+ }+ if (closed) return 'closed';+ await new Promise((resolve) =>+ setTimeout(resolve, MACRO_CONNECT_POLL_MS)+ );+ }+ return 'closed';+ });+}+/*** Pipedream's Connect UI drops its success message when an OAuth provider* severs the consent popup's opener, reporting only a close although thediff --git a/apps/web/src/lib/service-clients/service-cognition/client.ts b/apps/web/src/lib/service-clients/service-cognition/client.tsindex 06c022a9fa..254cf5bc2e 100644--- a/apps/web/src/lib/service-clients/service-cognition/client.ts+++ b/apps/web/src/lib/service-clients/service-cognition/client.ts@@ -78,20 +78,34 @@ 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.+/** The backend holding a connection's grant. */+export type PipedreamProvider = 'pipedream' | 'connect';export type PipedreamConnectionResponse = {app_slug: string;server_name: string;enabled: boolean;+ provider?: PipedreamProvider;};export type PipedreamUpdateRequest = {app_slug: string;server_name?: string;enabled?: boolean;};+export type PipedreamTokenRequest = {+ /** With it, an app Macro Connect serves may answer with a Connect URL. */+ app_slug?: string;+};+/** A Pipedream Connect token, or for `provider: 'connect'` a Connect URL. */export type PipedreamTokenResponse = {- token: string;- expires_at: string;- connect_link_url: string;+ provider: PipedreamProvider;+ token?: string | null;+ expires_at?: string | null;+ connect_link_url?: string | null;+ connect_url?: string | null;+};+export type PipedreamConnectCompleteRequest = {+ app_slug: string;+ server_name?: string;};export type PipedreamCompleteRequest = {account_id: string;@@ -435,17 +449,18 @@ export const cognitionApiServiceClient = {},/**- * Create a Pipedream Connect token for authorizing an MCP connector.+ * Start connecting an MCP connector: a Pipedream Connect token, or a+ * Macro Connect URL when the backend routes `app_slug` through Connect.* Answers with the {@link PIPEDREAM_DISABLED} error code on deployments* where Pipedream isn't configured (HTTP 501).*/- async createPipedreamToken() {+ async createPipedreamToken(args: PipedreamTokenRequest = {}) {return (await fetchWithToken<PipedreamTokenResponse, typeof PIPEDREAM_DISABLED>(`${dcsHost}/pipedream/mcp/token`,{method: 'POST',- body: JSON.stringify({}),+ body: JSON.stringify(args),errorResponseHandler: async (response) => {if (response.status === 501) {return {@@ -473,6 +488,22 @@ export const cognitionApiServiceClient = {).map((result) => result);},+ /**+ * Record an app connected through Macro Connect. Fails with `NOT_FOUND`+ * until Connect lists the connection, so callers poll it.+ */+ async completeMacroConnect(args: PipedreamConnectCompleteRequest) {+ return (+ await dcsFetch<PipedreamConnectionResponse>(+ `/pipedream/mcp/connect/complete`,+ {+ method: 'POST',+ body: JSON.stringify(args),+ }+ )+ ).map((result) => result);+ },+/*** Register an account a Connect flow created but the Connect UI never* reported. Fails with `NOT_FOUND` when there is none.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.tsindex 5dc007dc48..3f1f024a6f 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@@ -14,6 +14,7 @@ import type {ChatMessageError,CompleteOnboardingRequest,CreateChatRequest,+ CreatePipedreamMcpTokenBody,DatabaseQueryAnswer,DatabaseQueryRequest,DecisionErrorBody,@@ -44,6 +45,7 @@ import type {PatchChatRequest,PipedreamCatalogResponse,PipedreamCompleteRequest,+ PipedreamConnectCompleteRequest,PipedreamConnectionResponse,PipedreamOverlayResponse,PipedreamRecoverRequest,@@ -2618,6 +2620,80 @@ export const completePipedreamMcpConnection = async (} as completePipedreamMcpConnectionResponse;};+/**+ * Answers 404 until Connect lists an active connection for this user and+app, so the frontend can poll it while the consent window is open.+ * @summary Record an app the user connected through Macro Connect.+ */+export type completePipedreamMcpConnectResponse200 = {+ data: PipedreamConnectionResponse;+ status: 200;+};++export type completePipedreamMcpConnectResponse401 = {+ data: string;+ status: 401;+};++export type completePipedreamMcpConnectResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type completePipedreamMcpConnectResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type completePipedreamMcpConnectResponse501 = {+ data: ErrorResponse;+ status: 501;+};++export type completePipedreamMcpConnectResponseSuccess =+ completePipedreamMcpConnectResponse200 & {+ headers: Headers;+ };+export type completePipedreamMcpConnectResponseError = (+ | completePipedreamMcpConnectResponse401+ | completePipedreamMcpConnectResponse404+ | completePipedreamMcpConnectResponse500+ | completePipedreamMcpConnectResponse501+) & {+ headers: Headers;+};++export type completePipedreamMcpConnectResponse =+ | completePipedreamMcpConnectResponseSuccess+ | completePipedreamMcpConnectResponseError;++export const getCompletePipedreamMcpConnectUrl = () => {+ return `/pipedream/mcp/connect/complete`;+};++export const completePipedreamMcpConnect = async (+ pipedreamConnectCompleteRequest: PipedreamConnectCompleteRequest,+ options?: RequestInit+): Promise<completePipedreamMcpConnectResponse> => {+ const res = await fetch(getCompletePipedreamMcpConnectUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(pipedreamConnectCompleteRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: completePipedreamMcpConnectResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as completePipedreamMcpConnectResponse;+};+/*** @summary List the MCP apps connected by the authenticated user.*/@@ -2955,9 +3031,12 @@ export const recoverPipedreamMcpConnection = async (};/**- * 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.+ * By default, a short-lived Pipedream Connect token: the frontend opens+Pipedream's hosted Connect UI with it, and the user picks (or is+deep-linked into) an app and authorizes it there. When the body names an+app Macro Connect serves and the `macro-connect` rollout is on for the+user, a Connect URL instead.+ * @summary Start a connect flow for the authenticated user.*/export type createPipedreamMcpTokenResponse200 = {data: PipedreamTokenResponse;@@ -3000,11 +3079,14 @@ export const getCreatePipedreamMcpTokenUrl = () => {};export const createPipedreamMcpToken = async (+ createPipedreamMcpTokenBody: CreatePipedreamMcpTokenBody,options?: RequestInit): Promise<createPipedreamMcpTokenResponse> => {const res = await fetch(getCreatePipedreamMcpTokenUrl(), {...options,method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(createPipedreamMcpTokenBody),});const body = [204, 205, 304].includes(res.status) ? null : await res.text();diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/createPipedreamMcpTokenBody.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/createPipedreamMcpTokenBody.tsnew file mode 100644index 0000000000..dfd8766ef4--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/createPipedreamMcpTokenBody.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { PipedreamTokenRequest } from './pipedreamTokenRequest';++export type CreatePipedreamMcpTokenBody = null | PipedreamTokenRequest;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.tsindex 6da20fe853..ccfceae162 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@@ -93,6 +93,7 @@ export * from './conversationRecord';export * from './createChatRequest';export * from './createChatRequestName';export * from './createChatRequestProjectId';+export * from './createPipedreamMcpTokenBody';export * from './databaseChange';export * from './databaseChangeOneOf';export * from './databaseChangeOneOfFive';@@ -236,11 +237,20 @@ export * from './pipedreamCatalogResponse';export * from './pipedreamCatalogResponseNextCursor';export * from './pipedreamCompleteRequest';export * from './pipedreamCompleteRequestServerName';+export * from './pipedreamConnectCompleteRequest';+export * from './pipedreamConnectCompleteRequestServerName';export * from './pipedreamConnectionResponse';export * from './pipedreamOverlayResponse';+export * from './pipedreamProviderResponse';export * from './pipedreamRecoverRequest';export * from './pipedreamRecoverRequestServerName';+export * from './pipedreamTokenRequest';+export * from './pipedreamTokenRequestAppSlug';export * from './pipedreamTokenResponse';+export * from './pipedreamTokenResponseConnectLinkUrl';+export * from './pipedreamTokenResponseConnectUrl';+export * from './pipedreamTokenResponseExpiresAt';+export * from './pipedreamTokenResponseToken';export * from './pipedreamUpdateRequest';export * from './pipedreamUpdateRequestEnabled';export * from './pipedreamUpdateRequestServerName';diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamConnectCompleteRequest.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamConnectCompleteRequest.tsnew file mode 100644index 0000000000..c478b5c3ae--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamConnectCompleteRequest.ts@@ -0,0 +1,17 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { PipedreamConnectCompleteRequestServerName } from './pipedreamConnectCompleteRequestServerName';++/**+ * Request body for recording a finished Macro Connect flow.+ */+export interface PipedreamConnectCompleteRequest {+ /** The app that was connected, by Pipedream slug. */+ app_slug: string;+ /** Optional display name for the connector, as for completion. */+ server_name?: PipedreamConnectCompleteRequestServerName;+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamConnectCompleteRequestServerName.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamConnectCompleteRequestServerName.tsnew file mode 100644index 0000000000..c58c4be855--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamConnectCompleteRequestServerName.ts@@ -0,0 +1,11 @@+/**+ * 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, as for completion.+ */+export type PipedreamConnectCompleteRequestServerName = 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.tsindex 357b9dcb31..19be2171a6 100644--- 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@@ -4,6 +4,7 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/+import type { PipedreamProviderResponse } from './pipedreamProviderResponse';/*** A connected MCP app as returned by the API.@@ -13,6 +14,8 @@ export interface PipedreamConnectionResponse {app_slug: string;/** Whether the connector is enabled for tool use. */enabled: boolean;+ /** The backend holding the grant. */+ provider: PipedreamProviderResponse;/** Human-readable display name. */server_name: string;}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamProviderResponse.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamProviderResponse.tsnew file mode 100644index 0000000000..64155467fe--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamProviderResponse.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Which backend a connection or connect flow uses.+ */+export type PipedreamProviderResponse =+ (typeof PipedreamProviderResponse)[keyof typeof PipedreamProviderResponse];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const PipedreamProviderResponse = {+ pipedream: 'pipedream',+ connect: 'connect',+} as const;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenRequest.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenRequest.tsnew file mode 100644index 0000000000..92f7b6d51b--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenRequest.ts@@ -0,0 +1,16 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { PipedreamTokenRequestAppSlug } from './pipedreamTokenRequestAppSlug';++/**+ * Request body for starting a connect flow.+ */+export interface PipedreamTokenRequest {+ /** The app to connect, by Pipedream slug. With it, an app Macro Connect+serves can answer with a Connect URL instead of a Pipedream token. */+ app_slug?: PipedreamTokenRequestAppSlug;+}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenRequestAppSlug.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenRequestAppSlug.tsnew file mode 100644index 0000000000..812b330df4--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenRequestAppSlug.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * The app to connect, by Pipedream slug. With it, an app Macro Connect+serves can answer with a Connect URL instead of a Pipedream token.+ */+export type PipedreamTokenRequestAppSlug = string | null;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.tsindex ba62a9e6b4..aaec02d58f 100644--- 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@@ -5,14 +5,28 @@* OpenAPI spec version: 1.0.0*/+import type { PipedreamProviderResponse } from './pipedreamProviderResponse';+import type { PipedreamTokenResponseConnectLinkUrl } from './pipedreamTokenResponseConnectLinkUrl';+import type { PipedreamTokenResponseConnectUrl } from './pipedreamTokenResponseConnectUrl';+import type { PipedreamTokenResponseExpiresAt } from './pipedreamTokenResponseExpiresAt';+import type { PipedreamTokenResponseToken } from './pipedreamTokenResponseToken';+/**- * Response from creating a Pipedream Connect token.+ * Response from starting a connect flow: a Pipedream Connect token, or for+`provider = connect` a Macro Connect URL.*/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;+ /** Shareable link that opens the same connect flow in a browser tab.+Pipedream only. */+ connect_link_url?: PipedreamTokenResponseConnectLinkUrl;+ /** URL to open in a popup or browser tab for Macro Connect's consent+flow; once it finishes, call `/pipedream/mcp/connect/complete`.+Connect only. */+ connect_url?: PipedreamTokenResponseConnectUrl;+ /** RFC 3339 expiry of the token. Pipedream only. */+ expires_at?: PipedreamTokenResponseExpiresAt;+ /** The backend this flow connects through. */+ provider: PipedreamProviderResponse;+ /** Short-lived token to open the Pipedream Connect UI with. Pipedream only. */+ token?: PipedreamTokenResponseToken;}diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseConnectLinkUrl.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseConnectLinkUrl.tsnew file mode 100644index 0000000000..b7d96f1e17--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseConnectLinkUrl.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Shareable link that opens the same connect flow in a browser tab.+Pipedream only.+ */+export type PipedreamTokenResponseConnectLinkUrl = string | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseConnectUrl.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseConnectUrl.tsnew file mode 100644index 0000000000..f39a9b0605--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseConnectUrl.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * URL to open in a popup or browser tab for Macro Connect's consent+flow; once it finishes, call `/pipedream/mcp/connect/complete`.+Connect only.+ */+export type PipedreamTokenResponseConnectUrl = string | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseExpiresAt.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseExpiresAt.tsnew file mode 100644index 0000000000..f2230ba02d--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseExpiresAt.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * RFC 3339 expiry of the token. Pipedream only.+ */+export type PipedreamTokenResponseExpiresAt = string | null;diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseToken.ts b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseToken.tsnew file mode 100644index 0000000000..a118f46fe8--- /dev/null+++ b/apps/web/src/lib/service-clients/service-cognition/generated/schemas/pipedreamTokenResponseToken.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Short-lived token to open the Pipedream Connect UI with. Pipedream only.+ */+export type PipedreamTokenResponseToken = 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.jsonindex ddd279c17b..78ce481e87 100644--- a/apps/web/src/lib/service-clients/service-cognition/openapi.json+++ b/apps/web/src/lib/service-clients/service-cognition/openapi.json@@ -2154,6 +2154,76 @@}}},+ "/pipedream/mcp/connect/complete": {+ "post": {+ "tags": ["pipedream-mcp"],+ "summary": "Record an app the user connected through Macro Connect.",+ "description": "Answers 404 until Connect lists an active connection for this user and\napp, so the frontend can poll it while the consent window is open.",+ "operationId": "complete_pipedream_mcp_connect",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PipedreamConnectCompleteRequest"+ }+ }+ },+ "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"],@@ -2420,9 +2490,25 @@"/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.",+ "summary": "Start a connect flow for the authenticated user.",+ "description": "By default, a short-lived Pipedream Connect token: the frontend opens\nPipedream's hosted Connect UI with it, and the user picks (or is\ndeep-linked into) an app and authorizes it there. When the body names an\napp Macro Connect serves and the `macro-connect` rollout is on for the\nuser, a Connect URL instead.","operationId": "create_pipedream_mcp_token",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/PipedreamTokenRequest"+ }+ ]+ }+ }+ }+ },"responses": {"200": {"description": "",@@ -5454,10 +5540,25 @@}}},+ "PipedreamConnectCompleteRequest": {+ "type": "object",+ "description": "Request body for recording a finished Macro Connect flow.",+ "required": ["app_slug"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "The app that was connected, by Pipedream slug."+ },+ "server_name": {+ "type": ["string", "null"],+ "description": "Optional display name for the connector, as for completion."+ }+ }+ },"PipedreamConnectionResponse": {"type": "object","description": "A connected MCP app as returned by the API.",- "required": ["app_slug", "server_name", "enabled"],+ "required": ["app_slug", "server_name", "enabled", "provider"],"properties": {"app_slug": {"type": "string",@@ -5467,6 +5568,10 @@"type": "boolean","description": "Whether the connector is enabled for tool use."},+ "provider": {+ "$ref": "#/components/schemas/PipedreamProviderResponse",+ "description": "The backend holding the grant."+ },"server_name": {"type": "string","description": "Human-readable display name."@@ -5488,6 +5593,11 @@}}},+ "PipedreamProviderResponse": {+ "type": "string",+ "description": "Which backend a connection or connect flow uses.",+ "enum": ["pipedream", "connect"]+ },"PipedreamRecoverRequest": {"type": "object","description": "Request body for recovering a connect flow whose result the Connect UI\nnever reported.",@@ -5503,22 +5613,40 @@}}},+ "PipedreamTokenRequest": {+ "type": "object",+ "description": "Request body for starting a connect flow.",+ "properties": {+ "app_slug": {+ "type": ["string", "null"],+ "description": "The app to connect, by Pipedream slug. With it, an app Macro Connect\nserves can answer with a Connect URL instead of a Pipedream token."+ }+ }+ },"PipedreamTokenResponse": {"type": "object",- "description": "Response from creating a Pipedream Connect token.",- "required": ["token", "expires_at", "connect_link_url"],+ "description": "Response from starting a connect flow: a Pipedream Connect token, or for\n`provider = connect` a Macro Connect URL.",+ "required": ["provider"],"properties": {"connect_link_url": {- "type": "string",- "description": "Shareable link that opens the same connect flow in a browser tab."+ "type": ["string", "null"],+ "description": "Shareable link that opens the same connect flow in a browser tab.\nPipedream only."+ },+ "connect_url": {+ "type": ["string", "null"],+ "description": "URL to open in a popup or browser tab for Macro Connect's consent\nflow; once it finishes, call `/pipedream/mcp/connect/complete`.\nConnect only."},"expires_at": {- "type": "string",- "description": "RFC 3339 expiry of the token."+ "type": ["string", "null"],+ "description": "RFC 3339 expiry of the token. Pipedream only."+ },+ "provider": {+ "$ref": "#/components/schemas/PipedreamProviderResponse",+ "description": "The backend this flow connects through."},"token": {- "type": "string",- "description": "Short-lived token to open the Pipedream Connect UI with."+ "type": ["string", "null"],+ "description": "Short-lived token to open the Pipedream Connect UI with. Pipedream only."}}},diff --git a/crates/agent_code_mode/src/domain/operations.json b/crates/agent_code_mode/src/domain/operations.jsonindex f257949e1b..c7e9cef73c 100644--- a/crates/agent_code_mode/src/domain/operations.json+++ b/crates/agent_code_mode/src/domain/operations.json@@ -223,6 +223,7 @@"cognition.dismissPromptHandler": "Dismiss Prompt","cognition.browsePipedreamMcpCatalog": "Browse Pipedream Mcp Catalog","cognition.completePipedreamMcpConnection": "Complete Pipedream Mcp Connection",+ "cognition.completePipedreamMcpConnect": "Complete Pipedream Mcp Connect","cognition.deletePipedreamMcpConnection": "Delete Pipedream Mcp Connection","cognition.listPipedreamMcpConnections": "List Pipedream Mcp Connections","cognition.updatePipedreamMcpConnection": "Update Pipedream Mcp Connection",diff --git a/crates/agent_egress/src/outbound/mcp_credentials.rs b/crates/agent_egress/src/outbound/mcp_credentials.rsindex e008f5e354..4443800e0d 100644--- a/crates/agent_egress/src/outbound/mcp_credentials.rs+++ b/crates/agent_egress/src/outbound/mcp_credentials.rs@@ -114,6 +114,7 @@ whereserver_name: slug.as_str().to_owned(),account_id: String::new(),enabled: false,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,},false,),diff --git a/crates/agent_egress/src/outbound/mcp_credentials/test.rs b/crates/agent_egress/src/outbound/mcp_credentials/test.rsindex dbe7174ad6..65e7a502e1 100644--- a/crates/agent_egress/src/outbound/mcp_credentials/test.rs+++ b/crates/agent_egress/src/outbound/mcp_credentials/test.rs@@ -17,6 +17,7 @@ fn connection(app_slug: &str, enabled: bool) -> PipedreamConnection {server_name: format!("{app_slug} display name"),account_id: format!("apn_{app_slug}"),enabled,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,}}diff --git a/crates/agent_harness/src/outbound/connected_apps/test.rs b/crates/agent_harness/src/outbound/connected_apps/test.rsindex 178d632ba7..d7f5230613 100644--- a/crates/agent_harness/src/outbound/connected_apps/test.rs+++ b/crates/agent_harness/src/outbound/connected_apps/test.rs@@ -61,6 +61,7 @@ fn pipedream(app_slug: &str, enabled: bool) -> PipedreamConnection {server_name: format!("{app_slug} (Pipedream)"),account_id: "apn_1".into(),enabled,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,}}diff --git a/crates/agent_harness/src/outbound/egress/test.rs b/crates/agent_harness/src/outbound/egress/test.rsindex c3244d2020..c2d8909b86 100644--- a/crates/agent_harness/src/outbound/egress/test.rs+++ b/crates/agent_harness/src/outbound/egress/test.rs@@ -111,6 +111,7 @@ fn connection(app_slug: &str, enabled: bool) -> pipedream_mcp::domain::models::Pserver_name: app_slug.to_owned(),account_id: format!("apn_{app_slug}"),enabled,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,}}diff --git a/crates/ai_tools/Cargo.toml b/crates/ai_tools/Cargo.tomlindex 0a25b11ed9..6fd57785b6 100644--- a/crates/ai_tools/Cargo.toml+++ b/crates/ai_tools/Cargo.toml@@ -8,6 +8,7 @@ version = "0.1.0"test-support = [][dependencies]+feature_flags = { path = "../feature_flags" }import_linear = { path = "../import_linear" }import_jira = { path = "../import_jira" }@@ -85,6 +86,7 @@ macro_user_id = { path = "../macro_user_id" }mcp_client = { path = "../mcp_client" }mcp_select = { path = "../mcp_select" }pipedream_mcp = { path = "../pipedream_mcp" }+url = { workspace = true }model = { path = "../model" }model-entity = { path = "../model-entity" }model_notifications = { path = "../model_notifications" }diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rsindex e2c5b721c0..642d7810c6 100644--- a/crates/ai_tools/src/build_context.rs+++ b/crates/ai_tools/src/build_context.rs@@ -572,7 +572,7 @@ pub async fn build_tool_service_context_from_env(let admission =ai_billing::composition::pg_admission_service(pool.clone(), enforcement, pricing);- let pipedream_client = crate::mcp_app_catalog::pipedream_client_from_env()?;+ let pipedream_client = crate::mcp_app_catalog::connector_backends_from_env()?;let native_servers = match maybe_env.mcp_credentials_key_secret_name.as_ref()@@ -733,7 +733,9 @@ pub async fn build_tool_service_context_from_env(crate::tool_context::MaybeToolEventBroker::Real(macro_event_broker.clone()),entity_access_service.clone(),document_storage_service_url,- pipedream_client,+ pipedream_client+ .as_ref()+ .map(|backends| backends.pipedream().clone()),),read_agent_session_context: crate::build_read_agent_session_context(pool.clone(),diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rsindex 407f9082ab..0ada28c2bb 100644--- a/crates/ai_tools/src/lib.rs+++ b/crates/ai_tools/src/lib.rs@@ -73,7 +73,10 @@ pub use build_context::{};pub use deferred::{DeferredToolSet, deferred_tools};pub use import_jobs::{IMPORT_JOBS_HANDOVER_TIMEOUT, ImportJobs};-pub use mcp_app_catalog::{PipedreamMcpAppCatalog, pipedream_client_from_env};+pub use mcp_app_catalog::{+ PipedreamMcpAppCatalog, connect_adapter, connector_backends_from_env, macro_connect_rollout,+ pipedream_client_from_env,+};pub use search::search_toolset;pub use tool_context::{ChannelSideEffectClients, FormsToolConfig, MaybeToolEventBroker, NoOpCallRtcClient,diff --git a/crates/ai_tools/src/mcp_app_catalog.rs b/crates/ai_tools/src/mcp_app_catalog.rsindex fb079baaa2..d5b3fd0f22 100644--- a/crates/ai_tools/src/mcp_app_catalog.rs+++ b/crates/ai_tools/src/mcp_app_catalog.rs@@ -1,4 +1,6 @@-//! Pipedream app directory used when an agent pins MCP servers.+//! Pipedream app directory used when an agent pins MCP servers, and the+//! connector backends (Pipedream plus Macro Connect) built from the+//! environment.use std::sync::Arc;@@ -6,10 +8,15 @@ use anyhow::Context;use bots::domain::ports::{BotError, McpAppCatalog};use macro_env::Environment;use macro_env_var::maybe_env_var;-use pipedream_mcp::domain::ports::ConnectorDirectory;+use pipedream_mcp::domain::ports::ConnectRollout;use pipedream_mcp::outbound::api::{DEFAULT_API_URL, DEFAULT_MCP_URL, PipedreamClient, PipedreamConfig,};+use pipedream_mcp::outbound::connect::{ConnectAdapter, ConnectConfig};++use pipedream_mcp::outbound::dispatch::ConnectorBackends;+use std::collections::HashMap;+use std::sync::Mutex;maybe_env_var! {struct PipedreamCatalogEnv {@@ -25,9 +32,118 @@ maybe_env_var! {PipedreamApiUrl,/// Base URL of the Pipedream MCP server, shared with execution.PipedreamMcpUrl,+ /// Macro's customer key for the Macro Connect API.+ ConnectCustomerKey,+ /// PostHog project token; reads the `macro-connect` rollout.+ PosthogApiKey,+ /// Regional PostHog origin; defaults to the US origin.+ PosthogHost,}}+/// The Macro Connect adapter for `customer_key`, or `None` when the host has+/// no key (Connect off). Connect sends consent back to the cognition+/// service's callback page, whichever host builds the adapter.+pub fn connect_adapter(customer_key: Option<&str>) -> anyhow::Result<Option<Arc<ConnectAdapter>>> {+ let Some(customer_key) = customer_key.filter(|key| !key.is_empty()) else {+ return Ok(None);+ };+ let public_url = macro_service_urls::CognitionPublicUrl::new()?;+ let callback_url = url::Url::parse(&format!(+ "{}/pipedream/mcp/connect/callback",+ public_url.as_str().trim_end_matches('/')+ ))+ .context("Connect callback is not a URL")?;+ let adapter = ConnectAdapter::new(ConnectConfig {+ api_url: macro_service_urls::ConnectApiUrl::new()?.to_string(),+ customer_key: customer_key.to_owned(),+ callback_url,+ })+ .context("building Macro Connect client")?;+ Ok(Some(Arc::new(adapter)))+}++/// Pipedream plus Macro Connect when this process has credentials for both+/// (Connect is optional), otherwise `None`.+pub fn connector_backends_from_env() -> anyhow::Result<Option<Arc<ConnectorBackends>>> {+ let Some(pipedream) = pipedream_client_from_env()? else {+ return Ok(None);+ };+ let env = PipedreamCatalogEnv::new();+ let connect = connect_adapter(+ env.connect_customer_key+ .as_ref()+ .and_then(|value| value.value()),+ )?;+ let mut backends = ConnectorBackends::new(pipedream, connect);+ if let Some(rollout) = macro_connect_rollout(+ env.posthog_api_key.as_ref().and_then(|value| value.value()),+ env.posthog_host.as_ref().and_then(|value| value.value()),+ )? {+ backends = backends.with_rollout(rollout);+ }+ Ok(Some(Arc::new(backends)))+}++/// The PostHog flag that puts a user on Macro Connect alone. Keep in sync+/// with the web flag of the same key.+pub const MACRO_CONNECT_FLAG: &str = "macro-connect";++/// How long one user's flag answer is reused: every MCP connection asks.+const ROLLOUT_TTL: std::time::Duration = std::time::Duration::from_secs(60);++/// The `macro-connect` rollout read from PostHog, or `None` without a+/// PostHog key (nobody on Connect alone). Answers are cached per user for+/// [`ROLLOUT_TTL`]; a failed read answers `false`, keeping the user on+/// Pipedream.+pub fn macro_connect_rollout(+ api_key: Option<&str>,+ host: Option<&str>,+) -> anyhow::Result<Option<ConnectRollout>> {+ let Some(api_key) = api_key.filter(|key| !key.is_empty()) else {+ return Ok(None);+ };+ let flags = feature_flags::outbound::posthog::PostHogFeatureFlags::new(+ host.unwrap_or("https://us.i.posthog.com"),+ api_key.to_owned(),+ std::time::Duration::from_secs(3),+ )+ .map_err(|error| anyhow::anyhow!("invalid feature flag configuration: {error}"))?;+ Ok(Some(rollout_from(flags)))+}++fn rollout_from<F>(flags: F) -> ConnectRollout+where+ F: feature_flags::FeatureFlags + Clone + 'static,+{+ type Cache = HashMap<String, (bool, std::time::Instant)>;+ let cache: Arc<Mutex<Cache>> = Arc::default();+ Arc::new(move |user_id| {+ let flags = flags.clone();+ let cache = cache.clone();+ Box::pin(async move {+ let key = user_id.as_ref().to_owned();+ if let Some((on, at)) = cache.lock().ok().and_then(|cache| cache.get(&key).copied())+ && at.elapsed() < ROLLOUT_TTL+ {+ return on;+ }+ let on = match flags.load(&user_id).await {+ Ok(snapshot) => snapshot.is_enabled(MACRO_CONNECT_FLAG),+ Err(error) => {+ tracing::warn!(error = ?error, "could not read the macro-connect flag; using Pipedream");+ return false;+ }+ };+ if let Ok(mut cache) = cache.lock() {+ cache.retain(|_, (_, at)| at.elapsed() < ROLLOUT_TTL);+ cache.insert(key, (on, std::time::Instant::now()));+ }+ on+ })+ })+}+/// A Pipedream client when this process has the credentials, otherwise `None`.////// Incomplete credentials are treated as unconfigured: a slug cannot be@@ -113,7 +229,7 @@ impl McpAppCatalog for PipedreamMcpAppCatalog {"cannot verify MCP app {slug}: Pipedream is not configured")));};- match client.retrieve(slug).await {+ match client.retrieve_app(slug).await {Ok(Some(_)) => Ok(true),Ok(None) => Ok(false),Err(error) => {diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rsindex 6ebd883cc7..d684c219c6 100644--- a/crates/ai_tools/src/tool_context.rs+++ b/crates/ai_tools/src/tool_context.rs@@ -1970,11 +1970,11 @@ 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).+/// The connector backends (Pipedream, plus Macro Connect when configured):+/// `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>>;+ Option<std::sync::Arc<pipedream_mcp::outbound::dispatch::ConnectorBackends>>;/// The MCP stack selector wired to the concrete DCS stores: the native/// server store and the Pipedream connection store. Picks which stack@@ -1993,7 +1993,7 @@ pub type ToolImportService = import::domain::service::ImportServiceImpl<import::outbound::mcp_slack_source::McpSlackSource<ToolMcpSelector>,import_notion::outbound::pipedream::PipedreamNotionConnections<pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,- pipedream_mcp::outbound::api::PipedreamClient,+ pipedream_mcp::outbound::dispatch::ConnectorBackends,>,>;@@ -2127,7 +2127,7 @@ pub struct ToolServiceContext {/// Pipedream discovery dependencies shared by chat tools.pub type ToolConnectorToolContext = pipedream_mcp::inbound::toolset::ConnectorToolContext<- pipedream_mcp::outbound::api::PipedreamClient,+ pipedream_mcp::outbound::dispatch::ConnectorBackends,pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,mcp_select::NativeOverlayConnections<mcp_client::outbound::NativeServerStore>,>;@@ -2138,7 +2138,7 @@ pub type ToolConnectorToolContext = pipedream_mcp::inbound::toolset::ConnectorTo/// native MCP stack; `None` where that stack has no encryption key.pub fn build_connector_tool_context(pool: sqlx::PgPool,- client: Option<Arc<pipedream_mcp::outbound::api::PipedreamClient>>,+ client: Option<Arc<pipedream_mcp::outbound::dispatch::ConnectorBackends>>,native_servers: Option<Arc<mcp_client::outbound::NativeServerStore>>,) -> ToolConnectorToolContext {pipedream_mcp::inbound::toolset::ConnectorToolContext {diff --git a/crates/code_execution/src/outbound/deno/sdk.mjs b/crates/code_execution/src/outbound/deno/sdk.mjsindex b34fc8af35..66361ca914 100644--- a/crates/code_execution/src/outbound/deno/sdk.mjs+++ b/crates/code_execution/src/outbound/deno/sdk.mjs@@ -19,7 +19,7 @@ async function cO($,O,j){if(!Number.isInteger(O)||O<1)throw RangeError(`concurre`);U=y.pop()??"";for(let a of y){let i=a.split(``),F=[],v;for(let R of i)if(R.startsWith("data:"))F.push(R.replace(/^data:\s*/,""));else if(R.startsWith("event:"))v=R.replace(/^event:\s*/,"");else if(R.startsWith("id:"))J=R.replace(/^id:\s*/,"");else if(R.startsWith("retry:")){let m=Number.parseInt(R.replace(/^retry:\s*/,""),10);if(!Number.isNaN(m))V=m}let M,h=!1;if(F.length){let R=F.join(`-`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var XS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},KS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},YS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},sj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(KS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=XS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},tj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=YS(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var GS=/\{[^{}]+\}/g,QS=({path:$,url:O})=>{let j=O,x=O.match(GS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,sj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,tj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},c2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=QS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function j1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var d2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var l2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var r2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=sj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=tj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},p2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},JS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function a2($){for(let O of $.security??[]){if(JS($,O.name))continue;let j=await d2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var x1=($)=>c2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:r2($.querySerializer),url:$.url}),S1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=oj($.headers,O.headers),j},VS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},oj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?VS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ej{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var i2=()=>({error:new ej,request:new ej,response:new ej}),WS=r2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),BS={"Content-Type":"application/json"},Sj=($={})=>({...l2,headers:BS,parseAs:"auto",querySerializer:WS,...$});var Z1=($={})=>{let O=S1(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=S1(O,Q),j()},S=i2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:oj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await a2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=x1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:j1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?p2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return u2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:j1(I),url:z})};return{buildUrl:(Q)=>x1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var n2=Z1(Sj());class s2{client;constructor($){this.client=$?.client??n2}}class t2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class $0 extends s2{static __registry=new t2;constructor($){super($);$0.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}generateDatabaseQuery($){return($.client??this.client).post({url:"/database-query",...$,headers:{"Content-Type":"application/json",...$.headers}})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}generateImage($){return($.client??this.client).post({url:"/images/generate",...$,headers:{"Content-Type":"application/json",...$.headers}})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}listPipedreamMcpOverlays($){return($?.client??this.client).get({url:"/pipedream/mcp/overlays",...$})}recoverPipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/recover",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function e2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,`+`);try{M=JSON.parse(R),h=!0}catch{M=R}}if(h){if(S)await S(M);if(x)M=await x(M)}if(j?.({data:M,event:v,id:J,retry:V}),F.length)yield M}}}finally{H.removeEventListener("abort",g),T.releaseLock()}break}catch(D){if(O?.(D),Z!==void 0&&B>=Z)break;let _=Math.min(V*2**(B-1),X??30000);await I(_)}}}()}}var XS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},KS=($)=>{switch($){case"form":return",";case"pipeDelimited":return"|";case"spaceDelimited":return"%20";default:return","}},YS=($)=>{switch($){case"label":return".";case"matrix":return";";case"simple":return",";default:return"&"}},sj=({allowReserved:$,explode:O,name:j,style:x,value:S})=>{if(!O){let X=($?S:S.map((Y)=>encodeURIComponent(Y))).join(KS(x));switch(x){case"label":return`.${X}`;case"matrix":return`;${j}=${X}`;case"simple":return X;default:return`${j}=${X}`}}let K=XS(x),Z=S.map((X)=>{if(x==="label"||x==="simple")return $?X:encodeURIComponent(X);return EO({allowReserved:$,name:j,value:X})}).join(K);return x==="label"||x==="matrix"?K+Z:Z},EO=({allowReserved:$,name:O,value:j})=>{if(j===void 0||j===null)return"";if(typeof j==="object")throw Error("Deeply-nested arrays/objects aren’t supported. Provide your own `querySerializer()` to handle these.");return`${O}=${$?j:encodeURIComponent(j)}`},tj=({allowReserved:$,explode:O,name:j,style:x,value:S,valueOnly:K})=>{if(S instanceof Date)return K?S.toISOString():`${j}=${S.toISOString()}`;if(x!=="deepObject"&&!O){let Y=[];Object.entries(S).forEach(([Q,J])=>{Y=[...Y,Q,$?J:encodeURIComponent(J)]});let L=Y.join(",");switch(x){case"form":return`${j}=${L}`;case"label":return`.${L}`;case"matrix":return`;${j}=${L}`;default:return L}}let Z=YS(x),X=Object.entries(S).map(([Y,L])=>EO({allowReserved:$,name:x==="deepObject"?`${j}[${Y}]`:Y,value:L})).join(Z);return x==="label"||x==="matrix"?Z+X:X};var GS=/\{[^{}]+\}/g,QS=({path:$,url:O})=>{let j=O,x=O.match(GS);if(x)for(let S of x){let K=!1,Z=S.substring(1,S.length-1),X="simple";if(Z.endsWith("*"))K=!0,Z=Z.substring(0,Z.length-1);if(Z.startsWith("."))Z=Z.substring(1),X="label";else if(Z.startsWith(";"))Z=Z.substring(1),X="matrix";let Y=$[Z];if(Y===void 0||Y===null)continue;if(Array.isArray(Y)){j=j.replace(S,sj({explode:K,name:Z,style:X,value:Y}));continue}if(typeof Y==="object"){j=j.replace(S,tj({explode:K,name:Z,style:X,value:Y,valueOnly:!0}));continue}if(X==="matrix"){j=j.replace(S,`;${EO({name:Z,value:Y})}`);continue}let L=encodeURIComponent(X==="label"?`.${Y}`:Y);j=j.replace(S,L)}return j},c2=({baseUrl:$,path:O,query:j,querySerializer:x,url:S})=>{let K=S.startsWith("/")?S:`/${S}`,Z=($??"")+K;if(O)Z=QS({path:O,url:Z});let X=j?x(j):"";if(X.startsWith("?"))X=X.substring(1);if(X)Z+=`?${X}`;return Z};function j1($){let O=$.body!==void 0;if(O&&$.bodySerializer){if("serializedBody"in $)return $.serializedBody!==void 0&&$.serializedBody!==""?$.serializedBody:null;return $.body!==""?$.body:null}if(O)return $.body;return}var d2=async($,O)=>{let j=typeof O==="function"?await O($):O;if(!j)return;if($.scheme==="bearer")return`Bearer ${j}`;if($.scheme==="basic")return`Basic ${btoa(j)}`;return j};var l2={bodySerializer:($)=>JSON.stringify($,(O,j)=>typeof j==="bigint"?j.toString():j)};var r2=({parameters:$={},...O}={})=>{return(x)=>{let S=[];if(x&&typeof x==="object")for(let K in x){let Z=x[K];if(Z===void 0||Z===null)continue;let X=$[K]||O;if(Array.isArray(Z)){let Y=sj({allowReserved:X.allowReserved,explode:!0,name:K,style:"form",value:Z,...X.array});if(Y)S.push(Y)}else if(typeof Z==="object"){let Y=tj({allowReserved:X.allowReserved,explode:!0,name:K,style:"deepObject",value:Z,...X.object});if(Y)S.push(Y)}else{let Y=EO({allowReserved:X.allowReserved,name:K,value:Z});if(Y)S.push(Y)}}return S.join("&")}},p2=($)=>{if(!$)return"stream";let O=$.split(";")[0]?.trim();if(!O)return;if(O.startsWith("application/json")||O.endsWith("+json"))return"json";if(O==="multipart/form-data")return"formData";if(["application/","audio/","image/","video/"].some((j)=>O.startsWith(j)))return"blob";if(O.startsWith("text/"))return"text";return},JS=($,O)=>{if(!O)return!1;if($.headers.has(O)||$.query?.[O]||$.headers.get("Cookie")?.includes(`${O}=`))return!0;return!1};async function a2($){for(let O of $.security??[]){if(JS($,O.name))continue;let j=await d2(O,$.auth);if(!j)continue;let x=O.name??"Authorization";switch(O.in){case"query":if(!$.query)$.query={};$.query[x]=j;break;case"cookie":$.headers.append("Cookie",`${x}=${j}`);break;case"header":default:$.headers.set(x,j);break}}}var x1=($)=>c2({baseUrl:$.baseUrl,path:$.path,query:$.query,querySerializer:typeof $.querySerializer==="function"?$.querySerializer:r2($.querySerializer),url:$.url}),S1=($,O)=>{let j={...$,...O};if(j.baseUrl?.endsWith("/"))j.baseUrl=j.baseUrl.substring(0,j.baseUrl.length-1);return j.headers=oj($.headers,O.headers),j},VS=($)=>{let O=[];return $.forEach((j,x)=>{O.push([x,j])}),O},oj=(...$)=>{let O=new Headers;for(let j of $){if(!j)continue;let x=j instanceof Headers?VS(j):Object.entries(j);for(let[S,K]of x)if(K===null)O.delete(S);else if(Array.isArray(K))for(let Z of K)O.append(S,Z);else if(K!==void 0)O.set(S,typeof K==="object"?JSON.stringify(K):K)}return O};class ej{fns=[];clear(){this.fns=[]}eject($){let O=this.getInterceptorIndex($);if(this.fns[O])this.fns[O]=null}exists($){let O=this.getInterceptorIndex($);return Boolean(this.fns[O])}getInterceptorIndex($){if(typeof $==="number")return this.fns[$]?$:-1;return this.fns.indexOf($)}update($,O){let j=this.getInterceptorIndex($);if(this.fns[j])return this.fns[j]=O,$;return!1}use($){return this.fns.push($),this.fns.length-1}}var i2=()=>({error:new ej,request:new ej,response:new ej}),WS=r2({allowReserved:!1,array:{explode:!0,style:"form"},object:{explode:!0,style:"deepObject"}}),BS={"Content-Type":"application/json"},Sj=($={})=>({...l2,headers:BS,parseAs:"auto",querySerializer:WS,...$});var Z1=($={})=>{let O=S1(Sj(),$),j=()=>({...O}),x=(Q)=>{return O=S1(O,Q),j()},S=i2(),K=async(Q)=>{let J={...O,...Q,fetch:Q.fetch??O.fetch??globalThis.fetch,headers:oj(O.headers,Q.headers),serializedBody:void 0};if(J.security)await a2(J);if(J.requestValidator)await J.requestValidator(J);if(J.body!==void 0&&J.bodySerializer)J.serializedBody=J.bodySerializer(J.body);if(J.body===void 0||J.serializedBody==="")J.headers.delete("Content-Type");let I=J,z=x1(I);return{opts:I,url:z}},Z=async(Q)=>{let J=Q.throwOnError??O.throwOnError,I=Q.responseStyle??O.responseStyle,z,W;try{let{opts:V,url:B}=await K(Q),H={redirect:"follow",...V,body:j1(V)};z=new Request(B,H);for(let N of S.request.fns)if(N)z=await N(z,V);let P=V.fetch;W=await P(z);for(let N of S.response.fns)if(N)W=await N(W,z,V);let D={request:z,response:W};if(W.ok){let N=(V.parseAs==="auto"?p2(W.headers.get("Content-Type")):V.parseAs)??"json";if(W.status===204||W.headers.get("Content-Length")==="0"){let U;switch(N){case"arrayBuffer":case"blob":case"text":U=await W[N]();break;case"formData":U=new FormData;break;case"stream":U=W.body;break;case"json":default:U={};break}return V.responseStyle==="data"?U:{data:U,...D}}let T;switch(N){case"arrayBuffer":case"blob":case"formData":case"text":T=await W[N]();break;case"json":{let U=await W.text();T=U?JSON.parse(U):{};break}case"stream":return V.responseStyle==="data"?W.body:{data:W.body,...D}}if(N==="json"){if(V.responseValidator)await V.responseValidator(T);if(V.responseTransformer)T=await V.responseTransformer(T)}return V.responseStyle==="data"?T:{data:T,...D}}let _=await W.text(),q;try{q=JSON.parse(_)}catch{}throw q??_}catch(V){let B=V;for(let H of S.error.fns)if(H)B=await H(B,W,z,Q);if(B=B||{},J)throw B;return I==="data"?void 0:{error:B,request:z,response:W}}},X=(Q)=>(J)=>Z({...J,method:Q}),Y=(Q)=>async(J)=>{let{opts:I,url:z}=await K(J);return u2({...I,body:I.body,method:Q,onRequest:async(W,V)=>{let B=new Request(W,V);for(let H of S.request.fns)if(H)B=await H(B,I);return B},serializedBody:j1(I),url:z})};return{buildUrl:(Q)=>x1({...O,...Q}),connect:X("CONNECT"),delete:X("DELETE"),get:X("GET"),getConfig:j,head:X("HEAD"),interceptors:S,options:X("OPTIONS"),patch:X("PATCH"),post:X("POST"),put:X("PUT"),request:Z,setConfig:x,sse:{connect:Y("CONNECT"),delete:Y("DELETE"),get:Y("GET"),head:Y("HEAD"),options:Y("OPTIONS"),patch:Y("PATCH"),post:Y("POST"),put:Y("PUT"),trace:Y("TRACE")},trace:X("TRACE")}};var n2=Z1(Sj());class s2{client;constructor($){this.client=$?.client??n2}}class t2{defaultKey="default";instances=new Map;get($){let O=this.instances.get($??this.defaultKey);if(!O)throw Error('No SDK client found. Create one with "new Sdk()" to fix this error.');return O}set($,O){this.instances.set(O??this.defaultKey,$)}}class $0 extends s2{static __registry=new t2;constructor($){super($);$0.__registry.set(this,$?.key)}setPricingHandler($){return($.client??this.client).post({url:"/ai-cost/pricing",...$,headers:{"Content-Type":"application/json",...$.headers}})}getUsageHandler($){return($.client??this.client).post({url:"/ai-cost/usage",...$,headers:{"Content-Type":"application/json",...$.headers}})}upsertAiProjection($){return($.client??this.client).post({url:"/ai-projections",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatsForAttachmentHandler($){return($.client??this.client).get({url:"/attachments/{attachment_id}/chats",...$})}deleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}",...$})}patchChat($){return($.client??this.client).patch({url:"/chat/{chat_id}",...$,headers:{"Content-Type":"application/json",...$.headers}})}permanentlyDeleteChat($){return($.client??this.client).delete({url:"/chat/{chat_id}/permanent",...$})}createChat($){return($.client??this.client).post({url:"/chats",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChatHistoryHandler($){return($.client??this.client).get({url:"/chats/history/{chat_id}",...$})}getChatHistoryBatchMessagesHandler($){return($.client??this.client).post({url:"/chats/history_batch_messages",...$,headers:{"Content-Type":"application/json",...$.headers}})}getChat($){return($.client??this.client).get({url:"/chats/{chat_id}",...$})}copyChat($){return($.client??this.client).post({url:"/chats/{chat_id}/copy",...$})}getChatPermissions($){return($.client??this.client).get({url:"/chats/{chat_id}/permissions",...$})}revertDeleteChat($){return($.client??this.client).put({url:"/chats/{chat_id}/revert_delete",...$})}callTool($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/call",...$,headers:{"Content-Type":"application/json",...$.headers}})}rejectToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/reject",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolResponse($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/response/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateToolCall($){return($.client??this.client).post({url:"/chats/{chat_id}/tool/update",...$,headers:{"Content-Type":"application/json",...$.headers}})}getCitationHandler($){return($.client??this.client).get({url:"/citations/{id}",...$})}generateDatabaseQuery($){return($.client??this.client).post({url:"/database-query",...$,headers:{"Content-Type":"application/json",...$.headers}})}decisions($){return($.client??this.client).post({url:"/decisions",...$,headers:{"Content-Type":"application/json",...$.headers}})}healthHandler($){return($?.client??this.client).get({url:"/health",...$})}generateImage($){return($.client??this.client).post({url:"/images/generate",...$,headers:{"Content-Type":"application/json",...$.headers}})}notionReportHandler($){return($?.client??this.client).get({url:"/import/notion",...$})}cancelNotionHandler($){return($?.client??this.client).post({url:"/import/notion/cancel",...$})}runImportHandler($){return($.client??this.client).post({url:"/import/run",...$,headers:{"Content-Type":"application/json",...$.headers}})}discoverHandler($){return($.client??this.client).post({url:"/import/runs/{source}/discover",...$})}getStateHandler($){return($?.client??this.client).get({url:"/import/state",...$})}workspaceReportHandler($){return($.client??this.client).get({url:"/import/workspaces/{source}",...$})}cancelWorkspaceHandler($){return($.client??this.client).post({url:"/import/workspaces/{source}/cancel",...$})}deleteMcpServer($){return($.client??this.client).delete({url:"/mcp/servers",...$})}listMcpServers($){return($?.client??this.client).get({url:"/mcp/servers",...$})}addMcpServer($){return($.client??this.client).post({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}updateMcpServer($){return($.client??this.client).put({url:"/mcp/servers",...$,headers:{"Content-Type":"application/json",...$.headers}})}mcpAuthCallback($){return($?.client??this.client).get({url:"/mcp/servers/auth/callback",...$})}mcpOauthClientMetadata($){return($?.client??this.client).get({url:"/mcp/servers/auth/client-metadata",...$})}startMcpAuth($){return($.client??this.client).post({url:"/mcp/servers/auth/start",...$,headers:{"Content-Type":"application/json",...$.headers}})}getMemoryHandler($){return($?.client??this.client).get({url:"/memory",...$})}getStateHandler2($){return($?.client??this.client).get({url:"/onboarding",...$})}completeHandler($){return($.client??this.client).post({url:"/onboarding/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}dismissedPromptsHandler($){return($?.client??this.client).get({url:"/onboarding/prompts",...$})}dismissPromptHandler($){return($.client??this.client).post({url:"/onboarding/prompts/{prompt_id}/dismiss",...$})}browsePipedreamMcpCatalog($){return($?.client??this.client).get({url:"/pipedream/mcp/catalog",...$})}completePipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}completePipedreamMcpConnect($){return($.client??this.client).post({url:"/pipedream/mcp/connect/complete",...$,headers:{"Content-Type":"application/json",...$.headers}})}deletePipedreamMcpConnection($){return($.client??this.client).delete({url:"/pipedream/mcp/connections",...$})}listPipedreamMcpConnections($){return($?.client??this.client).get({url:"/pipedream/mcp/connections",...$})}updatePipedreamMcpConnection($){return($.client??this.client).put({url:"/pipedream/mcp/connections",...$,headers:{"Content-Type":"application/json",...$.headers}})}listPipedreamMcpOverlays($){return($?.client??this.client).get({url:"/pipedream/mcp/overlays",...$})}recoverPipedreamMcpConnection($){return($.client??this.client).post({url:"/pipedream/mcp/recover",...$,headers:{"Content-Type":"application/json",...$.headers}})}createPipedreamMcpToken($){return($?.client??this.client).post({url:"/pipedream/mcp/token",...$,headers:{"Content-Type":"application/json",...$?.headers}})}getBatchPreview($){return($.client??this.client).post({url:"/preview",...$,headers:{"Content-Type":"application/json",...$.headers}})}sendChatMessage($){return($.client??this.client).post({url:"/stream/chat/message",...$,headers:{"Content-Type":"application/json",...$.headers}})}stopChatStream($){return($.client??this.client).post({url:"/stream/chat/message/stop",...$,headers:{"Content-Type":"application/json",...$.headers}})}structuredCompletion($){return($.client??this.client).post({url:"/structured-completion",...$,headers:{"Content-Type":"application/json",...$.headers}})}}function e2({onRequest:$,onSseError:O,onSseEvent:j,responseTransformer:x,responseValidator:S,sseDefaultRetryDelay:K,sseMaxRetryAttempts:Z,sseMaxRetryDelay:X,sseSleepFn:Y,url:L,...Q}){let J,I=Y??((V)=>new Promise((B)=>setTimeout(B,V)));return{stream:async function*(){let V=K??3000,B=0,H=Q.signal??new AbortController().signal;while(!0){if(H.aborted)break;B++;let P=Q.headers instanceof Headers?Q.headers:new Headers(Q.headers);if(J!==void 0)P.set("Last-Event-ID",J);try{let D={redirect:"follow",...Q,body:Q.serializedBody,headers:P,signal:H},_=new Request(L,D);if($)_=await $(L,D);let N=await(Q.fetch??globalThis.fetch)(_);if(!N.ok)throw Error(`SSE failed: ${N.status} ${N.statusText}`);if(!N.body)throw Error("No body in SSE response");let T=N.body.pipeThrough(new TextDecoderStream).getReader(),U="",g=()=>{try{T.cancel()}catch{}};H.addEventListener("abort",g);try{while(!0){let{done:r,value:p}=await T.read();if(r)break;U+=p,U=U.replace(/\r\n?/g,``);let y=U.split(``);U=y.pop()??"";for(let a of y){let i=a.split(`diff --git a/crates/connect_client/AGENTS.md b/crates/connect_client/AGENTS.mdnew file mode 100644index 0000000000..93afd00d5f--- /dev/null+++ b/crates/connect_client/AGENTS.md@@ -0,0 +1,36 @@+# connect_client++## What it is++A pinned copy of Macro Connect's public Rust client, `crates/connect_client`+in the private repo macro-inc/macro-connect, at commit `0814a61`. Macro reaches+Connect only through this crate.++## Start here++- `src/lib.rs`: `ConnectClient`: catalog, connect sessions, connections,+ token export, and the MCP gateway address (`mcp_upstream`).+- `src/wire.rs`: the JSON bodies Connect's API serves.++## Scope++- Owns: nothing. The source of truth is macro-inc/macro-connect.+- Not here: how Macro uses Connect → `pipedream_mcp` (`outbound/connect.rs`).++## Gotchas++- Do not edit it here. Change it upstream, then copy `src/` over again and+ update the commit above. The one local difference: trace headers are+ injected with `macro_tower_layers::inject_trace_headers` instead of+ Connect's `connect_platform`.+- It is a copy because Macro's CI and image builds cannot read the private+ repo. Replace it with a git dependency pinned to a rev once they can.++## Boundaries++- Depends on: `macro_tower_layers` (trace injection).+- Used by: `pipedream_mcp`.++## Checks++- `cargo nextest run -p connect_client`diff --git a/crates/connect_client/CLAUDE.md b/crates/connect_client/CLAUDE.mdnew file mode 120000index 0000000000..47dc3e3d86--- /dev/null+++ b/crates/connect_client/CLAUDE.md@@ -0,0 +1 @@+AGENTS.md\ No newline at end of filediff --git a/crates/connect_client/Cargo.toml b/crates/connect_client/Cargo.tomlnew file mode 100644index 0000000000..a43f247e56--- /dev/null+++ b/crates/connect_client/Cargo.toml@@ -0,0 +1,24 @@+[package]+name = "connect_client"+version = "0.1.0"+edition = "2024"+publish = false++[dependencies]+chrono = { workspace = true }+macro_tower_layers = { path = "../macro_tower_layers" }+reqwest = { workspace = true }+rootcause = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+strum = { workspace = true }+thiserror = { workspace = true }+tracing = { workspace = true }+url = { workspace = true }+utoipa = { workspace = true }+workspace-hack = { version = "0.1", path = "../workspace-hack" }+zeroize = { workspace = true }++[dev-dependencies]+tokio = { workspace = true }+wiremock = { workspace = true }diff --git a/crates/connect_client/src/lib.rs b/crates/connect_client/src/lib.rsnew file mode 100644index 0000000000..af90418434--- /dev/null+++ b/crates/connect_client/src/lib.rs@@ -0,0 +1,446 @@+#![deny(missing_docs)]++//! Typed, authenticated Rust client for the Macro Connect API.++pub mod wire;++use std::{fmt, time::Duration};++use macro_tower_layers::inject_trace_headers;+use reqwest::{Method, StatusCode, header::HeaderMap};+use tracing::Span;+use url::Url;+use zeroize::{Zeroize as _, Zeroizing};++use wire::{+ CatalogEntry, ConnectSessionRequest, ConnectSessionResponse, Connection, ConnectionsPage,+ ConnectionsQuery, ConnectionsSummary, DeleteResponse, ErrorResponse, ListedConnection,+ ListedUser, TokenResponse, UsersPage, UsersQuery,+};++/// A failure a Connect customer can act on.+#[derive(Debug, thiserror::Error)]+pub enum Error {+ /// The user has no connection to the requested app.+ #[error("app is not connected")]+ NotConnected,+ /// The user must reconnect the app.+ #[error("connection needs reauthorization")]+ NeedsReauth,+ /// The customer key was rejected.+ #[error("customer key was rejected")]+ Unauthorized,+ /// Connect could not be reached or is temporarily unavailable.+ #[error("Connect is unavailable")]+ Unavailable,+ /// Connect returned another API error.+ #[error("Connect API returned {status}: {message}")]+ Api {+ /// HTTP status code.+ status: StatusCode,+ /// API error code or response message.+ message: String,+ },+ /// Request construction or decoding failed.+ #[error("Connect client failed: {0}")]+ Internal(rootcause::Report),+}++/// Authenticated client for one Connect customer.+pub struct ConnectClient {+ base_url: Url,+ customer_key: Zeroizing<String>,+ http: reqwest::Client,+}++impl fmt::Debug for ConnectClient {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter+ .debug_struct("ConnectClient")+ .field("base_url", &self.base_url)+ .field("customer_key", &"[REDACTED]")+ .finish_non_exhaustive()+ }+}++/// Address and customer credential for an MCP client to dial Connect's gateway.+pub struct McpUpstream {+ /// Customer-scoped MCP gateway URL.+ pub url: Url,+ /// Customer bearer token to send to the gateway.+ pub bearer_token: String,+}++impl fmt::Debug for McpUpstream {+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {+ formatter+ .debug_struct("McpUpstream")+ .field("url", &self.url)+ .field("bearer_token", &"[REDACTED]")+ .finish()+ }+}++impl Drop for McpUpstream {+ fn drop(&mut self) {+ self.bearer_token.zeroize();+ }+}++impl ConnectClient {+ /// Construct a client for a Connect origin or prefixed base URL.+ pub fn new(base_url: &str, customer_key: impl Into<String>) -> Result<Self, Error> {+ let base_url = Url::parse(base_url)+ .map_err(|error| Error::Internal(rootcause::Report::new(error).into_dynamic()))?;+ if !matches!(base_url.scheme(), "http" | "https")+ || base_url.cannot_be_a_base()+ || !base_url.username().is_empty()+ || base_url.password().is_some()+ || base_url.query().is_some()+ || base_url.fragment().is_some()+ {+ return Err(Error::Internal(+ rootcause::Report::new(std::io::Error::new(+ std::io::ErrorKind::InvalidInput,+ "invalid Connect base URL",+ ))+ .into_dynamic(),+ ));+ }+ let http = reqwest::Client::builder()+ .connect_timeout(Duration::from_secs(10))+ .timeout(Duration::from_secs(30))+ .build()+ .map_err(|error| Error::Internal(rootcause::Report::new(error).into_dynamic()))?;+ Ok(Self {+ base_url,+ customer_key: Zeroizing::new(customer_key.into()),+ http,+ })+ }++ /// List apps available to connect.+ #[tracing::instrument(+ name = "connect.client.catalog",+ skip_all,+ fields(app_id, outcome),+ err+ )]+ pub async fn catalog(&self) -> Result<Vec<CatalogEntry>, Error> {+ self.request(Method::GET, &["v1", "catalog"], None).await+ }++ /// Fetch an official SVG icon from Connect's public catalog.+ pub async fn catalog_icon(&self, app_id: &str) -> Result<Vec<u8>, Error> {+ let mut headers = HeaderMap::new();+ inject_trace_headers(&mut headers);+ let response = self+ .http+ .get(self.route(&["v1", "catalog", app_id, "icon.svg"]))+ .headers(headers)+ .send()+ .await+ .map_err(|_| Error::Unavailable)?;+ if !response.status().is_success() {+ return Err(Error::Api {+ status: response.status(),+ message: "catalog icon unavailable".to_owned(),+ });+ }+ response+ .bytes()+ .await+ .map(|bytes| bytes.to_vec())+ .map_err(|_| Error::Unavailable)+ }++ /// Create a browser session for connecting a user's app.+ #[tracing::instrument(name = "connect.client.create_connect_session", skip_all, fields(app_id = %app_id, outcome), err)]+ pub async fn create_connect_session(+ &self,+ external_user_id: &str,+ app_id: &str,+ redirect_url: &str,+ ) -> Result<ConnectSessionResponse, Error> {+ let body = ConnectSessionRequest {+ external_user_id: external_user_id.to_owned(),+ app_id: app_id.to_owned(),+ redirect_url: redirect_url.to_owned(),+ };+ self.request(Method::POST, &["v1", "connect-sessions"], Some(&body))+ .await+ }++ /// List a user's app connections.+ #[tracing::instrument(+ name = "connect.client.connections",+ skip_all,+ fields(app_id, outcome),+ err+ )]+ pub async fn connections(&self, external_user_id: &str) -> Result<Vec<Connection>, Error> {+ self.request(+ Method::GET,+ &["v1", "users", external_user_id, "connections"],+ None,+ )+ .await+ }++ /// List one page of this customer's connections, newest first.+ #[tracing::instrument(+ name = "connect.client.list_connections",+ skip_all,+ fields(count, outcome),+ err+ )]+ pub async fn list_connections(+ &self,+ query: ConnectionsQuery,+ ) -> Result<ConnectionsPage, Error> {+ let mut url = self.route(&["v1", "connections"]);+ {+ let mut pairs = url.query_pairs_mut();+ if let Some(limit) = query.limit {+ pairs.append_pair("limit", &limit.to_string());+ }+ if let Some(cursor) = &query.cursor {+ pairs.append_pair("cursor", cursor);+ }+ if let Some(app_id) = &query.app_id {+ pairs.append_pair("app_id", app_id);+ }+ if let Some(status) = query.status {+ pairs.append_pair("status", &status.to_string());+ }+ }+ let page: ConnectionsPage = self.request_at(Method::GET, url, None).await?;+ Span::current().record("count", page.items.len());+ Ok(page)+ }++ /// Return summary counts for this customer.+ #[tracing::instrument(+ name = "connect.client.connections_summary",+ skip_all,+ fields(users, connections, outcome),+ err+ )]+ pub async fn connections_summary(&self) -> Result<ConnectionsSummary, Error> {+ let summary: ConnectionsSummary = self+ .request(Method::GET, &["v1", "connections", "summary"], None)+ .await?;+ Span::current().record("users", summary.users);+ Span::current().record("connections", summary.connections);+ Ok(summary)+ }++ /// Collect every page matching the filters. Callers should use pages for large datasets.+ pub async fn all_connections(+ &self,+ mut query: ConnectionsQuery,+ ) -> Result<Vec<ListedConnection>, Error> {+ let mut items = Vec::new();+ loop {+ let page = self.list_connections(query.clone()).await?;+ items.extend(page.items);+ match page.next_cursor {+ Some(cursor) if query.cursor.as_deref() != Some(&cursor) => {+ query.cursor = Some(cursor)+ }+ Some(_) => {+ return Err(Error::Internal(+ rootcause::Report::new(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "repeated connections cursor",+ ))+ .into_dynamic(),+ ));+ }+ None => return Ok(items),+ }+ }+ }++ /// List one page of connected users with all of each user's connections.+ #[tracing::instrument(+ name = "connect.client.list_users",+ skip_all,+ fields(count, outcome),+ err+ )]+ pub async fn list_users(&self, query: UsersQuery) -> Result<UsersPage, Error> {+ let mut url = self.route(&["v1", "users"]);+ {+ let mut pairs = url.query_pairs_mut();+ if let Some(limit) = query.limit {+ pairs.append_pair("limit", &limit.to_string());+ }+ if let Some(cursor) = &query.cursor {+ pairs.append_pair("cursor", cursor);+ }+ if let Some(app_id) = &query.app_id {+ pairs.append_pair("app_id", app_id);+ }+ if let Some(status) = query.status {+ pairs.append_pair("status", &status.to_string());+ }+ }+ let page: UsersPage = self.request_at(Method::GET, url, None).await?;+ Span::current().record("count", page.items.len());+ Ok(page)+ }++ /// Collect all connected users matching the filters.+ pub async fn all_users(&self, mut query: UsersQuery) -> Result<Vec<ListedUser>, Error> {+ let mut items = Vec::new();+ loop {+ let page = self.list_users(query.clone()).await?;+ items.extend(page.items);+ match page.next_cursor {+ Some(cursor) if query.cursor.as_deref() != Some(&cursor) => {+ query.cursor = Some(cursor)+ }+ Some(_) => {+ return Err(Error::Internal(+ rootcause::Report::new(std::io::Error::new(+ std::io::ErrorKind::InvalidData,+ "repeated users cursor",+ ))+ .into_dynamic(),+ ));+ }+ None => return Ok(items),+ }+ }+ }++ /// Delete a user's app connection locally. The vendor grant is not revoked.+ #[tracing::instrument(name = "connect.client.delete_connection", skip_all, fields(app_id = %app_id, outcome), err)]+ pub async fn delete_connection(+ &self,+ external_user_id: &str,+ app_id: &str,+ ) -> Result<DeleteResponse, Error> {+ self.request(+ Method::DELETE,+ &["v1", "users", external_user_id, "connections", app_id],+ None,+ )+ .await+ }++ /// Export a user's current vendor access token.+ #[tracing::instrument(name = "connect.client.access_token", skip_all, fields(app_id = %app_id, outcome), err)]+ pub async fn access_token(+ &self,+ external_user_id: &str,+ app_id: &str,+ ) -> Result<TokenResponse, Error> {+ self.request(+ Method::GET,+ &[+ "v1",+ "users",+ external_user_id,+ "connections",+ app_id,+ "token",+ ],+ None,+ )+ .await+ }++ /// Return the gateway address and credential without making a network call.+ #[tracing::instrument(name = "connect.client.mcp_upstream", skip_all, fields(app_id = %app_id, outcome = "ready"))]+ pub fn mcp_upstream(&self, external_user_id: &str, app_id: &str) -> McpUpstream {+ McpUpstream {+ url: self.route(&["v1", "users", external_user_id, "mcp", app_id]),+ bearer_token: self.customer_key.to_string(),+ }+ }++ fn route(&self, parts: &[&str]) -> Url {+ let mut url = self.base_url.clone();+ // `new` accepts only hierarchical HTTP URLs, so path segments are available.+ let mut segments = url.path_segments_mut().expect("validated HTTP base URL");+ segments.pop_if_empty();+ segments.extend(parts.iter().copied());+ drop(segments);+ url+ }++ async fn request<T: serde::de::DeserializeOwned>(+ &self,+ method: Method,+ parts: &[&str],+ body: Option<&ConnectSessionRequest>,+ ) -> Result<T, Error> {+ self.request_at(method, self.route(parts), body).await+ }++ async fn request_at<T: serde::de::DeserializeOwned>(+ &self,+ method: Method,+ url: Url,+ body: Option<&ConnectSessionRequest>,+ ) -> Result<T, Error> {+ let mut headers = HeaderMap::new();+ inject_trace_headers(&mut headers);+ let mut request = self+ .http+ .request(method, url)+ .headers(headers)+ .bearer_auth(self.customer_key.as_str());+ if let Some(body) = body {+ request = request.json(body);+ }+ let response = request.send().await.map_err(|error| {+ if error.is_connect() || error.is_timeout() {+ Span::current().record("outcome", "unavailable");+ Error::Unavailable+ } else {+ Span::current().record("outcome", "internal");+ Error::Internal(rootcause::Report::new(error).into_dynamic())+ }+ })?;+ let status = response.status();+ let bytes = response.bytes().await.map_err(|error| {+ Span::current().record("outcome", "internal");+ Error::Internal(rootcause::Report::new(error).into_dynamic())+ })?;+ if !status.is_success() {+ let message = serde_json::from_slice::<ErrorResponse>(&bytes)+ .map(|response| response.error)+ .unwrap_or_else(|_| status.canonical_reason().unwrap_or("API error").to_owned());+ let error = match (status, message.as_str()) {+ (StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN, _) => Error::Unauthorized,+ (status, _) if status.is_server_error() => Error::Unavailable,+ (StatusCode::NOT_FOUND, _) => Error::NotConnected,+ (StatusCode::CONFLICT, "needs_reauth") => Error::NeedsReauth,+ _ => Error::Api { status, message },+ };+ Span::current().record(+ "outcome",+ match error {+ Error::NotConnected => "not_connected",+ Error::NeedsReauth => "needs_reauth",+ Error::Unauthorized => "unauthorized",+ Error::Unavailable => "unavailable",+ _ => "api_error",+ },+ );+ return Err(error);+ }+ let value = serde_json::from_slice(&bytes).map_err(|error| {+ Span::current().record("outcome", "decode_error");+ Error::Internal(rootcause::Report::new(error).into_dynamic())+ })?;+ Span::current().record("outcome", "ok");+ Ok(value)+ }+}++#[cfg(test)]+mod test;diff --git a/crates/connect_client/src/test.rs b/crates/connect_client/src/test.rsnew file mode 100644index 0000000000..18cc4addba--- /dev/null+++ b/crates/connect_client/src/test.rs@@ -0,0 +1,237 @@+use super::*;+use wiremock::{+ Mock, MockServer, ResponseTemplate,+ matchers::{body_json, header, method, path, query_param},+};++#[tokio::test]+async fn calls_every_customer_route_with_the_shared_wire_contract() {+ let server = MockServer::start().await;+ let client =+ ConnectClient::new(&format!("{}/connect", server.uri()), "ck_test_secret").unwrap();+ Mock::given(method("GET"))+ .and(path("/connect/v1/catalog"))+ .and(header("authorization", "Bearer ck_test_secret"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!([{+ "id": "notion", "name": "Notion", "description": "Notes", "access": ["mcp"],+ "mcp_url": "https://mcp.notion.com/mcp", "icon_url": null,+ "oauth_client": "dcr", "pipedream_app_slugs": ["notion"]+ }])),+ )+ .mount(&server)+ .await;+ let catalog = client.catalog().await.unwrap();+ assert_eq!(catalog[0].id, "notion");+ assert_eq!(catalog[0].oauth_client, Some(wire::OAuthClient::Dcr));+ assert_eq!(catalog[0].pipedream_app_slugs, ["notion"]);++ Mock::given(method("GET"))+ .and(path("/connect/v1/catalog/notion/icon.svg"))+ .respond_with(ResponseTemplate::new(200).set_body_raw("<svg/>", "image/svg+xml"))+ .mount(&server)+ .await;+ assert_eq!(client.catalog_icon("notion").await.unwrap(), b"<svg/>");++ Mock::given(method("POST"))+ .and(path("/connect/v1/connect-sessions"))+ .and(body_json(serde_json::json!({+ "external_user_id": "user-1", "app_id": "notion", "redirect_url": "https://customer.test/done"+ })))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "connect_url": "https://connect.test/v1/connect/session", "expires_at": "2026-10-30T10:00:00Z"+ })))+ .mount(&server).await;+ let session = client+ .create_connect_session("user-1", "notion", "https://customer.test/done")+ .await+ .unwrap();+ assert_eq!(+ session.connect_url,+ "https://connect.test/v1/connect/session"+ );++ Mock::given(method("GET"))+ .and(path("/connect/v1/users/user-1/connections"))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(serde_json::json!([{+ "appId": "notion", "status": "active", "scopes": ["read"],+ "createdAt": "2026-10-30T09:00:00Z"+ }])),+ )+ .mount(&server)+ .await;+ let connections = client.connections("user-1").await.unwrap();+ assert_eq!(connections[0].app_id, "notion");+ assert!(matches!(+ connections[0].status,+ wire::ConnectionStatus::Active+ ));++ Mock::given(method("DELETE"))+ .and(path("/connect/v1/users/user-1/connections/notion"))+ .respond_with(+ ResponseTemplate::new(200)+ .set_body_json(serde_json::json!({"vendorGrantRevoked": false})),+ )+ .mount(&server)+ .await;+ assert!(+ !client+ .delete_connection("user-1", "notion")+ .await+ .unwrap()+ .vendor_grant_revoked+ );++ Mock::given(method("GET"))+ .and(path("/connect/v1/users/user-1/connections/notion/token"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "accessToken": "vendor-secret", "expiresAt": null+ })))+ .mount(&server)+ .await;+ let token = client.access_token("user-1", "notion").await.unwrap();+ assert_eq!(token.access_token, "vendor-secret");+ assert!(!format!("{token:?}").contains("vendor-secret"));++ let upstream = client.mcp_upstream("user-1", "notion");+ assert_eq!(+ upstream.url.as_str(),+ format!("{}/connect/v1/users/user-1/mcp/notion", server.uri())+ );+ assert_eq!(upstream.bearer_token, "ck_test_secret");+ assert!(!format!("{client:?} {upstream:?}").contains("ck_test_secret"));+ assert_eq!(server.received_requests().await.unwrap().len(), 6);+}++#[tokio::test]+async fn lists_customer_pages_and_summary_with_filters() {+ let server = MockServer::start().await;+ Mock::given(method("GET")).and(path("/v1/connections"))+ .and(header("authorization", "Bearer ck_test_secret"))+ .and(query_param("limit", "1"))+ .and(query_param("app_id", "notion"))+ .and(query_param("status", "active"))+ .respond_with(|request: &wiremock::Request| {+ if request.url.query_pairs().any(|(key, value)| key == "cursor" && value == "next") {+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": [{"externalUserId":"second","appId":"notion","status":"active","scopes":[],"createdAt":"2026-10-29T09:00:00Z","updatedAt":"2026-10-29T10:00:00Z","accessTokenExpiresAt":null}],"nextCursor":null}))+ } else {+ ResponseTemplate::new(200).set_body_json(serde_json::json!({"items": [{"externalUserId":"first","appId":"notion","status":"active","scopes":["read"],"createdAt":"2026-10-30T09:00:00Z","updatedAt":"2026-10-30T10:00:00Z","accessTokenExpiresAt":"2026-10-30T11:00:00Z"}],"nextCursor":"next"}))+ }+ }).mount(&server).await;+ Mock::given(method("GET")).and(path("/v1/connections/summary"))+ .and(header("authorization", "Bearer ck_test_secret"))+ .respond_with(ResponseTemplate::new(200).set_body_json(serde_json::json!({"users":2,"connections":2,"needsReauth":0,"apps":[{"appId":"notion","active":2,"needsReauth":0}]})))+ .mount(&server).await;+ let client = ConnectClient::new(&server.uri(), "ck_test_secret").unwrap();+ let query = wire::ConnectionsQuery {+ limit: Some(1),+ cursor: None,+ app_id: Some("notion".into()),+ status: Some(wire::ConnectionStatus::Active),+ };+ let page = client.list_connections(query.clone()).await.unwrap();+ assert_eq!(page.items[0].external_user_id, "first");+ assert!(page.items[0].access_token_expires_at.is_some());+ assert_eq!(page.next_cursor.as_deref(), Some("next"));+ let all = client.all_connections(query).await.unwrap();+ assert_eq!(+ all.iter()+ .map(|item| item.external_user_id.as_str())+ .collect::<Vec<_>>(),+ ["first", "second"]+ );+ let summary = client.connections_summary().await.unwrap();+ assert_eq!(+ (summary.users, summary.connections, summary.apps[0].active),+ (2, 2, 2)+ );+}++#[tokio::test]+async fn lists_complete_user_pages_with_filters() {+ let server = MockServer::start().await;+ Mock::given(method("GET")).and(path("/v1/users"))+ .and(header("authorization", "Bearer ck_test_secret"))+ .and(query_param("limit", "1"))+ .and(query_param("app_id", "notion"))+ .and(query_param("status", "active"))+ .respond_with(|request: &wiremock::Request| {+ let (user, cursor) = if request.url.query_pairs().any(|(key, value)| key == "cursor" && value == "next") {+ ("second", serde_json::Value::Null)+ } else {+ ("first", serde_json::json!("next"))+ };+ ResponseTemplate::new(200).set_body_json(serde_json::json!({+ "items":[{"externalUserId":user,"firstConnectedAt":"2026-10-30T09:00:00Z","connections":[+ {"externalUserId":user,"appId":"linear","status":"needs_reauth","scopes":[],"createdAt":"2026-10-29T09:00:00Z","updatedAt":"2026-10-29T10:00:00Z","accessTokenExpiresAt":null},+ {"externalUserId":user,"appId":"notion","status":"active","scopes":[],"createdAt":"2026-10-30T09:00:00Z","updatedAt":"2026-10-30T10:00:00Z","accessTokenExpiresAt":null}+ ]}],"nextCursor":cursor+ }))+ }).mount(&server).await;+ let client = ConnectClient::new(&server.uri(), "ck_test_secret").unwrap();+ let query = wire::UsersQuery {+ limit: Some(1),+ cursor: None,+ app_id: Some("notion".into()),+ status: Some(wire::ConnectionStatus::Active),+ };+ let first = client.list_users(query.clone()).await.unwrap();+ assert_eq!(first.items.len(), 1);+ assert_eq!(first.items[0].connections.len(), 2);+ assert_eq!(first.next_cursor.as_deref(), Some("next"));+ let all = client.all_users(query).await.unwrap();+ assert_eq!(+ all.iter()+ .map(|user| user.external_user_id.as_str())+ .collect::<Vec<_>>(),+ ["first", "second"]+ );+}++#[tokio::test]+async fn maps_status_and_error_codes_for_callers() {+ for (status, code, expected) in [+ (404, "not_found", "not_connected"),+ (409, "needs_reauth", "needs_reauth"),+ (401, "invalid_key", "unauthorized"),+ (401, "not_found", "unauthorized"),+ (500, "internal_error", "unavailable"),+ (500, "not_found", "unavailable"),+ (503, "internal_error", "unavailable"),+ (400, "invalid_redirect_url", "api"),+ ] {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/v1/users/user-1/connections"))+ .respond_with(+ ResponseTemplate::new(status).set_body_json(serde_json::json!({"error": code})),+ )+ .mount(&server)+ .await;+ let client = ConnectClient::new(&server.uri(), "ck_test_secret").unwrap();+ let error = client.connections("user-1").await.unwrap_err();+ match expected {+ "not_connected" => assert!(matches!(error, Error::NotConnected)),+ "needs_reauth" => assert!(matches!(error, Error::NeedsReauth)),+ "unauthorized" => assert!(matches!(error, Error::Unauthorized)),+ "unavailable" => assert!(matches!(error, Error::Unavailable)),+ "api" => assert!(+ matches!(error, Error::Api { status: StatusCode::BAD_REQUEST, message } if message == code)+ ),+ _ => unreachable!(),+ }+ }+}++#[tokio::test]+async fn mcp_gateway_path_escapes_customer_identifiers() {+ let client = ConnectClient::new("https://connect.test/connect/", "private-key").unwrap();+ let upstream = client.mcp_upstream("user/one", "notion");+ assert_eq!(+ upstream.url.as_str(),+ "https://connect.test/connect/v1/users/user%2Fone/mcp/notion"+ );+ assert!(!format!("{client:?} {upstream:?}").contains("private-key"));+}diff --git a/crates/connect_client/src/wire.rs b/crates/connect_client/src/wire.rsnew file mode 100644index 0000000000..b1c3631403--- /dev/null+++ b/crates/connect_client/src/wire.rs@@ -0,0 +1,244 @@+//! Shared JSON bodies for Macro Connect's customer-facing routes.++use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;+use zeroize::Zeroize as _;++/// An app available in Connect's catalog.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+pub struct CatalogEntry {+ /// Stable app identifier.+ pub id: String,+ /// Display name.+ pub name: String,+ /// Short capabilities description.+ pub description: String,+ /// Access methods, such as `mcp`.+ pub access: Vec<String>,+ /// How Connect obtains an OAuth client; absent for API-key-only apps.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub oauth_client: Option<OAuthClient>,+ /// Vendor-owned MCP server URL.+ pub mcp_url: String,+ /// Connect-served icon path when an official SVG is available.+ pub icon_url: Option<String>,+ /// Pipedream Connect app slugs this app replaces, for customers migrating+ /// connections off Pipedream. Empty when there is no equivalent.+ #[serde(default)]+ pub pipedream_app_slugs: Vec<String>,+}++/// How Connect obtains a vendor OAuth client.+#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum OAuthClient {+ /// Connect registers and manages its own vendor OAuth app.+ ManagedOauthApp,+ /// The vendor authorization server registers Connect's client.+ Dcr,+}++/// Body for creating a browser connect session.+#[derive(Debug, Deserialize, Serialize, ToSchema)]+pub struct ConnectSessionRequest {+ /// Customer's user identifier.+ #[serde(alias = "externalUserId")]+ pub external_user_id: String,+ /// App to connect.+ #[serde(alias = "appId")]+ pub app_id: String,+ /// Customer callback URL.+ #[serde(alias = "redirectUrl")]+ pub redirect_url: String,+}++/// URL and expiration of a browser connect session.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+pub struct ConnectSessionResponse {+ /// URL for the user's browser to visit.+ pub connect_url: String,+ /// Session expiration.+ pub expires_at: DateTime<Utc>,+}++/// One of a customer's user connections.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct Connection {+ /// Stable app identifier.+ pub app_id: String,+ /// Whether the grant can be used.+ pub status: ConnectionStatus,+ /// Granted OAuth scopes.+ pub scopes: Vec<String>,+ /// Creation time.+ pub created_at: DateTime<Utc>,+}++/// Filters and paging for a customer's connections.+#[derive(Clone, Debug, Default, Deserialize, Serialize)]+pub struct ConnectionsQuery {+ /// Page size; defaults to 100 and cannot exceed 500.+ pub limit: Option<u16>,+ /// Opaque cursor from a prior page.+ pub cursor: Option<String>,+ /// Restrict results to an app.+ pub app_id: Option<String>,+ /// Restrict results to a connection status.+ pub status: Option<ConnectionStatus>,+}++/// A connection and its owning customer's opaque user identifier.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListedConnection {+ /// Customer-provided user identifier.+ pub external_user_id: String,+ /// Stable app identifier.+ pub app_id: String,+ /// Current usability.+ pub status: ConnectionStatus,+ /// Granted OAuth scopes.+ pub scopes: Vec<String>,+ /// Creation time.+ pub created_at: DateTime<Utc>,+ /// Last connection update.+ pub updated_at: DateTime<Utc>,+ /// Access token expiration, when known.+ pub access_token_expires_at: Option<DateTime<Utc>>,+}++/// One page of customer connections.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectionsPage {+ /// Connections in descending creation order.+ pub items: Vec<ListedConnection>,+ /// Opaque position for the next page, or null when complete.+ pub next_cursor: Option<String>,+}++/// Filters and paging for a customer's connected users.+#[derive(Clone, Debug, Default, Deserialize, Serialize)]+pub struct UsersQuery {+ /// Number of users per page; defaults to 100 and cannot exceed 500.+ pub limit: Option<u16>,+ /// Opaque cursor from a prior page.+ pub cursor: Option<String>,+ /// Select users with a matching app connection.+ pub app_id: Option<String>,+ /// Select users with a matching connection status.+ pub status: Option<ConnectionStatus>,+}++/// A customer user and all of their connections.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ListedUser {+ /// Customer-provided user identifier.+ pub external_user_id: String,+ /// Creation time of the user's first connection.+ pub first_connected_at: DateTime<Utc>,+ /// Every connection of the user, ordered by app ID.+ pub connections: Vec<ListedConnection>,+}++/// One page of connected users.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct UsersPage {+ /// Users ordered by first connection time, newest first, then user ID descending.+ pub items: Vec<ListedUser>,+ /// Opaque position for the next page, or null when complete.+ pub next_cursor: Option<String>,+}++/// Connection counts for one catalog app.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct AppConnectionsSummary {+ /// Stable app identifier.+ pub app_id: String,+ /// Usable connections.+ pub active: u64,+ /// Connections requiring new consent.+ pub needs_reauth: u64,+}++/// Counts for a customer and each app with connections.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ConnectionsSummary {+ /// Distinct users with at least one connection.+ pub users: u64,+ /// Total connections.+ pub connections: u64,+ /// Connections requiring new consent.+ pub needs_reauth: u64,+ /// Counts by app; apps with no connections are omitted.+ pub apps: Vec<AppConnectionsSummary>,+}++/// Current usability of a connection.+#[derive(+ Clone, Copy, Debug, Deserialize, Serialize, ToSchema, strum::EnumString, strum::Display,+)]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum ConnectionStatus {+ /// Grant is available.+ Active,+ /// User must grant access again.+ NeedsReauth,+}++/// Result of deleting a connection locally.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct DeleteResponse {+ /// Always false: deleting locally does not revoke the vendor grant.+ pub vendor_grant_revoked: bool,+}++/// An exported OAuth access token.+#[derive(Deserialize, Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct TokenResponse {+ /// Bearer token for the vendor API.+ pub access_token: String,+ /// Expiration, when supplied by the vendor.+ pub expires_at: Option<DateTime<Utc>>,+}++impl std::fmt::Debug for TokenResponse {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("TokenResponse")+ .field("access_token", &"[REDACTED]")+ .field("expires_at", &self.expires_at)+ .finish()+ }+}++impl Drop for TokenResponse {+ fn drop(&mut self) {+ self.access_token.zeroize();+ }+}++/// Connect API error body.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+pub struct ErrorResponse {+ /// Stable machine-readable error code.+ pub error: String,+}++/// MCP gateway error body.+#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]+pub struct McpErrorResponse {+ /// Stable machine-readable error code.+ pub error: String,+ /// App for which the request failed.+ pub app_id: String,+}diff --git a/crates/granola_sync/src/outbound/accounts.rs b/crates/granola_sync/src/outbound/accounts.rsindex 40529daea5..a10102b03c 100644--- a/crates/granola_sync/src/outbound/accounts.rs+++ b/crates/granola_sync/src/outbound/accounts.rs@@ -4,11 +4,21 @@ use crate::domain::{};use async_trait::async_trait;use macro_user_id::user_id::MacroUserIdStr;-use pipedream_mcp::domain::ports::{AppConnections, ConnectionStore};+use pipedream_mcp::domain::{+ models::{ConnectionProvider, PipedreamConnection},+ ports::{AppConnections, ConnectionStore},+};/// Uses the Pipedream domain ports rather than reaching into its storage.pub struct ConnectedAccounts<S>(pub S);+/// Sync reads Granola's REST API, which takes Pipedream's API-key account.+/// A Granola connection held by Macro Connect is an MCP grant, which that API+/// does not accept, so it is not synced.+fn syncable(connection: &PipedreamConnection) -> bool {+ connection.enabled && connection.provider == ConnectionProvider::Pipedream+}+#[async_trait]impl<S: ConnectionStore + AppConnections> Accounts for ConnectedAccounts<S> {async fn account(&self, user: &MacroUserIdStr<'static>) -> Result<Option<String>> {@@ -17,7 +27,7 @@ impl<S: ConnectionStore + AppConnections> Accounts for ConnectedAccounts<S> {.load(user, GRANOLA_APP).await.map_err(|error| rootcause::report!("Pipedream connection lookup failed: {error:?}"))?- .filter(|connection| connection.enabled)+ .filter(syncable).map(|connection| connection.account_id))}async fn connected(&self) -> Result<Vec<(MacroUserIdStr<'static>, String)>> {@@ -27,7 +37,31 @@ impl<S: ConnectionStore + AppConnections> Accounts for ConnectedAccounts<S> {.await.map_err(|error| rootcause::report!("Pipedream connection listing failed: {error:?}"))?.into_iter()+ .filter(syncable).map(|connection| (connection.user_id, connection.account_id)).collect())}}++#[cfg(test)]+mod test {+ use super::*;++ fn connection(provider: ConnectionProvider, enabled: bool) -> PipedreamConnection {+ PipedreamConnection {+ user_id: MacroUserIdStr::try_from_email("[email protected]").unwrap(),+ app_slug: GRANOLA_APP.into(),+ server_name: "Granola".into(),+ account_id: "apn_1".into(),+ enabled,+ provider,+ }+ }++ #[test]+ fn only_enabled_pipedream_accounts_sync() {+ assert!(syncable(&connection(ConnectionProvider::Pipedream, true)));+ assert!(!syncable(&connection(ConnectionProvider::Pipedream, false)));+ assert!(!syncable(&connection(ConnectionProvider::Connect, true)));+ }+}diff --git a/crates/granola_sync/src/outbound/api.rs b/crates/granola_sync/src/outbound/api.rsindex 0f38acece7..5e683d3568 100644--- a/crates/granola_sync/src/outbound/api.rs+++ b/crates/granola_sync/src/outbound/api.rs@@ -42,6 +42,7 @@ impl<P: ConnectedAppProxy> GranolaApi<P> {server_name: "Granola".into(),account_id: connection.account_id.clone(),enabled: true,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,};let response = self.0diff --git a/crates/import_notion/src/outbound/pipedream/test.rs b/crates/import_notion/src/outbound/pipedream/test.rsindex adbecd6942..003204063b 100644--- a/crates/import_notion/src/outbound/pipedream/test.rs+++ b/crates/import_notion/src/outbound/pipedream/test.rs@@ -95,6 +95,7 @@ async fn a_connected_user_reaches_notion_through_the_proxy_with_one_pacer_per_acserver_name: "Notion".into(),account_id: "apn_notion".into(),enabled: true,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,})));let proxy = Arc::new(RecordingProxy::default());let connections = PipedreamNotionConnections::new(store, Some(proxy.clone()));@@ -143,6 +144,7 @@ async fn no_connection_a_disabled_one_or_no_proxy_means_no_notion() {server_name: "Notion".into(),account_id: "apn_notion".into(),enabled: false,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,};let enabled = PipedreamConnection {enabled: true,diff --git a/crates/import_tracker/test_support.rs b/crates/import_tracker/test_support.rsindex ebedf394c2..b7e84a7f62 100644--- a/crates/import_tracker/test_support.rs+++ b/crates/import_tracker/test_support.rs@@ -20,6 +20,7 @@ impl ConnectionStore for Store {server_name: slug.into(),account_id: "apn_test".into(),enabled: true,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,}))}async fn save(&self, _: &PipedreamConnection) -> Result<(), Self::Err> {diff --git a/crates/macro_db_client/migrations/20261103130404_pipedream_connections_provider.sql b/crates/macro_db_client/migrations/20261103130404_pipedream_connections_provider.sqlnew file mode 100644index 0000000000..65c320e73d--- /dev/null+++ b/crates/macro_db_client/migrations/20261103130404_pipedream_connections_provider.sql@@ -0,0 +1,8 @@+-- Which backend holds a connection's grant: Pipedream Connect, or Macro+-- Connect (`connect`). For `connect` rows, `account_id` is Connect's app id+-- and `app_slug` stays the Pipedream slug the app replaces, so tool+-- selection and agent egress keep keying connections by slug.+ALTER TABLE pipedream_mcp_connections+ ADD COLUMN provider TEXT NOT NULL DEFAULT 'pipedream'+ CONSTRAINT pipedream_mcp_connections_provider_check+ CHECK (provider IN ('pipedream', 'connect'));diff --git a/crates/macro_service_urls/src/lib.rs b/crates/macro_service_urls/src/lib.rsindex e409015d87..9f7a25d3bf 100644--- a/crates/macro_service_urls/src/lib.rs+++ b/crates/macro_service_urls/src/lib.rs@@ -602,6 +602,12 @@ service_url! {dev: "https://document-cognition-dev.macro.com",prod: "https://document-cognition.macro.com",},+ /// Macro Connect API base URL: Macro's OAuth broker for MCP connectors.+ pub ConnectApiUrl {+ local: "http://localhost:8080",+ dev: "https://connect-dev.macro.com",+ prod: "https://connect.macro.com",+ },/// Link unfurl service API URL.pub UnfurlServiceUrl {local: "http://localhost:8095",diff --git a/crates/macro_service_urls/src/test.rs b/crates/macro_service_urls/src/test.rsindex 9ada4b2401..a57e625ce0 100644--- a/crates/macro_service_urls/src/test.rs+++ b/crates/macro_service_urls/src/test.rs@@ -805,3 +805,8 @@ fn service_url_converts_to_string() {assert_eq!(url_string, "https://borrowed.macro.com");}++#[test]+fn connect_api_url_parses() {+ assert_parses_for_all_environments(ConnectApiUrl::default_for_environment);+}diff --git a/crates/mcp_select/src/selection/test.rs b/crates/mcp_select/src/selection/test.rsindex fe4987beff..6c7f273c13 100644--- a/crates/mcp_select/src/selection/test.rs+++ b/crates/mcp_select/src/selection/test.rs@@ -20,6 +20,7 @@ fn pd(slug: &str, enabled: bool) -> PipedreamConnection {server_name: slug.into(),account_id: "account".into(),enabled,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,}}diff --git a/crates/mcp_select/src/test.rs b/crates/mcp_select/src/test.rsindex 51bd28d2fa..b0d4365d9f 100644--- a/crates/mcp_select/src/test.rs+++ b/crates/mcp_select/src/test.rs@@ -99,6 +99,7 @@ fn connections(slugs: &[&str]) -> Vec<PipedreamConnection> {server_name: "Slack".to_string(),account_id: format!("apn_{slug}"),enabled: true,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,}).collect()}@@ -390,6 +391,7 @@ async fn mixed_stack_discovers_and_dispatches_both_and_deduplicates_names() {server_name: hosted_name.into(),account_id: "test".into(),enabled: true,+ provider: pipedream_mcp::domain::models::ConnectionProvider::Pipedream,}],native_records: vec![McpServerRecord {user_id: user(),diff --git a/crates/pipedream_mcp/AGENTS.md b/crates/pipedream_mcp/AGENTS.mdindex 5fabecdef0..4024caff35 100644--- a/crates/pipedream_mcp/AGENTS.md+++ b/crates/pipedream_mcp/AGENTS.md@@ -4,7 +4,10 @@Part of the AI agent tools feature. Lets users connect third-party appsthrough Pipedream Connect (Pipedream owns grants/tokens/refresh), and the-AI loop calls their tools through Pipedream's remote MCP server.+AI loop calls their tools through Pipedream's remote MCP server. A user the+`macro-connect` flag is on for is on Macro Connect alone (Macro's own OAuth+apps; Connect owns grants and refresh): directory, connect flow, tool+listings, and calls all go through Connect, with no Pipedream fallback.## Start here@@ -23,6 +26,19 @@ AI loop calls their tools through Pipedream's remote MCP server.(also reached through `recover_pipedream_connection`)refuses them (409) and deletes the new Pipedream account.- `src/inbound/toolset.rs`: how connected apps surface as agent tools.+- `src/outbound/connect.rs`: the Macro Connect adapter over+ `connect_client` (a pinned copy of Connect's client): tools through Connect's+ MCP gateway, app API calls with an exported access token, catalog apps+ addressed by the Pipedream slugs they replace.+- `src/outbound/dispatch.rs`: `ConnectorBackends`, the one type hosts wire:+ it holds the host's `ConnectRollout` (the `macro-connect` PostHog flag,+ read by `ai_tools::macro_connect_rollout`). A user on Connect alone gets+ Connect's directory and tool listings, and their Pipedream rows are+ refused; everyone else stays on Pipedream. A Connect row always reaches+ Connect.+- `src/domain/service/connect.rs`: `start_connect_session` and+ `complete_connect_connection` record Connect connections; the router only+ calls them for users on Connect alone (`MacroConnect::connect_only`).## Scope@@ -35,13 +51,23 @@ AI loop calls their tools through Pipedream's remote MCP server.## Boundaries- Depends on: `ai_toolset`, `mcp_toolset`, `macro_authorization`,- `macro_user_id`.+ `macro_user_id`, `connect_client` (the only Connect crate Macro may use).- Used by: `ai_tools`, `import_notion`, `import_tracker`, `import_linear`,`import_jira`, `agent_egress`, `agent_harness`,`granola_sync`, `mcp_select`, `services/agent_harness_service`.## Gotchas+- A `provider = connect` row stores Connect's app id in `account_id` and keeps+ the Pipedream slug in `app_slug`, so `mcp_select` and agent egress need no+ changes. Granola connects through Connect like any app (an MCP grant).+ Granola meeting sync still reads Granola's API-key REST API, so it only+ syncs Pipedream-held Granola accounts; sync over Granola's MCP server is+ follow-up work.+- The Connect consent redirect (`/pipedream/mcp/connect/callback`) is public+ and records nothing; the app polls `/pipedream/mcp/connect/complete`, which+ trusts only Connect's own connection list.+- Overlaying an app hides its Pipedream grant from every reader, includingimports (Linear, Jira, Notion) and Granola sync, which use the Pipedreamproxy. Keep those slugs out of `mcp_overlays` until their readers have adiff --git a/crates/pipedream_mcp/Cargo.toml b/crates/pipedream_mcp/Cargo.tomlindex 6c92ded9cb..6ff9714ec3 100644--- a/crates/pipedream_mcp/Cargo.toml+++ b/crates/pipedream_mcp/Cargo.toml@@ -11,6 +11,7 @@ async-trait.workspace = truebase64.workspace = trueaxum.workspace = truechrono.workspace = true+connect_client = { path = "../connect_client" }futures.workspace = truehttp.workspace = truemacro_authorization = { path = "../macro_authorization", default-features = false, features = [diff --git a/crates/pipedream_mcp/src/domain/models.rs b/crates/pipedream_mcp/src/domain/models.rsindex 2247d6b311..dd57deea6f 100644--- a/crates/pipedream_mcp/src/domain/models.rs+++ b/crates/pipedream_mcp/src/domain/models.rs@@ -1,11 +1,10 @@pub use macro_user_id::user_id::MacroUserIdStr;pub use mcp_toolset::{MCP_CLIENT_NAME, McpServer, client_info};-/// An MCP connector a user has connected through Pipedream.+/// An MCP connector a user has connected through Pipedream or Macro Connect.///-/// 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.+/// The provider owns the OAuth grant and tokens for the connected account; we+/// store only which app the user connected and where the grant lives.#[derive(Clone, Debug, PartialEq, Eq)]pub struct PipedreamConnection {/// The user who connected the app.@@ -14,10 +13,56 @@ pub struct PipedreamConnection {pub app_slug: String,/// Human-readable display name, e.g. `Linear`.pub server_name: String,- /// The Pipedream connected-account ID holding the grant.+ /// Where the grant lives: the Pipedream connected-account ID, or for+ /// [`ConnectionProvider::Connect`] the Connect app ID.pub account_id: String,/// Whether the connector is enabled for tool use.pub enabled: bool,+ /// Which backend holds the grant and serves the tools.+ pub provider: ConnectionProvider,+}++/// The backend holding a connection's grant.+///+/// A record keeps the Pipedream app slug either way, so tool selection and+/// agent egress key connections the same way for both.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+pub enum ConnectionProvider {+ /// Pipedream Connect: `account_id` is a Pipedream account (`apn_...`).+ #[default]+ Pipedream,+ /// Macro Connect: `account_id` is the Connect app ID.+ Connect,+}++impl ConnectionProvider {+ /// The value stored in `pipedream_mcp_connections.provider`.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Pipedream => "pipedream",+ Self::Connect => "connect",+ }+ }++ /// Parse a stored provider value.+ pub fn parse(value: &str) -> anyhow::Result<Self> {+ match value {+ "pipedream" => Ok(Self::Pipedream),+ "connect" => Ok(Self::Connect),+ other => anyhow::bail!("unknown connection provider {other:?}"),+ }+ }+}++/// A Macro Connect catalog app, addressed by the Pipedream slug it replaces.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct ConnectApp {+ /// Connect's app ID, e.g. `airtable`.+ pub app_id: String,+ /// The Pipedream app slug it stands in for, e.g. `airtable_oauth`.+ pub app_slug: String,+ /// Human-readable name, e.g. `Airtable`.+ pub name: String,}/// A catalog app that connects through the native MCP stack instead ofdiff --git a/crates/pipedream_mcp/src/domain/ports.rs b/crates/pipedream_mcp/src/domain/ports.rsindex 5cf1861480..4a22de1ee5 100644--- a/crates/pipedream_mcp/src/domain/ports.rs+++ b/crates/pipedream_mcp/src/domain/ports.rs@@ -1,6 +1,6 @@use super::models::{- CatalogEntry, CatalogPage, ConnectToken, ConnectorOverlay, MacroUserIdStr, McpServer,- PipedreamAccount, PipedreamConnection,+ CatalogEntry, CatalogPage, ConnectApp, ConnectToken, ConnectorOverlay, MacroUserIdStr,+ McpServer, PipedreamAccount, PipedreamConnection,};/// The catalog apps that connect through the native MCP stack instead of@@ -139,7 +139,48 @@ pub trait PipedreamConnect: Send + Sync + 'static {fn delete_account(&self, account_id: &str) -> impl Future<Output = anyhow::Result<()>> + Send;}-/// Port for browsing the directory of connectable apps.+/// Port for Macro Connect's connect flow: Connect owns the consent flow,+/// the grant, and refresh, like Pipedream Connect, but Macro owns the OAuth+/// apps. Apps are addressed by the Pipedream slug they replace.+pub trait MacroConnect: Send + Sync + 'static {+ /// Whether every connector call for `user_id` goes through Connect, with+ /// no Pipedream at all: Connect is configured and the `macro-connect`+ /// rollout is on for them. Otherwise everything stays on Pipedream.+ fn connect_only(&self, user_id: &MacroUserIdStr<'static>) -> impl Future<Output = bool> + Send;++ /// The Connect app standing in for `app_slug`, or `None` when Connect+ /// does not serve it (or is not configured).+ fn app_for_slug(+ &self,+ app_slug: &str,+ ) -> impl Future<Output = anyhow::Result<Option<ConnectApp>>> + Send;++ /// Start a browser connect session for `user_id` and return the URL to+ /// open. Connect redirects back to Macro when consent finishes.+ fn create_connect_session(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app: &ConnectApp,+ ) -> impl Future<Output = anyhow::Result<String>> + Send;++ /// Whether `user_id` holds a usable connection to `app_id`.+ fn is_connected(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_id: &str,+ ) -> impl Future<Output = anyhow::Result<bool>> + Send;++ /// Delete `user_id`'s connection to `app_id` from Connect.+ fn delete_connection(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_id: &str,+ ) -> impl Future<Output = anyhow::Result<()>> + Send;+}++/// Port for browsing the directory of connectable apps. Lookups are for a+/// user because the directory is theirs: Connect's catalog for a user on+/// Connect (see [`MacroConnect::connect_only`]), Pipedream's otherwise.pub trait ConnectorDirectory: Send + Sync + 'static {/// Search the directory.///@@ -150,6 +191,7 @@ pub trait ConnectorDirectory: Send + Sync + 'static {/// action to expose as a tool) and that the catalog doesn't hide.fn search(&self,+ user_id: &MacroUserIdStr<'static>,search: Option<&str>,cursor: Option<&str>,limit: u32,@@ -163,6 +205,7 @@ pub trait ConnectorDirectory: Send + Sync + 'static {/// miss.fn retrieve(&self,+ user_id: &MacroUserIdStr<'static>,app_slug: &str,) -> impl Future<Output = anyhow::Result<Option<CatalogEntry>>> + Send;}@@ -223,3 +266,12 @@ pub trait ConnectedAppProxy: Send + Sync + 'static {body: Option<&serde_json::Value>,) -> impl Future<Output = anyhow::Result<ProxyResponse>> + Send;}++/// Whether the `macro-connect` rollout is on for a user: every connector+/// call for them goes through Macro Connect instead of Pipedream. Hosts read+/// the feature flag here; a failed read must answer `false`.+pub type ConnectRollout = std::sync::Arc<+ dyn Fn(MacroUserIdStr<'static>) -> std::pin::Pin<Box<dyn Future<Output = bool> + Send>>+ + Send+ + Sync,+>;diff --git a/crates/pipedream_mcp/src/domain/service/catalog.rs b/crates/pipedream_mcp/src/domain/service/catalog.rsindex e807efd170..2aa4671602 100644--- a/crates/pipedream_mcp/src/domain/service/catalog.rs+++ b/crates/pipedream_mcp/src/domain/service/catalog.rs@@ -1,11 +1,12 @@//! Browsing the catalog of connectable MCP apps.//!-//! The catalog is Pipedream's app directory, ranked by Pipedream's own-//! popularity ordering (see the directory adapter). Clients render the+//! The catalog is the user's directory: Macro Connect's catalog for a user+//! on Connect alone, otherwise Pipedream's app directory, ranked by+//! Pipedream's own popularity ordering (see the directory adapters). Clients render the//! user's connected apps as their own section from the connections//! endpoint; the catalog itself carries no curated pinning.-use crate::domain::models::CatalogPage;+use crate::domain::models::{CatalogPage, MacroUserIdStr};use crate::domain::ports::ConnectorDirectory;#[cfg(test)]@@ -20,6 +21,7 @@ const DEFAULT_PAGE_SIZE: u32 = 20;#[tracing::instrument(skip(directory), err)]pub async fn browse_catalog<D: ConnectorDirectory>(directory: &D,+ user_id: &MacroUserIdStr<'static>,search: Option<&str>,cursor: Option<&str>,limit: Option<u32>,@@ -27,5 +29,5 @@ pub async fn browse_catalog<D: ConnectorDirectory>(let search = search.map(str::trim).filter(|s| !s.is_empty());let limit = limit.unwrap_or(DEFAULT_PAGE_SIZE).clamp(1, MAX_PAGE_SIZE);- directory.search(search, cursor, limit).await+ directory.search(user_id, search, cursor, limit).await}diff --git a/crates/pipedream_mcp/src/domain/service/catalog/test.rs b/crates/pipedream_mcp/src/domain/service/catalog/test.rsindex 5235dbc78f..9664876182 100644--- a/crates/pipedream_mcp/src/domain/service/catalog/test.rs+++ b/crates/pipedream_mcp/src/domain/service/catalog/test.rs@@ -1,5 +1,9 @@use super::*;use crate::domain::models::CatalogEntry;++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email("[email protected]").unwrap()+}use std::sync::Mutex;/// Search text, pagination cursor, and page size sent to the directory.@@ -26,6 +30,7 @@ impl FakeDirectory {impl ConnectorDirectory for FakeDirectory {async fn search(&self,+ _user_id: &MacroUserIdStr<'static>,search: Option<&str>,cursor: Option<&str>,limit: u32,@@ -38,7 +43,11 @@ impl ConnectorDirectory for FakeDirectory {Ok(self.page.clone())}- async fn retrieve(&self, app_slug: &str) -> anyhow::Result<Option<CatalogEntry>> {+ async fn retrieve(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ ) -> anyhow::Result<Option<CatalogEntry>> {Ok(self.page.entries@@ -63,7 +72,9 @@ async fn directory_results_pass_through_in_order() {let directory =FakeDirectory::returning(vec![directory_entry("slack"), directory_entry("airtable")]);- let page = browse_catalog(&directory, None, None, None).await.unwrap();+ let page = browse_catalog(&directory, &user(), None, None, None)+ .await+ .unwrap();let slugs: Vec<_> = page.entries.iter().map(|e| e.app_slug.as_str()).collect();assert_eq!(slugs, ["slack", "airtable"]);@@ -73,9 +84,15 @@ async fn directory_results_pass_through_in_order() {async fn search_is_trimmed_and_forwarded() {let directory = FakeDirectory::returning(vec![]);- browse_catalog(&directory, Some(" linear "), Some("cursor-1"), Some(5))- .await- .unwrap();+ browse_catalog(+ &directory,+ &user(),+ Some(" linear "),+ Some("cursor-1"),+ Some(5),+ )+ .await+ .unwrap();let seen = directory.seen.lock().unwrap();let (search, cursor, limit) = seen[0].clone();@@ -88,7 +105,7 @@ async fn search_is_trimmed_and_forwarded() {async fn blank_search_browses_and_limit_is_clamped() {let directory = FakeDirectory::returning(vec![]);- browse_catalog(&directory, Some(" "), None, Some(9999))+ browse_catalog(&directory, &user(), Some(" "), None, Some(9999)).await.unwrap();diff --git a/crates/pipedream_mcp/src/domain/service/connect.rs b/crates/pipedream_mcp/src/domain/service/connect.rsindex c8ca21510f..ca94804fd0 100644--- a/crates/pipedream_mcp/src/domain/service/connect.rs+++ b/crates/pipedream_mcp/src/domain/service/connect.rs@@ -5,9 +5,14 @@//! [`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.+//!+//! Apps Macro Connect serves connect through Connect instead, when the+//! `macro-connect` rollout is on for the user: [`start_connect_session`]+//! picks the backend and [`complete_connect_connection`] records the+//! connection once Connect confirms it.-use crate::domain::models::{MacroUserIdStr, PipedreamConnection};-use crate::domain::ports::{ConnectionStore, ConnectorOverlays, PipedreamConnect};+use crate::domain::models::{ConnectApp, ConnectionProvider, MacroUserIdStr, PipedreamConnection};+use crate::domain::ports::{ConnectionStore, ConnectorOverlays, MacroConnect, PipedreamConnect};#[cfg(test)]mod test;@@ -92,6 +97,7 @@ where.unwrap_or(account.app_name),account_id: account.id,enabled: existing.as_ref().is_none_or(|r| r.enabled),+ provider: ConnectionProvider::Pipedream,};store.save(&record).await.map_err(anyhow::Error::from)?;@@ -161,32 +167,31 @@ where.map(Some)}-/// Remove a connected app, revoking its Pipedream account. Returns the-/// connection that was removed, or `None` when the app was not connected.+/// Remove a connected app, revoking its grant with whichever backend holds+/// it. Returns the connection that was removed, or `None` when the app was+/// not connected.///-/// The Pipedream deletion is best effort: failing to clean up remotely must+/// The remote 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)]+#[tracing::instrument(skip(store, backends), err)]pub async fn disconnect_mcp_server<S, P>(store: &S,- pipedream: &P,+ backends: &P,user_id: &MacroUserIdStr<'static>,app_slug: &str,) -> anyhow::Result<Option<PipedreamConnection>>whereS: ConnectionStore,- P: PipedreamConnect,+ P: PipedreamConnect + MacroConnect,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");+ if let Some(record) = &record {+ revoke(backends, record).await;}store@@ -196,3 +201,109 @@ whereOk(record)}++/// Best-effort removal of `record`'s grant from the backend holding it.+async fn revoke<P: PipedreamConnect + MacroConnect>(backends: &P, record: &PipedreamConnection) {+ let result = match record.provider {+ ConnectionProvider::Pipedream => backends.delete_account(&record.account_id).await,+ ConnectionProvider::Connect => {+ backends+ .delete_connection(&record.user_id, &record.account_id)+ .await+ }+ };+ if let Err(error) = result {+ tracing::warn!(+ error = ?error,+ account_id = %record.account_id,+ provider = record.provider.as_str(),+ "failed to delete remote connection"+ );+ }+}++/// The Connect app to connect `app_slug` through, or `None` when Connect does+/// not serve it.+///+/// Only for users on Connect alone (callers check+/// [`MacroConnect::connect_only`]), for whom Connect serves every app it+/// lists, overlaid or not, Granola included: nothing falls back to Pipedream.+#[tracing::instrument(skip(connect), err)]+pub async fn connect_app_for<C>(connect: &C, app_slug: &str) -> anyhow::Result<Option<ConnectApp>>+where+ C: MacroConnect,+{+ connect.app_for_slug(app_slug).await+}++/// Start connecting `app_slug` through Connect. Returns the URL for the+/// user's browser, or `None` when Connect does not serve the app.+#[tracing::instrument(skip(connect), err)]+pub async fn start_connect_session<C>(+ connect: &C,+ user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+) -> anyhow::Result<Option<String>>+where+ C: MacroConnect,+{+ let Some(app) = connect_app_for(connect, app_slug).await? else {+ return Ok(None);+ };+ connect+ .create_connect_session(user_id, &app)+ .await+ .map(Some)+}++/// Record a connection Connect holds for `user_id` to the app replacing+/// `app_slug`.+///+/// Nothing the browser reports is trusted: Connect itself must list an+/// active connection for this user before a record is written. A Pipedream+/// grant the record replaces is revoked, so only one backend holds the app.+#[tracing::instrument(skip(store, backends), err)]+pub async fn complete_connect_connection<S, P>(+ store: &S,+ backends: &P,+ user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ server_name: Option<&str>,+) -> Result<PipedreamConnection, PipedreamConnectError>+where+ S: ConnectionStore,+ P: PipedreamConnect + MacroConnect,+ anyhow::Error: From<S::Err>,+{+ let app = connect_app_for(backends, app_slug)+ .await?+ .ok_or(PipedreamConnectError::NotFound)?;+ if !backends.is_connected(user_id, &app.app_id).await? {+ return Err(PipedreamConnectError::NotFound);+ }++ let existing = store+ .load(user_id, app_slug)+ .await+ .map_err(anyhow::Error::from)?;+ let record = PipedreamConnection {+ user_id: user_id.clone(),+ app_slug: app.app_slug,+ server_name: server_name+ .map(str::to_owned)+ .or_else(|| existing.as_ref().map(|r| r.server_name.clone()))+ .unwrap_or(app.name),+ account_id: app.app_id,+ enabled: existing.as_ref().is_none_or(|r| r.enabled),+ provider: ConnectionProvider::Connect,+ };+ store.save(&record).await.map_err(anyhow::Error::from)?;++ if let Some(previous) = existing+ && previous.provider == ConnectionProvider::Pipedream+ {+ revoke(backends, &previous).await;+ }++ Ok(record)+}diff --git a/crates/pipedream_mcp/src/domain/service/connect/test.rs b/crates/pipedream_mcp/src/domain/service/connect/test.rsindex 74f6c7698f..a887388501 100644--- a/crates/pipedream_mcp/src/domain/service/connect/test.rs+++ b/crates/pipedream_mcp/src/domain/service/connect/test.rs@@ -68,6 +68,78 @@ impl ConnectionStore for FakeStore {struct FakePipedream {accounts: HashMap<String, PipedreamAccount>,deleted: Mutex<Vec<String>>,+ /// Connect apps by the Pipedream slug they replace.+ connect_apps: HashMap<String, ConnectApp>,+ /// `(user, app_id)` pairs Connect lists as connected.+ connect_connections: Mutex<Vec<(String, String)>>,+ connect_deleted: Mutex<Vec<(String, String)>>,+}++impl FakePipedream {+ fn with_connect_app(mut self, app_slug: &str, app_id: &str) -> Self {+ self.connect_apps.insert(+ app_slug.to_owned(),+ ConnectApp {+ app_id: app_id.to_owned(),+ app_slug: app_slug.to_owned(),+ name: "Linear".to_owned(),+ },+ );+ self+ }++ fn connected_on_connect(self, user_id: &str, app_id: &str) -> Self {+ self.connect_connections+ .lock()+ .unwrap()+ .push((user_id.to_owned(), app_id.to_owned()));+ self+ }+}++impl MacroConnect for FakePipedream {+ async fn connect_only(&self, _user_id: &MacroUserIdStr<'static>) -> bool {+ true+ }++ async fn app_for_slug(&self, app_slug: &str) -> anyhow::Result<Option<ConnectApp>> {+ Ok(self.connect_apps.get(app_slug).cloned())+ }++ async fn create_connect_session(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app: &ConnectApp,+ ) -> anyhow::Result<String> {+ Ok(format!(+ "https://connect.test/v1/connect/{}/{user_id}",+ app.app_id+ ))+ }++ async fn is_connected(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_id: &str,+ ) -> anyhow::Result<bool> {+ Ok(self+ .connect_connections+ .lock()+ .unwrap()+ .contains(&(user_id.to_string(), app_id.to_owned())))+ }++ async fn delete_connection(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_id: &str,+ ) -> anyhow::Result<()> {+ self.connect_deleted+ .lock()+ .unwrap()+ .push((user_id.to_string(), app_id.to_owned()));+ Ok(())+ }}impl PipedreamConnect for FakePipedream {@@ -243,6 +315,7 @@ async fn reconnecting_keeps_name_and_enabled_state_but_swaps_the_account() {server_name: "My Linear".into(),account_id: "apn_old".into(),enabled: false,+ provider: ConnectionProvider::Pipedream,}).await.unwrap();@@ -302,6 +375,7 @@ async fn disconnect_revokes_the_pipedream_account_and_deletes_the_row() {server_name: "Linear".into(),account_id: "apn_1".into(),enabled: true,+ provider: ConnectionProvider::Pipedream,}).await.unwrap();@@ -438,6 +512,7 @@ async fn recovery_does_not_report_the_already_stored_account_as_new() {server_name: "Linear".into(),account_id: "apn_1".into(),enabled: true,+ provider: ConnectionProvider::Pipedream,}).await.unwrap();@@ -490,3 +565,153 @@ async fn recovering_an_overlaid_app_is_refused_and_its_account_deleted() {assert_eq!(*pd.deleted.lock().unwrap(), vec!["apn_1".to_owned()]);assert!(store.records.lock().unwrap().is_empty(), "nothing stored");}++#[tokio::test]+async fn connect_session_starts_for_an_app_connect_serves() {+ let pd = FakePipedream::default().with_connect_app("linear", "linear");++ let url = start_connect_session(&pd, &user("macro|[email protected]"), "linear")+ .await+ .unwrap();++ assert_eq!(+ url.as_deref(),+ Some("https://connect.test/v1/connect/linear/macro|[email protected]")+ );+}++#[tokio::test]+async fn connect_serves_overlaid_apps_and_granola_and_nothing_it_lacks() {+ let pd = FakePipedream::default()+ .with_connect_app("sentry", "sentry")+ .with_connect_app("granola", "granola");+ let user = user("macro|[email protected]");++ for slug in ["sentry", "granola"] {+ let url = start_connect_session(&pd, &user, slug).await.unwrap();+ assert!(url.is_some_and(|url| url.contains(slug)), "{slug}");+ }+ assert_eq!(+ start_connect_session(&pd, &user, "notion").await.unwrap(),+ None+ );+}++#[tokio::test]+async fn completing_through_connect_stores_a_connect_record() {+ let store = FakeStore::default();+ let pd = FakePipedream::default()+ .with_connect_app("airtable_oauth", "airtable")+ .connected_on_connect("macro|[email protected]", "airtable");++ let record = complete_connect_connection(+ &store,+ &pd,+ &user("macro|[email protected]"),+ "airtable_oauth",+ None,+ )+ .await+ .unwrap();++ assert_eq!(record.app_slug, "airtable_oauth");+ assert_eq!(record.account_id, "airtable");+ assert_eq!(record.provider, ConnectionProvider::Connect);+ assert!(record.enabled);+ assert_eq!(+ store+ .load(&user("macro|[email protected]"), "airtable_oauth")+ .await+ .unwrap(),+ Some(record)+ );+}++#[tokio::test]+async fn completing_through_connect_before_connect_confirms_is_not_found() {+ let store = FakeStore::default();+ // Connected for someone else: the caller cannot claim it.+ let pd = FakePipedream::default()+ .with_connect_app("linear", "linear")+ .connected_on_connect("macro|[email protected]", "linear");++ let err = complete_connect_connection(+ &store,+ &pd,+ &user("macro|[email protected]"),+ "linear",+ None,+ )+ .await+ .unwrap_err();++ assert!(matches!(err, PipedreamConnectError::NotFound));+ assert!(store.records.lock().unwrap().is_empty());+}++#[tokio::test]+async fn completing_through_connect_revokes_the_pipedream_grant_it_replaces() {+ 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_1".into(),+ enabled: false,+ provider: ConnectionProvider::Pipedream,+ })+ .await+ .unwrap();+ let pd = FakePipedream::default()+ .with_connect_app("linear", "linear")+ .connected_on_connect("macro|[email protected]", "linear");++ let record = complete_connect_connection(+ &store,+ &pd,+ &user("macro|[email protected]"),+ "linear",+ None,+ )+ .await+ .unwrap();++ assert_eq!(record.server_name, "My Linear");+ assert!(!record.enabled);+ assert_eq!(record.provider, ConnectionProvider::Connect);+ assert_eq!(*pd.deleted.lock().unwrap(), vec!["apn_1".to_owned()]);+}++#[tokio::test]+async fn disconnecting_a_connect_app_deletes_it_from_connect() {+ let store = FakeStore::default();+ store+ .save(&PipedreamConnection {+ user_id: user("macro|[email protected]"),+ app_slug: "airtable_oauth".into(),+ server_name: "Airtable".into(),+ account_id: "airtable".into(),+ enabled: true,+ provider: ConnectionProvider::Connect,+ })+ .await+ .unwrap();+ let pd = FakePipedream::default();++ disconnect_mcp_server(+ &store,+ &pd,+ &user("macro|[email protected]"),+ "airtable_oauth",+ )+ .await+ .unwrap();++ assert_eq!(+ *pd.connect_deleted.lock().unwrap(),+ vec![("macro|[email protected]".to_owned(), "airtable".to_owned())]+ );+ assert!(pd.deleted.lock().unwrap().is_empty());+ assert!(store.records.lock().unwrap().is_empty());+}diff --git a/crates/pipedream_mcp/src/domain/service/discovery.rs b/crates/pipedream_mcp/src/domain/service/discovery.rsindex 1844fb0ec9..f931dfff22 100644--- a/crates/pipedream_mcp/src/domain/service/discovery.rs+++ b/crates/pipedream_mcp/src/domain/service/discovery.rs@@ -120,16 +120,21 @@ whereif query.trim().is_empty() {anyhow::bail!("Search for an app name, such as Linear");}- let page =- super::catalog::browse_catalog(directory.as_ref(), Some(query), None, Some(10))- .await?;+ let page = super::catalog::browse_catalog(+ directory.as_ref(),+ user_id,+ Some(query),+ None,+ Some(10),+ )+ .await?;Ok(DiscoveryResult::Search {apps: page.entries.into_iter().map(DiscoveredApp::from).collect(),more_results: page.next_cursor.is_some(),})}DiscoveryRequest::Inspect { app_slug } => {- let Some(app) = directory.retrieve(app_slug).await? else {+ let Some(app) = directory.retrieve(user_id, app_slug).await? else {anyhow::bail!("No connectable app has that slug; search the catalog first");};let connected = self.connected(user_id, &app.app_slug).await?;diff --git a/crates/pipedream_mcp/src/domain/service/discovery/test.rs b/crates/pipedream_mcp/src/domain/service/discovery/test.rsindex 8da8c09215..e66749d4cd 100644--- a/crates/pipedream_mcp/src/domain/service/discovery/test.rs+++ b/crates/pipedream_mcp/src/domain/service/discovery/test.rs@@ -21,6 +21,7 @@ fn entry() -> CatalogEntry {impl ConnectorDirectory for Directory {async fn search(&self,+ _user_id: &MacroUserIdStr<'static>,search: Option<&str>,_cursor: Option<&str>,limit: u32,@@ -32,7 +33,11 @@ impl ConnectorDirectory for Directory {next_cursor: Some("next".into()),})}- async fn retrieve(&self, slug: &str) -> anyhow::Result<Option<CatalogEntry>> {+ async fn retrieve(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ slug: &str,+ ) -> anyhow::Result<Option<CatalogEntry>> {Ok((slug == "linear").then(entry))}}@@ -115,6 +120,7 @@ impl ConnectionStore for Store {server_name: "Linear".into(),account_id: "account".into(),enabled,+ provider: crate::domain::models::ConnectionProvider::Pipedream,}))}}diff --git a/crates/pipedream_mcp/src/domain/service/mod.rs b/crates/pipedream_mcp/src/domain/service/mod.rsindex 6e37998dd9..38f4492aa6 100644--- a/crates/pipedream_mcp/src/domain/service/mod.rs+++ b/crates/pipedream_mcp/src/domain/service/mod.rs@@ -8,5 +8,8 @@ pub mod discovery;pub mod toolset;pub use catalog::browse_catalog;-pub use connect::{PipedreamConnectError, complete_pipedream_connection, disconnect_mcp_server};+pub use connect::{+ PipedreamConnectError, complete_connect_connection, complete_pipedream_connection,+ connect_app_for, disconnect_mcp_server, start_connect_session,+};pub use toolset::PipedreamToolSet;diff --git a/crates/pipedream_mcp/src/inbound/axum_router.rs b/crates/pipedream_mcp/src/inbound/axum_router.rsindex bdd5a1b9b1..b4ab151529 100644--- a/crates/pipedream_mcp/src/inbound/axum_router.rs+++ b/crates/pipedream_mcp/src/inbound/axum_router.rs@@ -1,11 +1,13 @@use crate::domain::{- models::{CatalogEntry, ConnectorOverlay, PipedreamConnection},- ports::{ConnectionStore, ConnectorDirectory, ConnectorOverlays, PipedreamConnect},+ models::{CatalogEntry, ConnectionProvider, ConnectorOverlay, PipedreamConnection},+ ports::{+ ConnectionStore, ConnectorDirectory, ConnectorOverlays, MacroConnect, PipedreamConnect,+ },service::{catalog::browse_catalog,connect::{- PipedreamConnectError, complete_pipedream_connection, disconnect_mcp_server,- recover_pipedream_connection,+ PipedreamConnectError, complete_connect_connection, complete_pipedream_connection,+ disconnect_mcp_server, recover_pipedream_connection, start_connect_session,},},};@@ -72,7 +74,7 @@ impl<S, P, Auth> FromRef<PipedreamRouterState<S, P, Auth>> for MacroAuthorizatioimpl<S, P, Auth> PipedreamRouterState<S, P, Auth>whereS: ConnectionStore,- P: PipedreamConnect + ConnectorDirectory,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,{/// Create a new router state from a server store, the Pipedream client@@ -116,6 +118,18 @@ where.as_ref().ok_or(PipedreamHandlerErr::PipedreamNotConfigured)}++ /// Whether `user_id` is on Macro Connect alone (see+ /// [`MacroConnect::connect_only`]).+ async fn connect_only(+ &self,+ user_id: ¯o_user_id::user_id::MacroUserIdStr<'static>,+ ) -> bool {+ match &self.pipedream {+ Some(backends) => backends.connect_only(user_id).await,+ None => false,+ }+ }}/// Authenticated MCP routes: connected-app CRUD, the Pipedream connect flow,@@ -125,7 +139,7 @@ pub fn pipedream_mcp_router<S, P, Auth, Global>() -> Router<Global>whereS: ConnectionStore + ConnectorOverlays,- P: PipedreamConnect + ConnectorDirectory,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,anyhow::Error: From<S::Err>,Global: Send + Sync,@@ -155,6 +169,10 @@ where"/pipedream/mcp/recover",post(recover_connection::<S, P, Auth>),)+ .route(+ "/pipedream/mcp/connect/complete",+ post(complete_connect::<S, P, Auth>),+ ).route("/pipedream/mcp/catalog",get(browse_catalog_handler::<S, P, Auth>),@@ -185,6 +203,39 @@ where})}+/// The public page Macro Connect sends the browser to after consent.+///+/// It records nothing: the page only tells the user to return to Macro and+/// closes itself. The app, polling the authenticated+/// `/pipedream/mcp/connect/complete`, records the connection once Connect+/// confirms it, so nothing in this unauthenticated request is trusted.+pub fn pipedream_connect_callback_router<Global>() -> Router<Global>+where+ Global: Send + Sync + Clone + 'static,+{+ Router::new().route("/pipedream/mcp/connect/callback", get(connect_callback))+}++/// Query Connect appends to the callback URL.+#[derive(Debug, Deserialize)]+pub struct ConnectCallbackQuery {+ /// `connected` or `error`.+ status: Option<String>,+}++#[tracing::instrument(skip_all, fields(status = query.status.as_deref()))]+async fn connect_callback(+ Query(query): Query<ConnectCallbackQuery>,+) -> axum::response::Html<&'static str> {+ axum::response::Html(match query.status.as_deref() {+ Some("connected") => CONNECT_CALLBACK_CONNECTED,+ _ => CONNECT_CALLBACK_FAILED,+ })+}++const CONNECT_CALLBACK_CONNECTED: &str = "<!doctype html><meta charset=utf-8><title>Connected</title><p>Connected. You can close this window and return to Macro.</p><script>window.close()</script>";+const CONNECT_CALLBACK_FAILED: &str = "<!doctype html><meta charset=utf-8><title>Not connected</title><p>The connection did not finish. Close this window and try again in Macro.</p>";+/// State for the public webhook route: the shared secret, nothing else.#[derive(Clone)]pub struct PipedreamWebhookState {@@ -271,15 +322,61 @@ pub struct PipedreamDeleteParams {app_slug: String,}-/// Response from creating a Pipedream Connect token.+/// Request body for starting a connect flow.+#[derive(Debug, Default, Deserialize, ToSchema)]+pub struct PipedreamTokenRequest {+ /// The app to connect, by Pipedream slug. With it, an app Macro Connect+ /// serves can answer with a Connect URL instead of a Pipedream token.+ #[serde(default)]+ app_slug: Option<String>,+}++/// Which backend a connection or connect flow uses.+#[derive(Clone, Copy, Debug, Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum PipedreamProviderResponse {+ /// Pipedream Connect.+ Pipedream,+ /// Macro Connect.+ Connect,+}++impl From<ConnectionProvider> for PipedreamProviderResponse {+ fn from(provider: ConnectionProvider) -> Self {+ match provider {+ ConnectionProvider::Pipedream => Self::Pipedream,+ ConnectionProvider::Connect => Self::Connect,+ }+ }+}++/// Response from starting a connect flow: a Pipedream Connect token, or for+/// `provider = connect` a Macro Connect URL.#[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,+ /// The backend this flow connects through.+ provider: PipedreamProviderResponse,+ /// Short-lived token to open the Pipedream Connect UI with. Pipedream only.+ token: Option<String>,+ /// RFC 3339 expiry of the token. Pipedream only.+ expires_at: Option<String>,/// Shareable link that opens the same connect flow in a browser tab.- connect_link_url: String,+ /// Pipedream only.+ connect_link_url: Option<String>,+ /// URL to open in a popup or browser tab for Macro Connect's consent+ /// flow; once it finishes, call `/pipedream/mcp/connect/complete`.+ /// Connect only.+ connect_url: Option<String>,+}++/// Request body for recording a finished Macro Connect flow.+#[derive(Debug, Deserialize, ToSchema)]+pub struct PipedreamConnectCompleteRequest {+ /// The app that was connected, by Pipedream slug.+ app_slug: String,+ /// Optional display name for the connector, as for completion.+ #[serde(default)]+ server_name: Option<String>,}/// Request body for completing a Pipedream connect flow.@@ -313,6 +410,8 @@ pub struct PipedreamConnectionResponse {server_name: String,/// Whether the connector is enabled for tool use.enabled: bool,+ /// The backend holding the grant.+ provider: PipedreamProviderResponse,}impl PipedreamConnectionResponse {@@ -321,6 +420,7 @@ impl PipedreamConnectionResponse {app_slug: record.app_slug.clone(),server_name: record.server_name.clone(),enabled: record.enabled,+ provider: record.provider.into(),}}}@@ -410,6 +510,9 @@ pub enum PipedreamHandlerErr {/// The app connects through its own MCP server, never Pipedream.#[error("{0}")]Overlaid(String),+ /// The user is on Macro Connect alone, which this request would bypass.+ #[error("{0}")]+ ConnectOnly(&'static str),/// An internal error occurred.#[error("{0}")]Internal(#[from] anyhow::Error),@@ -433,6 +536,7 @@ impl IntoResponse for PipedreamHandlerErr {PipedreamHandlerErr::NotFound => StatusCode::NOT_FOUND,PipedreamHandlerErr::PipedreamNotConfigured => StatusCode::NOT_IMPLEMENTED,PipedreamHandlerErr::Overlaid(_) => StatusCode::CONFLICT,+ PipedreamHandlerErr::ConnectOnly(_) => StatusCode::CONFLICT,PipedreamHandlerErr::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,};(@@ -466,7 +570,7 @@ pub async fn list_connections<S, P, Auth>() -> Result<Json<Vec<PipedreamConnectionResponse>>, PipedreamHandlerErr>whereS: ConnectionStore,- P: PipedreamConnect + ConnectorDirectory,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,anyhow::Error: From<S::Err>,{@@ -476,10 +580,14 @@ where.list(&user.macro_user_id).await.map_err(anyhow::Error::from)?;+ // Pipedream connections are unusable to a user on Connect alone; the+ // app shows as not connected until they reconnect it through Connect.+ let connect_only = state.connect_only(&user.macro_user_id).await;Ok(Json(records.iter()+ .filter(|record| !connect_only || record.provider == ConnectionProvider::Connect).map(PipedreamConnectionResponse::from_record).collect(),))@@ -507,7 +615,7 @@ pub async fn update_connection<S, P, Auth>() -> Result<Json<PipedreamConnectionResponse>, PipedreamHandlerErr>whereS: ConnectionStore,- P: PipedreamConnect + ConnectorDirectory,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,anyhow::Error: From<S::Err>,{@@ -556,7 +664,7 @@ pub async fn delete_connection<S, P, Auth>() -> Result<StatusCode, PipedreamHandlerErr>whereS: ConnectionStore,- P: PipedreamConnect + ConnectorDirectory,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,anyhow::Error: From<S::Err>,{@@ -582,6 +690,7 @@ wherepath = "/pipedream/mcp/token",tag = "pipedream-mcp",operation_id = "create_pipedream_mcp_token",+ request_body(content = Option<PipedreamTokenRequest>),responses((status = 200, body = PipedreamTokenResponse),(status = 401, body = String),@@ -589,33 +698,108 @@ where(status = 500, body = ErrorResponse),))]-/// Create a short-lived Pipedream Connect token for the authenticated user.+/// Start a connect flow 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.+/// By default, a short-lived Pipedream Connect token: the frontend opens+/// Pipedream's hosted Connect UI with it, and the user picks (or is+/// deep-linked into) an app and authorizes it there. When the body names an+/// app Macro Connect serves and the `macro-connect` rollout is on for the+/// user, a Connect URL instead.#[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>,+ body: Option<Json<PipedreamTokenRequest>>,) -> Result<Json<PipedreamTokenResponse>, PipedreamHandlerErr>where- S: ConnectionStore,- P: PipedreamConnect + ConnectorDirectory,+ S: ConnectionStore + ConnectorOverlays,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,{let user = &authorization.authorization.user;- let token = state- .pipedream()?+ let pipedream = state.pipedream()?;+ let app_slug = body.and_then(|Json(body)| body.app_slug);+ // A user on Connect alone gets a Connect URL or a 404, never a+ // Pipedream token.+ if state.connect_only(&user.macro_user_id).await {+ let app_slug = app_slug.ok_or(PipedreamHandlerErr::ConnectOnly(+ "name the app to connect through Macro Connect",+ ))?;+ let connect_url = start_connect_session(pipedream.as_ref(), &user.macro_user_id, &app_slug)+ .await?+ .ok_or(PipedreamHandlerErr::NotFound)?;+ return Ok(Json(PipedreamTokenResponse {+ provider: PipedreamProviderResponse::Connect,+ token: None,+ expires_at: None,+ connect_link_url: None,+ connect_url: Some(connect_url),+ }));+ }++ let token = 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,+ provider: PipedreamProviderResponse::Pipedream,+ token: Some(token.token),+ expires_at: Some(token.expires_at),+ connect_link_url: Some(token.connect_link_url),+ connect_url: None,}))}+#[utoipa::path(+ post,+ path = "/pipedream/mcp/connect/complete",+ tag = "pipedream-mcp",+ operation_id = "complete_pipedream_mcp_connect",+ request_body = PipedreamConnectCompleteRequest,+ responses(+ (status = 200, body = PipedreamConnectionResponse),+ (status = 401, body = String),+ (status = 404, body = ErrorResponse),+ (status = 501, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+/// Record an app the user connected through Macro Connect.+///+/// Answers 404 until Connect lists an active connection for this user and+/// app, so the frontend can poll it while the consent window is open.+#[tracing::instrument(skip_all, err, fields(connector.app_slug = %body.app_slug))]+pub async fn complete_connect<S, P, Auth>(+ State(state): State<PipedreamRouterState<S, P, Auth>>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ Json(body): Json<PipedreamConnectCompleteRequest>,+) -> Result<Json<PipedreamConnectionResponse>, PipedreamHandlerErr>+where+ S: ConnectionStore + ConnectorOverlays,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,+ Auth: MacroAuthorizationService,+ anyhow::Error: From<S::Err>,+{+ let user = &authorization.authorization.user;+ if !state.connect_only(&user.macro_user_id).await {+ return Err(PipedreamHandlerErr::NotFound);+ }+ let record = complete_connect_connection(+ state.store.as_ref(),+ state.pipedream()?.as_ref(),+ &user.macro_user_id,+ &body.app_slug,+ 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(post,path = "/pipedream/mcp/complete",@@ -644,11 +828,16 @@ pub async fn complete_connection<S, P, Auth>() -> Result<Json<PipedreamConnectionResponse>, PipedreamHandlerErr>whereS: ConnectionStore + ConnectorOverlays,- P: PipedreamConnect + ConnectorDirectory,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,anyhow::Error: From<S::Err>,{let user = &authorization.authorization.user;+ if state.connect_only(&user.macro_user_id).await {+ return Err(PipedreamHandlerErr::ConnectOnly(+ "this account connects apps through Macro Connect, not Pipedream",+ ));+ }let record = complete_pipedream_connection(state.store.as_ref(),state.store.as_ref(),@@ -695,11 +884,14 @@ pub async fn recover_connection<S, P, Auth>() -> Result<Json<PipedreamConnectionResponse>, PipedreamHandlerErr>whereS: ConnectionStore + ConnectorOverlays,- P: PipedreamConnect + ConnectorDirectory,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,anyhow::Error: From<S::Err>,{let user = &authorization.authorization.user;+ if state.connect_only(&user.macro_user_id).await {+ return Err(PipedreamHandlerErr::NotFound);+ }let record = recover_pipedream_connection(state.store.as_ref(),state.store.as_ref(),@@ -738,16 +930,18 @@ where#[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>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,Query(params): Query<PipedreamCatalogParams>,) -> Result<Json<PipedreamCatalogResponse>, PipedreamHandlerErr>whereS: ConnectionStore,- P: PipedreamConnect + ConnectorDirectory,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,{+ // Connect's catalog for a user on Connect alone (see the directory).let page = browse_catalog(state.pipedream()?.as_ref(),+ &authorization.authorization.user.macro_user_id,params.search.as_deref(),params.cursor.as_deref(),params.limit,@@ -778,13 +972,27 @@ where#[tracing::instrument(skip_all, err)]pub async fn list_overlays<S, P, Auth>(State(state): State<PipedreamRouterState<S, P, Auth>>,- _authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,+ authorization: MacroAuthorizationExtractor<Auth, UserOrInternal>,) -> Result<Json<Vec<PipedreamOverlayResponse>>, PipedreamHandlerErr>whereS: ConnectionStore + ConnectorOverlays,- P: PipedreamConnect + ConnectorDirectory,+ P: PipedreamConnect + ConnectorDirectory + MacroConnect,Auth: MacroAuthorizationService,{- let overlays = state.store.overlays().await?;+ let mut overlays = state.store.overlays().await?;+ // Connect serves its apps to a user on Connect alone, overlaid or not.+ if let Ok(backends) = state.pipedream()+ && backends+ .connect_only(&authorization.authorization.user.macro_user_id)+ .await+ {+ let mut kept = Vec::with_capacity(overlays.len());+ for overlay in overlays {+ if backends.app_for_slug(&overlay.app_slug).await?.is_none() {+ kept.push(overlay);+ }+ }+ overlays = kept;+ }Ok(Json(overlays.into_iter().map(Into::into).collect()))}diff --git a/crates/pipedream_mcp/src/inbound/mod.rs b/crates/pipedream_mcp/src/inbound/mod.rsindex 1a8b701e41..c4af82dacf 100644--- a/crates/pipedream_mcp/src/inbound/mod.rs+++ b/crates/pipedream_mcp/src/inbound/mod.rs@@ -3,4 +3,8 @@ pub mod axum_router;/// AI tool for discovering and inspecting unconnected apps.pub mod toolset;-pub use axum_router::{PipedreamRouterState, pipedream_mcp_router, pipedream_webhook_router};+pub use crate::domain::ports::ConnectRollout;+pub use axum_router::{+ PipedreamRouterState, pipedream_connect_callback_router, pipedream_mcp_router,+ pipedream_webhook_router,+};diff --git a/crates/pipedream_mcp/src/outbound/api.rs b/crates/pipedream_mcp/src/outbound/api.rsindex fd824839b3..15f5685635 100644--- a/crates/pipedream_mcp/src/outbound/api.rs+++ b/crates/pipedream_mcp/src/outbound/api.rs@@ -1,6 +1,6 @@use crate::domain::models::{- CatalogEntry, CatalogPage, ConnectToken, McpServer, PipedreamAccount, PipedreamConnection,- client_info,+ CatalogEntry, CatalogPage, ConnectToken, MacroUserIdStr, McpServer, PipedreamAccount,+ PipedreamConnection, client_info,};use crate::domain::ports::{ConnectedAppProxy, ConnectorDirectory, McpConnection, PipedreamConnect, ProxyResponse,@@ -267,9 +267,10 @@ impl PipedreamConnect for PipedreamClient {}}-impl ConnectorDirectory for PipedreamClient {+impl PipedreamClient {+ /// Pipedream's connectable app under `app_slug`, whoever asks.#[tracing::instrument(skip(self), err, fields(app = %app_slug))]- async fn retrieve(&self, app_slug: &str) -> anyhow::Result<Option<CatalogEntry>> {+ pub async fn retrieve_app(&self, app_slug: &str) -> anyhow::Result<Option<CatalogEntry>> {// The slug is interpolated into the path. Anything outside Pipedream's// app-slug charset is not an app, and is not requested.if !is_app_slug(app_slug) {@@ -298,10 +299,21 @@ impl ConnectorDirectory for PipedreamClient {let app: AppResponse = serde_json::from_value(app).context("parsing Pipedream app")?;Ok(connectable_catalog_entry(app_slug, app))}+}++impl ConnectorDirectory for PipedreamClient {+ async fn retrieve(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ ) -> anyhow::Result<Option<CatalogEntry>> {+ self.retrieve_app(app_slug).await+ }#[tracing::instrument(skip(self), err)]async fn search(&self,+ _user_id: &MacroUserIdStr<'static>,search: Option<&str>,cursor: Option<&str>,limit: u32,diff --git a/crates/pipedream_mcp/src/outbound/api/capabilities.rs b/crates/pipedream_mcp/src/outbound/api/capabilities.rsindex 5a06e12534..ffa26254fd 100644--- a/crates/pipedream_mcp/src/outbound/api/capabilities.rs+++ b/crates/pipedream_mcp/src/outbound/api/capabilities.rs@@ -24,6 +24,7 @@ impl ConnectorCapabilities for PipedreamClient {server_name: app_slug.to_owned(),account_id: String::new(),enabled: false,+ provider: crate::domain::models::ConnectionProvider::Pipedream,};tokio::time::timeout(Duration::from_secs(30), async {let client = self.connect(&record).await?;diff --git a/crates/pipedream_mcp/src/outbound/api/test.rs b/crates/pipedream_mcp/src/outbound/api/test.rsindex f14ee554a6..1cd2a61e2c 100644--- a/crates/pipedream_mcp/src/outbound/api/test.rs+++ b/crates/pipedream_mcp/src/outbound/api/test.rs@@ -95,6 +95,7 @@ async fn the_proxy_addresses_the_upstream_url_for_the_connected_account() {server_name: "Notion".into(),account_id: "apn_notion".into(),enabled: true,+ provider: crate::domain::models::ConnectionProvider::Pipedream,};let response = clientdiff --git a/crates/pipedream_mcp/src/outbound/connect.rs b/crates/pipedream_mcp/src/outbound/connect.rsnew file mode 100644index 0000000000..7b00c21bb4--- /dev/null+++ b/crates/pipedream_mcp/src/outbound/connect.rs@@ -0,0 +1,358 @@+use crate::domain::models::{+ CatalogEntry, CatalogPage, ConnectApp, MacroUserIdStr, McpServer, PipedreamConnection,+ client_info,+};+use crate::domain::ports::{+ ConnectedAppProxy, ConnectorCapabilities, ConnectorDirectory, MacroConnect, McpConnection,+ ProxyResponse,+};+use crate::domain::service::discovery::ConnectorTool;+use crate::outbound::api::{McpUpstream, McpUpstreamCall};+use anyhow::Context;+use connect_client::{ConnectClient, wire};+use reqwest::header::{HeaderMap, HeaderValue};+use rmcp::service::ServiceExt;+use rmcp::transport::StreamableHttpClientTransport;+use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;+use std::sync::Arc;+use std::time::{Duration, Instant};+use url::Url;++#[cfg(test)]+mod test;++/// How long a fetched Connect catalog is reused. The catalog changes only+/// when Connect deploys, and every connect click and tool listing reads it.+const CATALOG_TTL: Duration = Duration::from_secs(5 * 60);++/// Configuration for [`ConnectAdapter`].+#[derive(Clone)]+pub struct ConnectConfig {+ /// Connect API base URL, e.g. `https://connect-dev.macro.com`.+ pub api_url: String,+ /// Macro's customer key for the Connect API.+ pub customer_key: String,+ /// Where Connect sends the browser after consent.+ pub callback_url: Url,+}++impl std::fmt::Debug for ConnectConfig {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ formatter+ .debug_struct("ConnectConfig")+ .field("api_url", &self.api_url)+ .field("customer_key", &"[REDACTED]")+ .field("callback_url", &self.callback_url)+ .finish()+ }+}++/// Macro Connect behind this crate's ports, over `connect_client`.+///+/// Serves records with [`ConnectionProvider::Connect`]: tools through+/// Connect's MCP gateway (Connect attaches the vendor token), app API calls+/// with an exported access token, and the connect flow. Catalog apps are+/// addressed by the Pipedream slugs they replace.+///+/// [`ConnectionProvider::Connect`]: crate::domain::models::ConnectionProvider::Connect+pub struct ConnectAdapter {+ client: ConnectClient,+ api_url: Url,+ callback_url: Url,+ http: reqwest::Client,+ catalog: tokio::sync::Mutex<Option<(Instant, Arc<Vec<wire::CatalogEntry>>)>>,+}++impl ConnectAdapter {+ /// Build an adapter. Fails when the base URL is not an HTTP URL.+ pub fn new(config: ConnectConfig) -> anyhow::Result<Self> {+ let api_url = Url::parse(&config.api_url).context("Connect API URL is not a URL")?;+ let client = ConnectClient::new(&config.api_url, config.customer_key)+ .map_err(|error| anyhow::anyhow!("building Connect client: {error}"))?;+ let http = reqwest::Client::builder()+ .timeout(Duration::from_secs(30))+ .build()+ .context("building Connect proxy HTTP client")?;+ Ok(Self {+ client,+ api_url,+ callback_url: config.callback_url,+ http,+ catalog: tokio::sync::Mutex::new(None),+ })+ }++ async fn catalog(&self) -> anyhow::Result<Arc<Vec<wire::CatalogEntry>>> {+ let mut cached = self.catalog.lock().await;+ if let Some((fetched, apps)) = cached.as_ref()+ && fetched.elapsed() < CATALOG_TTL+ {+ return Ok(apps.clone());+ }+ let apps = Arc::new(+ self.client+ .catalog()+ .await+ .map_err(|error| anyhow::anyhow!("reading Connect catalog: {error}"))?,+ );+ *cached = Some((Instant::now(), apps.clone()));+ Ok(apps)+ }++ fn upstream_call(&self, record: &PipedreamConnection) -> McpUpstreamCall {+ let upstream = self+ .client+ .mcp_upstream(record.user_id.as_ref(), &record.account_id);+ McpUpstreamCall {+ url: upstream.url.clone(),+ bearer_token: upstream.bearer_token.clone(),+ headers: HeaderMap::new(),+ }+ }+}++/// The catalog entry Macro shows for a Connect app under `app_slug`. Icon+/// paths are relative to the Connect origin.+fn catalog_entry(app: &wire::CatalogEntry, app_slug: &str, api_url: &Url) -> CatalogEntry {+ CatalogEntry {+ app_slug: app_slug.to_owned(),+ display_name: app.name.clone(),+ description: Some(app.description.clone()),+ icon_url: app+ .icon_url+ .as_deref()+ .and_then(|path| api_url.join(path).ok())+ .map(String::from),+ categories: Vec::new(),+ }+}++impl MacroConnect for ConnectAdapter {+ /// The adapter is Connect itself.+ async fn connect_only(&self, _user_id: &MacroUserIdStr<'static>) -> bool {+ true+ }++ #[tracing::instrument(skip(self), err)]+ async fn app_for_slug(&self, app_slug: &str) -> anyhow::Result<Option<ConnectApp>> {+ Ok(self+ .catalog()+ .await?+ .iter()+ .find(|app| app.pipedream_app_slugs.iter().any(|slug| slug == app_slug))+ .map(|app| ConnectApp {+ app_id: app.id.clone(),+ app_slug: app_slug.to_owned(),+ name: app.name.clone(),+ }))+ }++ #[tracing::instrument(skip(self, app), err, fields(app_id = %app.app_id))]+ async fn create_connect_session(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app: &ConnectApp,+ ) -> anyhow::Result<String> {+ let mut redirect = self.callback_url.clone();+ redirect+ .query_pairs_mut()+ .append_pair("app_slug", &app.app_slug);+ let session = self+ .client+ .create_connect_session(user_id.as_ref(), &app.app_id, redirect.as_str())+ .await+ .map_err(|error| anyhow::anyhow!("creating Connect session: {error}"))?;+ Ok(session.connect_url)+ }++ #[tracing::instrument(skip(self), err)]+ async fn is_connected(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_id: &str,+ ) -> anyhow::Result<bool> {+ let connections = self+ .client+ .connections(user_id.as_ref())+ .await+ .map_err(|error| anyhow::anyhow!("listing Connect connections: {error}"))?;+ Ok(connections.iter().any(|connection| {+ connection.app_id == app_id+ && matches!(connection.status, wire::ConnectionStatus::Active)+ }))+ }++ #[tracing::instrument(skip(self), err)]+ async fn delete_connection(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_id: &str,+ ) -> anyhow::Result<()> {+ match self+ .client+ .delete_connection(user_id.as_ref(), app_id)+ .await+ {+ Ok(_) | Err(connect_client::Error::NotConnected) => Ok(()),+ Err(error) => Err(anyhow::anyhow!("deleting Connect connection: {error}")),+ }+ }+}++impl McpUpstream for ConnectAdapter {+ #[tracing::instrument(skip_all, err, fields(app = %record.app_slug, user_id = %record.user_id))]+ async fn upstream(&self, record: &PipedreamConnection) -> anyhow::Result<McpUpstreamCall> {+ Ok(self.upstream_call(record))+ }+}++impl McpConnection for ConnectAdapter {+ fn is_configured(&self) -> bool {+ true+ }++ #[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 upstream = self.upstream_call(record);+ let mut headers = HeaderMap::new();+ let mut auth = HeaderValue::from_str(&format!("Bearer {}", upstream.bearer_token))+ .context("invalid Connect customer key")?;+ auth.set_sensitive(true);+ headers.insert(reqwest::header::AUTHORIZATION, auth);++ let client = reqwest::Client::builder()+ .default_headers(headers)+ .build()+ .context("building Connect MCP HTTP client")?;+ let config = StreamableHttpClientTransportConfig::with_uri(upstream.url.as_str());+ let transport = StreamableHttpClientTransport::with_client(client, config);+ Ok(client_info().serve(transport).await?)+ }+}++impl ConnectorCapabilities for ConnectAdapter {+ /// Lists tools through the gateway, so only for a user who holds a+ /// Connect connection; anything else is an error the caller falls back+ /// from.+ #[tracing::instrument(skip_all, err)]+ async fn tools(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ ) -> anyhow::Result<Vec<ConnectorTool>> {+ let app = self+ .app_for_slug(app_slug)+ .await?+ .with_context(|| format!("Connect does not serve {app_slug}"))?;+ let record = PipedreamConnection {+ user_id: user_id.clone(),+ app_slug: app.app_slug,+ server_name: app.name,+ account_id: app.app_id,+ enabled: true,+ provider: crate::domain::models::ConnectionProvider::Connect,+ };+ tokio::time::timeout(Duration::from_secs(30), async {+ let client = self.connect(&record).await?;+ let tools = client.list_all_tools().await;+ let _ = client.cancel().await;+ Ok(tools?+ .into_iter()+ .map(|tool| ConnectorTool {+ name: tool.name.into_owned(),+ description: tool+ .description+ .map(|description| description.into_owned())+ .unwrap_or_default(),+ })+ .collect())+ })+ .await+ .map_err(|_| anyhow::anyhow!("Connector tool discovery timed out; retry later"))?+ }+}++impl ConnectorDirectory for ConnectAdapter {+ /// Connect's catalog under each app's first Pipedream slug, in catalog+ /// order. `cursor` is an offset.+ #[tracing::instrument(skip(self), err)]+ async fn search(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ search: Option<&str>,+ cursor: Option<&str>,+ limit: u32,+ ) -> anyhow::Result<CatalogPage> {+ let needle = search.map(str::to_lowercase);+ let matching: Vec<CatalogEntry> = self+ .catalog()+ .await?+ .iter()+ .filter(|app| {+ needle+ .as_deref()+ .is_none_or(|needle| app.name.to_lowercase().contains(needle))+ })+ .filter_map(|app| {+ let slug = app.pipedream_app_slugs.first()?;+ Some(catalog_entry(app, slug, &self.api_url))+ })+ .collect();+ let start: usize = cursor.map(str::parse).transpose()?.unwrap_or(0);+ let end = start.saturating_add(limit as usize).min(matching.len());+ Ok(CatalogPage {+ entries: matching.get(start..end).unwrap_or_default().to_vec(),+ next_cursor: (end < matching.len()).then(|| end.to_string()),+ })+ }++ #[tracing::instrument(skip(self), err)]+ async fn retrieve(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ ) -> anyhow::Result<Option<CatalogEntry>> {+ Ok(self+ .catalog()+ .await?+ .iter()+ .find(|app| app.pipedream_app_slugs.iter().any(|slug| slug == app_slug))+ .map(|app| catalog_entry(app, app_slug, &self.api_url)))+ }+}++impl ConnectedAppProxy for ConnectAdapter {+ /// Calls the app's API directly with the user's exported access token.+ #[tracing::instrument(skip_all, err, fields(app = %connection.app_slug, user_id = %connection.user_id, method = ?method))]+ async fn proxy(+ &self,+ connection: &PipedreamConnection,+ method: http::Method,+ url: &str,+ headers: &http::HeaderMap,+ body: Option<&serde_json::Value>,+ ) -> anyhow::Result<ProxyResponse> {+ let token = self+ .client+ .access_token(connection.user_id.as_ref(), &connection.account_id)+ .await+ .map_err(|error| anyhow::anyhow!("exporting Connect access token: {error}"))?;+ let mut request = self+ .http+ .request(method, url)+ .headers(headers.clone())+ .bearer_auth(&token.access_token);+ if let Some(body) = body {+ request = request.json(body);+ }+ let response = request.send().await.context("calling connected app")?;+ Ok(ProxyResponse {+ status: response.status(),+ headers: response.headers().clone(),+ body: response+ .text()+ .await+ .context("reading connected app response")?,+ })+ }+}diff --git a/crates/pipedream_mcp/src/outbound/connect/test.rs b/crates/pipedream_mcp/src/outbound/connect/test.rsnew file mode 100644index 0000000000..b3b6a78f82--- /dev/null+++ b/crates/pipedream_mcp/src/outbound/connect/test.rs@@ -0,0 +1,287 @@+use super::*;+use crate::domain::models::ConnectionProvider;+use axum::{+ Json, Router,+ extract::{Path, State},+ http::{HeaderMap as AxumHeaders, StatusCode},+ response::IntoResponse,+ routing::post,+};+use serde_json::{Value, json};+use std::sync::Mutex;+use wiremock::matchers::{body_json, header, method, path, query_param};+use wiremock::{Mock, MockServer, ResponseTemplate};++const KEY: &str = "ck_test_macro";++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email("[email protected]").unwrap()+}++fn adapter(base: &str) -> ConnectAdapter {+ ConnectAdapter::new(ConnectConfig {+ api_url: base.to_owned(),+ customer_key: KEY.to_owned(),+ callback_url: Url::parse("https://cognition.test/pipedream/mcp/connect/callback").unwrap(),+ })+ .unwrap()+}++fn record(app_slug: &str, app_id: &str) -> PipedreamConnection {+ PipedreamConnection {+ user_id: user(),+ app_slug: app_slug.to_owned(),+ server_name: "Airtable".to_owned(),+ account_id: app_id.to_owned(),+ enabled: true,+ provider: ConnectionProvider::Connect,+ }+}++async fn mount_catalog(server: &MockServer) {+ Mock::given(method("GET"))+ .and(path("/v1/catalog"))+ .and(header("authorization", format!("Bearer {KEY}").as_str()))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!([+ {+ "id": "airtable", "name": "Airtable", "description": "Bases and records",+ "access": ["mcp"], "mcp_url": "https://mcp.airtable.com/mcp",+ "icon_url": "/v1/catalog/airtable/icon.svg",+ "oauth_client": "managed_oauth_app",+ "pipedream_app_slugs": ["airtable_oauth"]+ },+ {+ "id": "slack", "name": "Slack", "description": "Messages",+ "access": ["mcp"], "mcp_url": "https://mcp.slack.com/mcp", "icon_url": null,+ "pipedream_app_slugs": ["slack", "slack_v2"]+ }+ ])))+ .expect(1)+ .mount(server)+ .await;+}++#[tokio::test]+async fn maps_pipedream_slugs_to_connect_apps_from_one_cached_catalog() {+ let server = MockServer::start().await;+ mount_catalog(&server).await;+ let connect = adapter(&server.uri());++ let airtable = connect+ .app_for_slug("airtable_oauth")+ .await+ .unwrap()+ .unwrap();+ assert_eq!(airtable.app_id, "airtable");+ assert_eq!(airtable.app_slug, "airtable_oauth");+ assert_eq!(airtable.name, "Airtable");+ let slack = connect.app_for_slug("slack_v2").await.unwrap().unwrap();+ assert_eq!(+ (slack.app_id.as_str(), slack.app_slug.as_str()),+ ("slack", "slack_v2")+ );+ assert_eq!(connect.app_for_slug("airtable").await.unwrap(), None);++ let entry = connect+ .retrieve(&user(), "airtable_oauth")+ .await+ .unwrap()+ .unwrap();+ assert_eq!(+ entry.icon_url.as_deref(),+ Some(format!("{}/v1/catalog/airtable/icon.svg", server.uri()).as_str())+ );+ let page = connect+ .search(&user(), Some("sla"), None, 10)+ .await+ .unwrap();+ assert_eq!(page.entries.len(), 1);+ assert_eq!(page.entries[0].app_slug, "slack");+ // `expect(1)` on the catalog mock checks the cache on drop.+}++#[tokio::test]+async fn connect_session_redirects_back_with_the_app_slug() {+ let server = MockServer::start().await;+ Mock::given(method("POST"))+ .and(path("/v1/connect-sessions"))+ .and(body_json(json!({+ "external_user_id": "macro|[email protected]",+ "app_id": "airtable",+ "redirect_url": "https://cognition.test/pipedream/mcp/connect/callback?app_slug=airtable_oauth"+ })))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!({+ "connect_url": "https://connect.test/v1/connect/tok",+ "expires_at": "2099-01-01T00:00:00Z"+ })))+ .expect(1)+ .mount(&server)+ .await;++ let url = adapter(&server.uri())+ .create_connect_session(+ &user(),+ &ConnectApp {+ app_id: "airtable".into(),+ app_slug: "airtable_oauth".into(),+ name: "Airtable".into(),+ },+ )+ .await+ .unwrap();++ assert_eq!(url, "https://connect.test/v1/connect/tok");+}++#[tokio::test]+async fn only_an_active_connection_to_the_app_counts_as_connected() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path("/v1/users/macro|[email protected]/connections"))+ .respond_with(ResponseTemplate::new(200).set_body_json(json!([+ {"appId": "airtable", "status": "needs_reauth", "scopes": [], "createdAt": "2026-11-03T00:00:00Z"},+ {"appId": "linear", "status": "active", "scopes": [], "createdAt": "2026-11-03T00:00:00Z"}+ ])))+ .mount(&server)+ .await;+ let connect = adapter(&server.uri());++ assert!(connect.is_connected(&user(), "linear").await.unwrap());+ assert!(!connect.is_connected(&user(), "airtable").await.unwrap());+ assert!(!connect.is_connected(&user(), "notion").await.unwrap());+}++#[tokio::test]+async fn deleting_tolerates_a_connection_connect_already_dropped() {+ let server = MockServer::start().await;+ Mock::given(method("DELETE"))+ .and(path(+ "/v1/users/macro|[email protected]/connections/airtable",+ ))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(json!({"vendorGrantRevoked": false})),+ )+ .expect(1)+ .mount(&server)+ .await;+ Mock::given(method("DELETE"))+ .and(path(+ "/v1/users/macro|[email protected]/connections/linear",+ ))+ .respond_with(ResponseTemplate::new(404).set_body_json(json!({"error": "not_found"})))+ .mount(&server)+ .await;+ let connect = adapter(&server.uri());++ connect+ .delete_connection(&user(), "airtable")+ .await+ .unwrap();+ connect.delete_connection(&user(), "linear").await.unwrap();+}++#[tokio::test]+async fn upstream_is_the_gateway_with_the_customer_key() {+ let connect = adapter("https://connect.test");++ let call = connect+ .upstream(&record("airtable_oauth", "airtable"))+ .await+ .unwrap();++ assert_eq!(+ call.url.as_str(),+ "https://connect.test/v1/users/macro|[email protected]/mcp/airtable"+ );+ assert_eq!(call.bearer_token, KEY);+ assert!(call.headers.is_empty());+}++#[tokio::test]+async fn proxy_calls_the_app_with_the_exported_token() {+ let server = MockServer::start().await;+ Mock::given(method("GET"))+ .and(path(+ "/v1/users/macro|[email protected]/connections/airtable/token",+ ))+ .respond_with(+ ResponseTemplate::new(200).set_body_json(json!({"accessToken": "vendor_token"})),+ )+ .mount(&server)+ .await;+ Mock::given(method("POST"))+ .and(path("/app/search"))+ .and(header("authorization", "Bearer vendor_token"))+ .and(header("notion-version", "2022-06-28"))+ .and(query_param("q", "x"))+ .and(body_json(json!({"query": "roadmap"})))+ .respond_with(ResponseTemplate::new(429).insert_header("retry-after", "3"))+ .mount(&server)+ .await;+ let mut headers = http::HeaderMap::new();+ headers.insert("notion-version", "2022-06-28".parse().unwrap());++ let response = adapter(&server.uri())+ .proxy(+ &record("airtable_oauth", "airtable"),+ http::Method::POST,+ &format!("{}/app/search?q=x", server.uri()),+ &headers,+ Some(&json!({"query": "roadmap"})),+ )+ .await+ .unwrap();++ assert_eq!(response.status, http::StatusCode::TOO_MANY_REQUESTS);+ assert_eq!(response.retry_after(), Some(Duration::from_secs(3)));+}++async fn gateway(+ State(calls): State<Arc<Mutex<Vec<String>>>>,+ Path((user_id, app_id)): Path<(String, String)>,+ headers: AxumHeaders,+ Json(body): Json<Value>,+) -> axum::response::Response {+ assert_eq!(headers["authorization"], format!("Bearer {KEY}"));+ assert_eq!(user_id, "macro|[email protected]");+ assert_eq!(app_id, "airtable");+ let method = body["method"].as_str().unwrap().to_owned();+ calls.lock().unwrap().push(method.clone());+ let result = match method.as_str() {+ "initialize" => {+ json!({"protocolVersion":"2025-03-26","capabilities":{"tools":{}},"serverInfo":{"name":"fixture","version":"1"}})+ }+ "notifications/initialized" => return StatusCode::ACCEPTED.into_response(),+ "tools/list" => {+ json!({"tools":[{"name":"list_records","description":"List records","inputSchema":{"type":"object","properties":{}}}]})+ }+ other => panic!("unexpected MCP method {other}"),+ };+ Json(json!({"jsonrpc":"2.0","id":body["id"],"result":result})).into_response()+}++#[tokio::test]+async fn connect_backed_upstream_speaks_mcp_through_the_gateway() {+ let calls = Arc::new(Mutex::new(Vec::new()));+ let app = Router::new()+ .route("/v1/users/{user_id}/mcp/{app_id}", post(gateway))+ .with_state(calls.clone());+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });++ let client = adapter(&format!("http://{address}"))+ .connect(&record("airtable_oauth", "airtable"))+ .await+ .unwrap();+ let tools = client.list_all_tools().await.unwrap();+ let _ = client.cancel().await;++ assert_eq!(tools.len(), 1);+ assert_eq!(tools[0].name, "list_records");+ assert_eq!(+ *calls.lock().unwrap(),+ ["initialize", "notifications/initialized", "tools/list"]+ );+ server.abort();+}diff --git a/crates/pipedream_mcp/src/outbound/dispatch.rs b/crates/pipedream_mcp/src/outbound/dispatch.rsnew file mode 100644index 0000000000..72d55e4817--- /dev/null+++ b/crates/pipedream_mcp/src/outbound/dispatch.rs@@ -0,0 +1,254 @@+use crate::domain::models::{+ CatalogEntry, CatalogPage, ConnectApp, ConnectToken, ConnectionProvider, MacroUserIdStr,+ McpServer, PipedreamAccount, PipedreamConnection,+};+use crate::domain::ports::{+ ConnectRollout, ConnectedAppProxy, ConnectorCapabilities, ConnectorDirectory, MacroConnect,+ McpConnection, PipedreamConnect, ProxyResponse,+};+use crate::domain::service::discovery::ConnectorTool;+use crate::outbound::api::{McpUpstream, McpUpstreamCall, PipedreamClient};+use crate::outbound::connect::ConnectAdapter;+use std::sync::Arc;++#[cfg(test)]+mod test;++/// Every connector backend behind one set of ports: Pipedream, plus Macro+/// Connect when configured.+///+/// A user the `macro-connect` rollout is on for is on Connect alone+/// ([`MacroConnect::connect_only`]): directory, tool listings, and every+/// stored connection go through Connect, and a Pipedream connection they+/// still hold is refused until they reconnect the app through Connect.+/// Nothing falls back to Pipedream. Everyone else stays on Pipedream, except+/// that a stored Connect connection always reaches Connect.+pub struct ConnectorBackends<P = PipedreamClient, C = ConnectAdapter> {+ pipedream: Arc<P>,+ connect: Option<Arc<C>>,+ rollout: Option<ConnectRollout>,+}++impl<P, C> ConnectorBackends<P, C> {+ /// Pipedream alone, or with Connect when `connect` is set. Nobody is on+ /// Connect alone until [`with_rollout`](Self::with_rollout).+ pub fn new(pipedream: Arc<P>, connect: Option<Arc<C>>) -> Self {+ Self {+ pipedream,+ connect,+ rollout: None,+ }+ }++ /// Put users `rollout` answers `true` for on Connect alone.+ pub fn with_rollout(mut self, rollout: ConnectRollout) -> Self {+ self.rollout = Some(rollout);+ self+ }++ /// The Pipedream backend.+ pub fn pipedream(&self) -> &Arc<P> {+ &self.pipedream+ }++ /// Connect, when `user_id` is on Connect alone.+ async fn connect_for_user(&self, user_id: &MacroUserIdStr<'static>) -> Option<&C> {+ let (Some(connect), Some(rollout)) = (&self.connect, &self.rollout) else {+ return None;+ };+ rollout(user_id.clone()).await.then_some(connect.as_ref())+ }++ /// The backend `record` names. A Pipedream record of a user on Connect+ /// alone is refused rather than used.+ async fn backend_for(&self, record: &PipedreamConnection) -> anyhow::Result<Backend<'_, P, C>> {+ match record.provider {+ ConnectionProvider::Connect => self+ .connect+ .as_deref()+ .map(Backend::Connect)+ .ok_or_else(|| {+ anyhow::anyhow!(+ "{} is connected through Macro Connect, which is not configured",+ record.app_slug+ )+ }),+ ConnectionProvider::Pipedream => {+ if self.connect_for_user(&record.user_id).await.is_some() {+ anyhow::bail!(+ "{} is connected through Pipedream; reconnect it through Macro Connect",+ record.app_slug+ );+ }+ Ok(Backend::Pipedream(&self.pipedream))+ }+ }+ }+}++enum Backend<'a, P, C> {+ Pipedream(&'a P),+ Connect(&'a C),+}++impl<P: McpConnection, C: McpConnection> McpConnection for ConnectorBackends<P, C> {+ fn is_configured(&self) -> bool {+ self.pipedream.is_configured()+ }++ async fn connect(&self, record: &PipedreamConnection) -> anyhow::Result<McpServer> {+ match self.backend_for(record).await? {+ Backend::Pipedream(pipedream) => pipedream.connect(record).await,+ Backend::Connect(connect) => connect.connect(record).await,+ }+ }+}++impl<P: McpUpstream, C: McpUpstream> McpUpstream for ConnectorBackends<P, C> {+ async fn upstream(&self, record: &PipedreamConnection) -> anyhow::Result<McpUpstreamCall> {+ match self.backend_for(record).await? {+ Backend::Pipedream(pipedream) => pipedream.upstream(record).await,+ Backend::Connect(connect) => connect.upstream(record).await,+ }+ }+}++impl<P: ConnectedAppProxy, C: ConnectedAppProxy> ConnectedAppProxy for ConnectorBackends<P, C> {+ async fn proxy(+ &self,+ connection: &PipedreamConnection,+ method: http::Method,+ url: &str,+ headers: &http::HeaderMap,+ body: Option<&serde_json::Value>,+ ) -> anyhow::Result<ProxyResponse> {+ match self.backend_for(connection).await? {+ Backend::Pipedream(pipedream) => {+ pipedream+ .proxy(connection, method, url, headers, body)+ .await+ }+ Backend::Connect(connect) => {+ connect.proxy(connection, method, url, headers, body).await+ }+ }+ }+}++/// Pipedream's own account API, for users still on Pipedream; callers check+/// [`MacroConnect::connect_only`] first.+impl<P: PipedreamConnect, C: Send + Sync + 'static> PipedreamConnect for ConnectorBackends<P, C> {+ async fn create_connect_token(&self, external_user_id: &str) -> anyhow::Result<ConnectToken> {+ self.pipedream.create_connect_token(external_user_id).await+ }++ async fn get_account(&self, account_id: &str) -> anyhow::Result<Option<PipedreamAccount>> {+ self.pipedream.get_account(account_id).await+ }++ async fn list_accounts(+ &self,+ external_user_id: &str,+ app_slug: &str,+ ) -> anyhow::Result<Vec<PipedreamAccount>> {+ self.pipedream+ .list_accounts(external_user_id, app_slug)+ .await+ }++ async fn delete_account(&self, account_id: &str) -> anyhow::Result<()> {+ self.pipedream.delete_account(account_id).await+ }+}++impl<P: ConnectorDirectory, C: ConnectorDirectory> ConnectorDirectory for ConnectorBackends<P, C> {+ /// Connect's catalog for a user on Connect alone, else Pipedream's+ /// directory.+ async fn search(+ &self,+ user_id: &MacroUserIdStr<'static>,+ search: Option<&str>,+ cursor: Option<&str>,+ limit: u32,+ ) -> anyhow::Result<CatalogPage> {+ match self.connect_for_user(user_id).await {+ Some(connect) => connect.search(user_id, search, cursor, limit).await,+ None => self.pipedream.search(user_id, search, cursor, limit).await,+ }+ }++ /// From the same directory as [`search`](Self::search).+ async fn retrieve(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ ) -> anyhow::Result<Option<CatalogEntry>> {+ match self.connect_for_user(user_id).await {+ Some(connect) => connect.retrieve(user_id, app_slug).await,+ None => self.pipedream.retrieve(user_id, app_slug).await,+ }+ }+}++impl<P: ConnectorCapabilities, C: ConnectorCapabilities> ConnectorCapabilities+ for ConnectorBackends<P, C>+{+ /// Connect's gateway listing for a user on Connect alone (which needs+ /// their Connect connection), else Pipedream's, which needs none.+ async fn tools(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ ) -> anyhow::Result<Vec<ConnectorTool>> {+ match self.connect_for_user(user_id).await {+ Some(connect) => connect.tools(user_id, app_slug).await,+ None => self.pipedream.tools(user_id, app_slug).await,+ }+ }+}++impl<P: Send + Sync + 'static, C: MacroConnect> MacroConnect for ConnectorBackends<P, C> {+ async fn connect_only(&self, user_id: &MacroUserIdStr<'static>) -> bool {+ self.connect_for_user(user_id).await.is_some()+ }++ async fn app_for_slug(&self, app_slug: &str) -> anyhow::Result<Option<ConnectApp>> {+ match &self.connect {+ Some(connect) => connect.app_for_slug(app_slug).await,+ None => Ok(None),+ }+ }++ async fn create_connect_session(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app: &ConnectApp,+ ) -> anyhow::Result<String> {+ match &self.connect {+ Some(connect) => connect.create_connect_session(user_id, app).await,+ None => anyhow::bail!("Macro Connect is not configured"),+ }+ }++ async fn is_connected(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_id: &str,+ ) -> anyhow::Result<bool> {+ match &self.connect {+ Some(connect) => connect.is_connected(user_id, app_id).await,+ None => Ok(false),+ }+ }++ async fn delete_connection(+ &self,+ user_id: &MacroUserIdStr<'static>,+ app_id: &str,+ ) -> anyhow::Result<()> {+ match &self.connect {+ Some(connect) => connect.delete_connection(user_id, app_id).await,+ None => anyhow::bail!("Macro Connect is not configured"),+ }+ }+}diff --git a/crates/pipedream_mcp/src/outbound/dispatch/test.rs b/crates/pipedream_mcp/src/outbound/dispatch/test.rsnew file mode 100644index 0000000000..5e03c1f5a3--- /dev/null+++ b/crates/pipedream_mcp/src/outbound/dispatch/test.rs@@ -0,0 +1,273 @@+use super::*;+use reqwest::header::HeaderMap;+use url::Url;++/// One backend: answers with its own name, and knows `apps` by slug.+struct Fake {+ name: &'static str,+ apps: &'static [&'static str],+ /// Whether the caller holds a connection, for gateway tool listings.+ connected: bool,+}++const PIPEDREAM: Fake = Fake {+ name: "pipedream",+ apps: &["linear", "notion"],+ connected: false,+};++fn connect(connected: bool) -> Fake {+ Fake {+ name: "connect",+ apps: &["linear", "airtable_oauth"],+ connected,+ }+}++fn backends(connect: Option<Fake>) -> ConnectorBackends<Fake, Fake> {+ ConnectorBackends::new(Arc::new(PIPEDREAM), connect.map(Arc::new))+}++/// Pipedream and Connect, with the rollout answering `on` for everyone.+fn rolled_out(on: bool) -> ConnectorBackends<Fake, Fake> {+ backends(Some(connect(true))).with_rollout(Arc::new(move |_| Box::pin(async move { on })))+}++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::try_from_email("[email protected]").unwrap()+}++fn record(provider: ConnectionProvider) -> PipedreamConnection {+ PipedreamConnection {+ user_id: user(),+ app_slug: "linear".into(),+ server_name: "Linear".into(),+ account_id: "id".into(),+ enabled: true,+ provider,+ }+}++impl McpUpstream for Fake {+ async fn upstream(&self, _record: &PipedreamConnection) -> anyhow::Result<McpUpstreamCall> {+ Ok(McpUpstreamCall {+ url: Url::parse(&format!("https://{}.test/mcp", self.name)).unwrap(),+ bearer_token: self.name.into(),+ headers: HeaderMap::new(),+ })+ }+}++impl ConnectorCapabilities for Fake {+ async fn tools(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ ) -> anyhow::Result<Vec<ConnectorTool>> {+ if self.name == "connect" && !self.connected {+ anyhow::bail!("not connected");+ }+ Ok(vec![ConnectorTool {+ name: format!("{}_{app_slug}", self.name),+ description: String::new(),+ }])+ }+}++impl ConnectorDirectory for Fake {+ async fn search(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ _search: Option<&str>,+ _cursor: Option<&str>,+ _limit: u32,+ ) -> anyhow::Result<CatalogPage> {+ Ok(CatalogPage {+ entries: vec![CatalogEntry {+ app_slug: self.name.to_owned(),+ display_name: self.name.to_owned(),+ description: None,+ icon_url: None,+ categories: Vec::new(),+ }],+ next_cursor: None,+ })+ }++ async fn retrieve(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ app_slug: &str,+ ) -> anyhow::Result<Option<CatalogEntry>> {+ Ok(self.apps.contains(&app_slug).then(|| CatalogEntry {+ app_slug: app_slug.to_owned(),+ display_name: self.name.to_owned(),+ description: None,+ icon_url: None,+ categories: Vec::new(),+ }))+ }+}++impl MacroConnect for Fake {+ async fn connect_only(&self, _user_id: &MacroUserIdStr<'static>) -> bool {+ self.name == "connect"+ }++ async fn app_for_slug(&self, app_slug: &str) -> anyhow::Result<Option<ConnectApp>> {+ Ok(self.apps.contains(&app_slug).then(|| ConnectApp {+ app_id: app_slug.to_owned(),+ app_slug: app_slug.to_owned(),+ name: app_slug.to_owned(),+ }))+ }++ async fn create_connect_session(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ _app: &ConnectApp,+ ) -> anyhow::Result<String> {+ Ok(format!("https://{}.test/session", self.name))+ }++ async fn is_connected(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ _app_id: &str,+ ) -> anyhow::Result<bool> {+ Ok(self.connected)+ }++ async fn delete_connection(+ &self,+ _user_id: &MacroUserIdStr<'static>,+ _app_id: &str,+ ) -> anyhow::Result<()> {+ Ok(())+ }+}++#[tokio::test]+async fn each_record_reaches_the_backend_holding_its_grant() {+ let backends = backends(Some(connect(true)));++ let pipedream = backends+ .upstream(&record(ConnectionProvider::Pipedream))+ .await+ .unwrap();+ let connect = backends+ .upstream(&record(ConnectionProvider::Connect))+ .await+ .unwrap();++ assert_eq!(pipedream.bearer_token, "pipedream");+ assert_eq!(connect.bearer_token, "connect");+}++#[tokio::test]+async fn a_connect_record_without_connect_configured_is_an_error() {+ let backends = backends(None);++ let error = backends+ .upstream(&record(ConnectionProvider::Connect))+ .await+ .unwrap_err();++ assert!(error.to_string().contains("not configured"), "{error}");+}++#[tokio::test]+async fn a_user_on_connect_alone_never_reaches_pipedream() {+ let user = user();+ let backends = rolled_out(true);++ assert!(backends.connect_only(&user).await);+ assert_eq!(+ backends+ .search(&user, None, None, 10)+ .await+ .unwrap()+ .entries[0]+ .app_slug,+ "connect"+ );+ assert_eq!(+ backends+ .retrieve(&user, "airtable_oauth")+ .await+ .unwrap()+ .unwrap()+ .display_name,+ "connect"+ );+ // Pipedream serves Notion; Connect does not, and nothing falls back.+ assert_eq!(backends.retrieve(&user, "notion").await.unwrap(), None);+ assert_eq!(+ backends.tools(&user, "linear").await.unwrap()[0].name,+ "connect_linear"+ );+ let error = backends+ .upstream(&record(ConnectionProvider::Pipedream))+ .await+ .unwrap_err();+ assert!(+ error+ .to_string()+ .contains("reconnect it through Macro Connect"),+ "{error}"+ );+ assert_eq!(+ backends+ .upstream(&record(ConnectionProvider::Connect))+ .await+ .unwrap()+ .bearer_token,+ "connect"+ );+}++#[tokio::test]+async fn with_the_rollout_off_everything_stays_on_pipedream() {+ let user = user();++ for backends in [+ rolled_out(false),+ backends(Some(connect(true))),+ backends(None),+ ] {+ assert!(!backends.connect_only(&user).await);+ assert_eq!(+ backends+ .search(&user, None, None, 10)+ .await+ .unwrap()+ .entries[0]+ .app_slug,+ "pipedream"+ );+ assert_eq!(+ backends.tools(&user, "linear").await.unwrap()[0].name,+ "pipedream_linear"+ );+ assert_eq!(+ backends.retrieve(&user, "airtable_oauth").await.unwrap(),+ None+ );+ assert_eq!(+ backends+ .upstream(&record(ConnectionProvider::Pipedream))+ .await+ .unwrap()+ .bearer_token,+ "pipedream"+ );+ }+}++#[tokio::test]+async fn without_connect_no_app_routes_through_it() {+ let backends = backends(None);++ assert_eq!(backends.app_for_slug("linear").await.unwrap(), None);+ assert!(!backends.is_connected(&user(), "linear").await.unwrap());+}diff --git a/crates/pipedream_mcp/src/outbound/mod.rs b/crates/pipedream_mcp/src/outbound/mod.rsindex 5c7a38b8e7..bc8981a316 100644--- a/crates/pipedream_mcp/src/outbound/mod.rs+++ b/crates/pipedream_mcp/src/outbound/mod.rs@@ -1,4 +1,9 @@/// HTTP adapter for the Pipedream API, the app directory, and the remote MCP server.pub mod api;+/// Macro Connect adapter over `connect_client`: the gateway, token export,+/// catalog, and connect flow.+pub mod connect;+/// One adapter over both backends, dispatching per connection record.+pub mod dispatch;/// 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.rsindex 748b2fe728..45fecfe386 100644--- a/crates/pipedream_mcp/src/outbound/pg_connection_repo.rs+++ b/crates/pipedream_mcp/src/outbound/pg_connection_repo.rs@@ -1,4 +1,6 @@-use crate::domain::models::{ConnectorOverlay, MacroUserIdStr, PipedreamConnection};+use crate::domain::models::{+ ConnectionProvider, ConnectorOverlay, MacroUserIdStr, PipedreamConnection,+};use crate::domain::ports::{AppConnections, ConnectionStore, ConnectorOverlays};use macro_user_id::cowlike::CowLike;use sqlx::PgPool;@@ -27,12 +29,13 @@ impl ConnectionStore for PgConnectionRepo {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)+ INSERT INTO pipedream_mcp_connections (user_id, app_slug, server_name, account_id, enabled, provider)+ VALUES ($1, $2, $3, $4, $5, $6)ON CONFLICT (user_id, app_slug) DO UPDATE SETserver_name = EXCLUDED.server_name,account_id = EXCLUDED.account_id,enabled = EXCLUDED.enabled,+ provider = EXCLUDED.provider,updated_at = NOW()"#,record.user_id.as_ref(),@@ -40,6 +43,7 @@ impl ConnectionStore for PgConnectionRepo {record.server_name,record.account_id,record.enabled,+ record.provider.as_str(),).execute(&self.pool).await?;@@ -54,7 +58,7 @@ impl ConnectionStore for PgConnectionRepo {) -> Result<Option<PipedreamConnection>, Self::Err> {let row = sqlx::query!(r#"- SELECT user_id, app_slug, server_name, account_id, enabled+ SELECT user_id, app_slug, server_name, account_id, enabled, providerFROM pipedream_mcp_connectionsWHERE user_id = $1 AND app_slug = $2AND NOT EXISTS (SELECT 1 FROM mcp_overlays o WHERE o.app_slug = $2)@@ -72,6 +76,7 @@ impl ConnectionStore for PgConnectionRepo {row.server_name,row.account_id,row.enabled,+ row.provider,)}).transpose()@@ -100,7 +105,7 @@ impl ConnectionStore for PgConnectionRepo {) -> Result<Vec<PipedreamConnection>, Self::Err> {let rows = sqlx::query!(r#"- SELECT user_id, app_slug, server_name, account_id, enabled+ SELECT user_id, app_slug, server_name, account_id, enabled, providerFROM pipedream_mcp_connections cWHERE user_id = $1AND NOT EXISTS (SELECT 1 FROM mcp_overlays o WHERE o.app_slug = c.app_slug)@@ -119,6 +124,7 @@ impl ConnectionStore for PgConnectionRepo {row.server_name,row.account_id,row.enabled,+ row.provider,)}).collect()@@ -133,7 +139,7 @@ impl AppConnections for PgConnectionRepo {) -> anyhow::Result<Vec<PipedreamConnection>> {let rows = sqlx::query!(r#"- SELECT user_id, app_slug, server_name, account_id, enabled+ SELECT user_id, app_slug, server_name, account_id, enabled, providerFROM pipedream_mcp_connectionsWHERE app_slug = $1 AND enabledAND NOT EXISTS (SELECT 1 FROM mcp_overlays o WHERE o.app_slug = $1)@@ -151,6 +157,7 @@ impl AppConnections for PgConnectionRepo {row.server_name,row.account_id,row.enabled,+ row.provider,)}).collect()@@ -186,6 +193,7 @@ fn to_record(server_name: String,account_id: String,enabled: bool,+ provider: String,) -> anyhow::Result<PipedreamConnection> {let user_id = MacroUserIdStr::parse_from_str(&user_id)?.into_owned();Ok(PipedreamConnection {@@ -194,6 +202,7 @@ fn to_record(server_name,account_id,enabled,+ provider: ConnectionProvider::parse(&provider)?,})}diff --git a/crates/pipedream_mcp/src/outbound/pg_connection_repo/test.rs b/crates/pipedream_mcp/src/outbound/pg_connection_repo/test.rsindex 1fe4b269c9..9b091f4ff2 100644--- a/crates/pipedream_mcp/src/outbound/pg_connection_repo/test.rs+++ b/crates/pipedream_mcp/src/outbound/pg_connection_repo/test.rs@@ -10,6 +10,7 @@ fn connection(app_slug: &str) -> PipedreamConnection {server_name: app_slug.to_owned(),account_id: format!("apn_{app_slug}"),enabled: true,+ provider: crate::domain::models::ConnectionProvider::Pipedream,}}@@ -99,3 +100,36 @@ async fn connections_require_an_existing_user(pool: PgPool) {let repo = PgConnectionRepo::new(pool);assert!(repo.save(&connection("granola")).await.is_err());}++/// Rows written before the provider column, and by services that predate+/// it, are Pipedream's; a Connect row round-trips its provider.+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("users"))+)]+async fn provider_defaults_to_pipedream_and_round_trips_connect(pool: PgPool) {+ sqlx::query!(+ "INSERT INTO pipedream_mcp_connections (user_id, app_slug, server_name, account_id)+ VALUES ($1, 'linear', 'Linear', 'apn_linear')",+ USER,+ )+ .execute(&pool)+ .await+ .unwrap();+ let repo = PgConnectionRepo::new(pool);+ let user = connection("linear").user_id;++ let legacy = repo.load(&user, "linear").await.unwrap().unwrap();+ assert_eq!(legacy.provider, ConnectionProvider::Pipedream);++ let connect = PipedreamConnection {+ account_id: "google_sheets".into(),+ provider: ConnectionProvider::Connect,+ ..connection("google_sheets")+ };+ repo.save(&connect).await.unwrap();+ assert_eq!(+ repo.load(&user, "google_sheets").await.unwrap(),+ Some(connect)+ );+}diff --git a/infra/packages/shared/src/service_urls.ts b/infra/packages/shared/src/service_urls.tsindex 842362e16b..e4a9c81660 100644--- a/infra/packages/shared/src/service_urls.ts+++ b/infra/packages/shared/src/service_urls.ts@@ -25,6 +25,7 @@ export enum ServiceUrl {AGENT_HARNESS_SERVICE_URL = 'AGENT_HARNESS_SERVICE_URL',AGENT_HARNESS_EGRESS_URL = 'AGENT_HARNESS_EGRESS_URL',MCP_SERVER_URL = 'MCP_SERVER_URL',+ CONNECT_API_URL = 'CONNECT_API_URL',}/**@@ -61,6 +62,7 @@ const DEV_SERVICE_URLS: ServiceUrlMap = {[ServiceUrl.AGENT_HARNESS_EGRESS_URL]:'https://dev-gateway.macro.com/agent-harness-egress',[ServiceUrl.MCP_SERVER_URL]: 'https://dev-gateway.macro.com/mcp',+ [ServiceUrl.CONNECT_API_URL]: 'https://connect-dev.macro.com',};/**@@ -88,6 +90,7 @@ const PROD_SERVICE_URLS: ServiceUrlMap = {[ServiceUrl.AGENT_HARNESS_EGRESS_URL]:'https://gateway.macro.com/agent-harness-egress',[ServiceUrl.MCP_SERVER_URL]: 'https://gateway.macro.com/mcp',+ [ServiceUrl.CONNECT_API_URL]: 'https://connect.macro.com',};/**diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/README.md b/packages/sdk-docs/reference/generated/cognition/types.gen/README.mdindex 279dedbffe..cb852c7eaa 100644--- a/packages/sdk-docs/reference/generated/cognition/types.gen/README.md+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/README.md@@ -52,11 +52,16 @@- [CompleteHandlerResponse](type-aliases/CompleteHandlerResponse.md)- [CompleteHandlerResponses](type-aliases/CompleteHandlerResponses.md)- [CompleteOnboardingRequest](type-aliases/CompleteOnboardingRequest.md)+- [CompletePipedreamMcpConnectData](type-aliases/CompletePipedreamMcpConnectData.md)+- [CompletePipedreamMcpConnectError](type-aliases/CompletePipedreamMcpConnectError.md)+- [CompletePipedreamMcpConnectErrors](type-aliases/CompletePipedreamMcpConnectErrors.md)- [CompletePipedreamMcpConnectionData](type-aliases/CompletePipedreamMcpConnectionData.md)- [CompletePipedreamMcpConnectionError](type-aliases/CompletePipedreamMcpConnectionError.md)- [CompletePipedreamMcpConnectionErrors](type-aliases/CompletePipedreamMcpConnectionErrors.md)- [CompletePipedreamMcpConnectionResponse](type-aliases/CompletePipedreamMcpConnectionResponse.md)- [CompletePipedreamMcpConnectionResponses](type-aliases/CompletePipedreamMcpConnectionResponses.md)+- [CompletePipedreamMcpConnectResponse](type-aliases/CompletePipedreamMcpConnectResponse.md)+- [CompletePipedreamMcpConnectResponses](type-aliases/CompletePipedreamMcpConnectResponses.md)- [CompletionUsage](type-aliases/CompletionUsage.md)- [ConnectedServer](type-aliases/ConnectedServer.md)- [ConversationRecord](type-aliases/ConversationRecord.md)@@ -272,9 +277,12 @@- [PipedreamCatalogEntryResponse](type-aliases/PipedreamCatalogEntryResponse.md)- [PipedreamCatalogResponse](type-aliases/PipedreamCatalogResponse.md)- [PipedreamCompleteRequest](type-aliases/PipedreamCompleteRequest.md)+- [PipedreamConnectCompleteRequest](type-aliases/PipedreamConnectCompleteRequest.md)- [PipedreamConnectionResponse](type-aliases/PipedreamConnectionResponse.md)- [PipedreamOverlayResponse](type-aliases/PipedreamOverlayResponse.md)+- [PipedreamProviderResponse](type-aliases/PipedreamProviderResponse.md)- [PipedreamRecoverRequest](type-aliases/PipedreamRecoverRequest.md)+- [PipedreamTokenRequest](type-aliases/PipedreamTokenRequest.md)- [PipedreamTokenResponse](type-aliases/PipedreamTokenResponse.md)- [PipedreamUpdateRequest](type-aliases/PipedreamUpdateRequest.md)- [Price](type-aliases/Price.md)diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectData.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectData.mdnew file mode 100644index 0000000000..21c791fec7--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectData.md@@ -0,0 +1,12 @@+# Type Alias: CompletePipedreamMcpConnectData++> **CompletePipedreamMcpConnectData** = \{ `body`: [`PipedreamConnectCompleteRequest`](PipedreamConnectCompleteRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/pipedream/mcp/connect/complete"`; \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-body"></a> `body` | [`PipedreamConnectCompleteRequest`](PipedreamConnectCompleteRequest.md) |+| <a id="property-path"></a> `path?` | `never` |+| <a id="property-query"></a> `query?` | `never` |+| <a id="property-url"></a> `url` | `"/pipedream/mcp/connect/complete"` |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectError.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectError.mdnew file mode 100644index 0000000000..52b284d45e--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectError.md@@ -0,0 +1,3 @@+# Type Alias: CompletePipedreamMcpConnectError++> **CompletePipedreamMcpConnectError** = [`CompletePipedreamMcpConnectErrors`](CompletePipedreamMcpConnectErrors.md)\[keyof [`CompletePipedreamMcpConnectErrors`](CompletePipedreamMcpConnectErrors.md)\]diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectErrors.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectErrors.mdnew file mode 100644index 0000000000..984583e1f5--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectErrors.md@@ -0,0 +1,12 @@+# Type Alias: CompletePipedreamMcpConnectErrors++> **CompletePipedreamMcpConnectErrors** = \{ `401`: `string`; `404`: [`ErrorResponse`](ErrorResponse.md); `500`: [`ErrorResponse`](ErrorResponse.md); `501`: [`ErrorResponse`](ErrorResponse.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-401"></a> `401` | `string` |+| <a id="property-404"></a> `404` | [`ErrorResponse`](ErrorResponse.md) |+| <a id="property-500"></a> `500` | [`ErrorResponse`](ErrorResponse.md) |+| <a id="property-501"></a> `501` | [`ErrorResponse`](ErrorResponse.md) |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectResponse.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectResponse.mdnew file mode 100644index 0000000000..f0d2c9eb48--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectResponse.md@@ -0,0 +1,3 @@+# Type Alias: CompletePipedreamMcpConnectResponse++> **CompletePipedreamMcpConnectResponse** = [`CompletePipedreamMcpConnectResponses`](CompletePipedreamMcpConnectResponses.md)\[keyof [`CompletePipedreamMcpConnectResponses`](CompletePipedreamMcpConnectResponses.md)\]diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectResponses.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectResponses.mdnew file mode 100644index 0000000000..830414486c--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CompletePipedreamMcpConnectResponses.md@@ -0,0 +1,9 @@+# Type Alias: CompletePipedreamMcpConnectResponses++> **CompletePipedreamMcpConnectResponses** = \{ `200`: [`PipedreamConnectionResponse`](PipedreamConnectionResponse.md); \}++## Properties++| Property | Type |+| ------ | ------ |+| <a id="property-200"></a> `200` | [`PipedreamConnectionResponse`](PipedreamConnectionResponse.md) |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CreatePipedreamMcpTokenData.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CreatePipedreamMcpTokenData.mdindex 70ab4cd373..a9a3bfce02 100644--- a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CreatePipedreamMcpTokenData.md+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/CreatePipedreamMcpTokenData.md@@ -1,12 +1,12 @@# Type Alias: CreatePipedreamMcpTokenData-> **CreatePipedreamMcpTokenData** = \{ `body?`: `never`; `path?`: `never`; `query?`: `never`; `url`: `"/pipedream/mcp/token"`; \}+> **CreatePipedreamMcpTokenData** = \{ `body?`: `null` \| [`PipedreamTokenRequest`](PipedreamTokenRequest.md); `path?`: `never`; `query?`: `never`; `url`: `"/pipedream/mcp/token"`; \}## Properties| Property | Type || ------ | ------ |-| <a id="property-body"></a> `body?` | `never` |+| <a id="property-body"></a> `body?` | `null` \| [`PipedreamTokenRequest`](PipedreamTokenRequest.md) || <a id="property-path"></a> `path?` | `never` || <a id="property-query"></a> `query?` | `never` || <a id="property-url"></a> `url` | `"/pipedream/mcp/token"` |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamConnectCompleteRequest.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamConnectCompleteRequest.mdnew file mode 100644index 0000000000..84ac0614a3--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamConnectCompleteRequest.md@@ -0,0 +1,12 @@+# Type Alias: PipedreamConnectCompleteRequest++> **PipedreamConnectCompleteRequest** = \{ `app_slug`: `string`; `server_name?`: `string` \| `null`; \}++Request body for recording a finished Macro Connect flow.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-app_slug"></a> `app_slug` | `string` | The app that was connected, by Pipedream slug. |+| <a id="property-server_name"></a> `server_name?` | `string` \| `null` | Optional display name for the connector, as for completion. |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamConnectionResponse.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamConnectionResponse.mdindex efe45ccebf..dafc20a4f5 100644--- a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamConnectionResponse.md+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamConnectionResponse.md@@ -1,6 +1,6 @@# Type Alias: PipedreamConnectionResponse-> **PipedreamConnectionResponse** = \{ `app_slug`: `string`; `enabled`: `boolean`; `server_name`: `string`; \}+> **PipedreamConnectionResponse** = \{ `app_slug`: `string`; `enabled`: `boolean`; `provider`: [`PipedreamProviderResponse`](PipedreamProviderResponse.md); `server_name`: `string`; \}A connected MCP app as returned by the API.@@ -10,4 +10,5 @@ A connected MCP app as returned by the API.| ------ | ------ | ------ || <a id="property-app_slug"></a> `app_slug` | `string` | Pipedream app name slug, e.g. `linear`. || <a id="property-enabled"></a> `enabled` | `boolean` | Whether the connector is enabled for tool use. |+| <a id="property-provider"></a> `provider` | [`PipedreamProviderResponse`](PipedreamProviderResponse.md) | The backend holding the grant. || <a id="property-server_name"></a> `server_name` | `string` | Human-readable display name. |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamProviderResponse.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamProviderResponse.mdnew file mode 100644index 0000000000..3c75b37abb--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamProviderResponse.md@@ -0,0 +1,5 @@+# Type Alias: PipedreamProviderResponse++> **PipedreamProviderResponse** = `"pipedream"` \| `"connect"`++Which backend a connection or connect flow uses.diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamTokenRequest.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamTokenRequest.mdnew file mode 100644index 0000000000..99a0029d0c--- /dev/null+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamTokenRequest.md@@ -0,0 +1,11 @@+# Type Alias: PipedreamTokenRequest++> **PipedreamTokenRequest** = \{ `app_slug?`: `string` \| `null`; \}++Request body for starting a connect flow.++## Properties++| Property | Type | Description |+| ------ | ------ | ------ |+| <a id="property-app_slug"></a> `app_slug?` | `string` \| `null` | The app to connect, by Pipedream slug. With it, an app Macro Connect serves can answer with a Connect URL instead of a Pipedream token. |diff --git a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamTokenResponse.md b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamTokenResponse.mdindex 988a1a74e0..bb2bdc7c96 100644--- a/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamTokenResponse.md+++ b/packages/sdk-docs/reference/generated/cognition/types.gen/type-aliases/PipedreamTokenResponse.md@@ -1,13 +1,16 @@# Type Alias: PipedreamTokenResponse-> **PipedreamTokenResponse** = \{ `connect_link_url`: `string`; `expires_at`: `string`; `token`: `string`; \}+> **PipedreamTokenResponse** = \{ `connect_link_url?`: `string` \| `null`; `connect_url?`: `string` \| `null`; `expires_at?`: `string` \| `null`; `provider`: [`PipedreamProviderResponse`](PipedreamProviderResponse.md); `token?`: `string` \| `null`; \}-Response from creating a Pipedream Connect token.+Response from starting a connect flow: a Pipedream Connect token, or for+`provider = connect` a Macro Connect URL.## Properties| Property | Type | Description || ------ | ------ | ------ |-| <a id="property-connect_link_url"></a> `connect_link_url` | `string` | Shareable link that opens the same connect flow in a browser tab. |-| <a id="property-expires_at"></a> `expires_at` | `string` | RFC 3339 expiry of the token. |-| <a id="property-token"></a> `token` | `string` | Short-lived token to open the Pipedream Connect UI with. |+| <a id="property-connect_link_url"></a> `connect_link_url?` | `string` \| `null` | Shareable link that opens the same connect flow in a browser tab. Pipedream only. |+| <a id="property-connect_url"></a> `connect_url?` | `string` \| `null` | URL to open in a popup or browser tab for Macro Connect's consent flow; once it finishes, call `/pipedream/mcp/connect/complete`. Connect only. |+| <a id="property-expires_at"></a> `expires_at?` | `string` \| `null` | RFC 3339 expiry of the token. Pipedream only. |+| <a id="property-provider"></a> `provider` | [`PipedreamProviderResponse`](PipedreamProviderResponse.md) | The backend this flow connects through. |+| <a id="property-token"></a> `token?` | `string` \| `null` | Short-lived token to open the Pipedream Connect UI with. Pipedream only. |diff --git a/packages/sdk/generated/cognition/index.ts b/packages/sdk/generated/cognition/index.tsindex babff7728b..ba0e53b0de 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-tsexport { type Options, Sdk } from './sdk.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, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponse, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponse, CancelWorkspaceHandlerResponses, 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, DatabaseChange, DatabaseQueryAnswer, DatabaseQueryChart, DatabaseQueryDisplayMode, DatabaseQueryRequest, DecisionErrorBody, DecisionRequest, DecisionResponse, DecisionsData, DecisionsError, DecisionsErrors, DecisionsResponse, DecisionsResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponse, DiscoverHandlerResponses, DismissedPrompts, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponse, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponse, DismissPromptHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, FreeTierModel, GenerateDatabaseQueryData, GenerateDatabaseQueryError, GenerateDatabaseQueryErrors, GenerateDatabaseQueryResponse, GenerateDatabaseQueryResponses, GenerateImageAspectRatio, GenerateImageData, GenerateImageError, GenerateImageErrorBody, GenerateImageErrors, GenerateImageReference, GenerateImageRequest, GenerateImageResponse, GenerateImageResponse2, GenerateImageResponses, 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, ImportKind, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, ListPipedreamMcpOverlaysData, ListPipedreamMcpOverlaysError, ListPipedreamMcpOverlaysErrors, ListPipedreamMcpOverlaysResponse, ListPipedreamMcpOverlaysResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, ModelSpeed, NewAttachment, NewChatMessage, NewMessageAttachment, NotionAlreadyImported, NotionDecision, NotionDocMeta, NotionImporter, NotionImportReport, NotionPlanItem, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponse, NotionReportHandlerResponses, NotionReportItem, NotionTaskFields, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamOverlayResponse, PipedreamRecoverRequest, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionError, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponse, RecoverPipedreamMcpConnectionResponses, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, ScanCounts, 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, StructuredCompletionOutcome, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, StructuredToolActivity, TargetType, ToolOutcome, 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, WorkspaceReportHandlerData, WorkspaceReportHandlerResponse, WorkspaceReportHandlerResponses } 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, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponse, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponse, CancelWorkspaceHandlerResponses, ChannelSharePermission, ChannelType, Chat, ChatAttachment, ChatHistory, ChatHistoryBatchMessagesRequest, ChatMessage, ChatMessageContent, ChatMessageError, ChatMessageWithAttachments, ChatPreview, ChatPreviewData, ChatResponse, ChatStream, ClientOptions, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponse, CompleteHandlerResponses, CompleteOnboardingRequest, CompletePipedreamMcpConnectData, CompletePipedreamMcpConnectError, CompletePipedreamMcpConnectErrors, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionError, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponse, CompletePipedreamMcpConnectionResponses, CompletePipedreamMcpConnectResponse, CompletePipedreamMcpConnectResponses, CompletionUsage, ConnectedServer, ConversationRecord, CopyChatData, CopyChatError, CopyChatErrors, CopyChatResponse, CopyChatResponses, CreateChatData, CreateChatError, CreateChatErrors, CreateChatRequest, CreateChatResponse, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenError, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponse, CreatePipedreamMcpTokenResponses, DatabaseChange, DatabaseQueryAnswer, DatabaseQueryChart, DatabaseQueryDisplayMode, DatabaseQueryRequest, DecisionErrorBody, DecisionRequest, DecisionResponse, DecisionsData, DecisionsError, DecisionsErrors, DecisionsResponse, DecisionsResponses, DeleteChatData, DeleteChatError, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerError, DeleteMcpServerErrors, DeleteMcpServerResponse, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionError, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponse, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponse, DiscoverHandlerResponses, DismissedPrompts, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponse, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponse, DismissPromptHandlerResponses, DocumentCognitionServiceApiVersion, DocumentReference, DocumentTextPart, DynamicSchema, Entity, EntityType, ErrorBody, ErrorResponse, Expiry, FeatureUsage, FileType, FreeTierModel, GenerateDatabaseQueryData, GenerateDatabaseQueryError, GenerateDatabaseQueryErrors, GenerateDatabaseQueryResponse, GenerateDatabaseQueryResponses, GenerateImageAspectRatio, GenerateImageData, GenerateImageError, GenerateImageErrorBody, GenerateImageErrors, GenerateImageReference, GenerateImageRequest, GenerateImageResponse, GenerateImageResponse2, GenerateImageResponses, 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, ImportKind, ImportRun, ImportSource, ImportState, ImportStatus, Initiator, JwtPayload, LinearIssueMeta, LinkShare, ListMcpServersData, ListMcpServersError, ListMcpServersErrors, ListMcpServersResponse, ListMcpServersResponses, ListPipedreamMcpConnectionsData, ListPipedreamMcpConnectionsError, ListPipedreamMcpConnectionsErrors, ListPipedreamMcpConnectionsResponse, ListPipedreamMcpConnectionsResponses, ListPipedreamMcpOverlaysData, ListPipedreamMcpOverlaysError, ListPipedreamMcpOverlaysErrors, ListPipedreamMcpOverlaysResponse, ListPipedreamMcpOverlaysResponses, MacroUserIdStr, McpAuthCallbackData, McpAuthCallbackError, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, MemoryErrorBody, MemoryResponse, MessageWithAttachments, ModelSpeed, NewAttachment, NewChatMessage, NewMessageAttachment, NotionAlreadyImported, NotionDecision, NotionDocMeta, NotionImporter, NotionImportReport, NotionPlanItem, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponse, NotionReportHandlerResponses, NotionReportItem, NotionTaskFields, OnboardingRow, OnboardingState, OnboardingStatus, PatchChatData, PatchChatError, PatchChatErrors, PatchChatRequest, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatError, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, PipedreamCatalogEntryResponse, PipedreamCatalogResponse, PipedreamCompleteRequest, PipedreamConnectCompleteRequest, PipedreamConnectionResponse, PipedreamOverlayResponse, PipedreamProviderResponse, PipedreamRecoverRequest, PipedreamTokenRequest, PipedreamTokenResponse, PipedreamUpdateRequest, Price, ProjectionStateResponse, ProjectionStatus, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionError, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponse, RecoverPipedreamMcpConnectionResponses, RefreshCadence, RejectToolCallData, RejectToolCallError, RejectToolCallErrors, RejectToolCallRequest, RejectToolCallResponses, RevertDeleteChatData, RevertDeleteChatError, RevertDeleteChatErrors, RevertDeleteChatResponses, Role, RunImportHandlerData, RunImportHandlerErrors, RunImportHandlerResponse, RunImportHandlerResponses, RunImportOutcome, RunImportRequest, RunStatus, ScanCounts, 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, StructuredCompletionOutcome, StructuredCompletionRequest, StructuredCompletionResponse, StructuredCompletionResponse2, StructuredCompletionResponses, StructuredToolActivity, TargetType, ToolOutcome, 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, WorkspaceReportHandlerData, WorkspaceReportHandlerResponse, WorkspaceReportHandlerResponses } from './types.gen';diff --git a/packages/sdk/generated/cognition/sdk.gen.ts b/packages/sdk/generated/cognition/sdk.gen.tsindex d7f7076781..56741ee27f 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, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolErrors, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponses, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponses, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponses, CopyChatData, CopyChatErrors, CopyChatResponses, CreateChatData, CreateChatErrors, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponses, DecisionsData, DecisionsErrors, DecisionsResponses, DeleteChatData, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerErrors, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponses, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponses, GenerateDatabaseQueryData, GenerateDatabaseQueryErrors, GenerateDatabaseQueryResponses, GenerateImageData, GenerateImageErrors, GenerateImageResponses, 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, ListPipedreamMcpOverlaysData, ListPipedreamMcpOverlaysErrors, ListPipedreamMcpOverlaysResponses, McpAuthCallbackData, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponses, PatchChatData, PatchChatErrors, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponses, RejectToolCallData, RejectToolCallErrors, RejectToolCallResponses, 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, WorkspaceReportHandlerData, WorkspaceReportHandlerResponses } from './types.gen';+import type { AddMcpServerData, AddMcpServerErrors, AddMcpServerResponses, BrowsePipedreamMcpCatalogData, BrowsePipedreamMcpCatalogErrors, BrowsePipedreamMcpCatalogResponses, CallToolData, CallToolErrors, CallToolResponses, CancelNotionHandlerData, CancelNotionHandlerErrors, CancelNotionHandlerResponses, CancelWorkspaceHandlerData, CancelWorkspaceHandlerResponses, CompleteHandlerData, CompleteHandlerErrors, CompleteHandlerResponses, CompletePipedreamMcpConnectData, CompletePipedreamMcpConnectErrors, CompletePipedreamMcpConnectionData, CompletePipedreamMcpConnectionErrors, CompletePipedreamMcpConnectionResponses, CompletePipedreamMcpConnectResponses, CopyChatData, CopyChatErrors, CopyChatResponses, CreateChatData, CreateChatErrors, CreateChatResponses, CreatePipedreamMcpTokenData, CreatePipedreamMcpTokenErrors, CreatePipedreamMcpTokenResponses, DecisionsData, DecisionsErrors, DecisionsResponses, DeleteChatData, DeleteChatErrors, DeleteChatResponses, DeleteMcpServerData, DeleteMcpServerErrors, DeleteMcpServerResponses, DeletePipedreamMcpConnectionData, DeletePipedreamMcpConnectionErrors, DeletePipedreamMcpConnectionResponses, DiscoverHandlerData, DiscoverHandlerErrors, DiscoverHandlerResponses, DismissedPromptsHandlerData, DismissedPromptsHandlerErrors, DismissedPromptsHandlerResponses, DismissPromptHandlerData, DismissPromptHandlerErrors, DismissPromptHandlerResponses, GenerateDatabaseQueryData, GenerateDatabaseQueryErrors, GenerateDatabaseQueryResponses, GenerateImageData, GenerateImageErrors, GenerateImageResponses, 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, ListPipedreamMcpOverlaysData, ListPipedreamMcpOverlaysErrors, ListPipedreamMcpOverlaysResponses, McpAuthCallbackData, McpAuthCallbackErrors, McpAuthCallbackResponses, McpOauthClientMetadataData, McpOauthClientMetadataResponses, NotionReportHandlerData, NotionReportHandlerErrors, NotionReportHandlerResponses, PatchChatData, PatchChatErrors, PatchChatResponses, PermanentlyDeleteChatData, PermanentlyDeleteChatErrors, PermanentlyDeleteChatResponses, RecoverPipedreamMcpConnectionData, RecoverPipedreamMcpConnectionErrors, RecoverPipedreamMcpConnectionResponses, RejectToolCallData, RejectToolCallErrors, RejectToolCallResponses, 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, WorkspaceReportHandlerData, WorkspaceReportHandlerResponses } from './types.gen';export type Options<TData extends TDataShape = TDataShape, ThrowOnError extends boolean = boolean, TResponse = unknown> = Options2<TData, ThrowOnError, TResponse> & {/**@@ -503,6 +503,23 @@ export class Sdk extends HeyApiClient {});}+ /**+ * Record an app the user connected through Macro Connect.+ *+ * Answers 404 until Connect lists an active connection for this user and+ * app, so the frontend can poll it while the consent window is open.+ */+ public completePipedreamMcpConnect<ThrowOnError extends boolean = false>(options: Options<CompletePipedreamMcpConnectData, ThrowOnError>): RequestResult<CompletePipedreamMcpConnectResponses, CompletePipedreamMcpConnectErrors, ThrowOnError> {+ return (options.client ?? this.client).post<CompletePipedreamMcpConnectResponses, CompletePipedreamMcpConnectErrors, ThrowOnError>({+ url: '/pipedream/mcp/connect/complete',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options.headers+ }+ });+ }+/*** Disconnect an app, revoking its Pipedream account.*/@@ -561,13 +578,23 @@ export class Sdk extends HeyApiClient {}/**- * Create a short-lived Pipedream Connect token for the authenticated user.+ * Start a connect flow 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.+ * By default, a short-lived Pipedream Connect token: the frontend opens+ * Pipedream's hosted Connect UI with it, and the user picks (or is+ * deep-linked into) an app and authorizes it there. When the body names an+ * app Macro Connect serves and the `macro-connect` rollout is on for the+ * user, a Connect URL instead.*/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 });+ return (options?.client ?? this.client).post<CreatePipedreamMcpTokenResponses, CreatePipedreamMcpTokenErrors, ThrowOnError>({+ url: '/pipedream/mcp/token',+ ...options,+ headers: {+ 'Content-Type': 'application/json',+ ...options?.headers+ }+ });}public getBatchPreview<ThrowOnError extends boolean = false>(options: Options<GetBatchPreviewData, ThrowOnError>): RequestResult<GetBatchPreviewResponses, GetBatchPreviewErrors, ThrowOnError> {diff --git a/packages/sdk/generated/cognition/types.gen.ts b/packages/sdk/generated/cognition/types.gen.tsindex 8b82006712..7ac1f6721d 100644--- a/packages/sdk/generated/cognition/types.gen.ts+++ b/packages/sdk/generated/cognition/types.gen.ts@@ -1500,6 +1500,20 @@ export type PipedreamCompleteRequest = {server_name?: string | null;};+/**+ * Request body for recording a finished Macro Connect flow.+ */+export type PipedreamConnectCompleteRequest = {+ /**+ * The app that was connected, by Pipedream slug.+ */+ app_slug: string;+ /**+ * Optional display name for the connector, as for completion.+ */+ server_name?: string | null;+};+/*** A connected MCP app as returned by the API.*/@@ -1512,6 +1526,10 @@ export type PipedreamConnectionResponse = {* Whether the connector is enabled for tool use.*/enabled: boolean;+ /**+ * The backend holding the grant.+ */+ provider: PipedreamProviderResponse;/*** Human-readable display name.*/@@ -1533,6 +1551,11 @@ export type PipedreamOverlayResponse = {server_url: string;};+/**+ * Which backend a connection or connect flow uses.+ */+export type PipedreamProviderResponse = 'pipedream' | 'connect';+/*** Request body for recovering a connect flow whose result the Connect UI* never reported.@@ -1549,21 +1572,44 @@ export type PipedreamRecoverRequest = {};/**- * Response from creating a Pipedream Connect token.+ * Request body for starting a connect flow.+ */+export type PipedreamTokenRequest = {+ /**+ * The app to connect, by Pipedream slug. With it, an app Macro Connect+ * serves can answer with a Connect URL instead of a Pipedream token.+ */+ app_slug?: string | null;+};++/**+ * Response from starting a connect flow: a Pipedream Connect token, or for+ * `provider = connect` a Macro Connect URL.*/export type PipedreamTokenResponse = {/*** Shareable link that opens the same connect flow in a browser tab.+ * Pipedream only.*/- connect_link_url: string;+ connect_link_url?: string | null;/**- * RFC 3339 expiry of the token.+ * URL to open in a popup or browser tab for Macro Connect's consent+ * flow; once it finishes, call `/pipedream/mcp/connect/complete`.+ * Connect only.*/- expires_at: string;+ connect_url?: string | null;/**- * Short-lived token to open the Pipedream Connect UI with.+ * RFC 3339 expiry of the token. Pipedream only.*/- token: string;+ expires_at?: string | null;+ /**+ * The backend this flow connects through.+ */+ provider: PipedreamProviderResponse;+ /**+ * Short-lived token to open the Pipedream Connect UI with. Pipedream only.+ */+ token?: string | null;};/**@@ -3444,6 +3490,28 @@ export type CompletePipedreamMcpConnectionResponses = {export type CompletePipedreamMcpConnectionResponse = CompletePipedreamMcpConnectionResponses[keyof CompletePipedreamMcpConnectionResponses];+export type CompletePipedreamMcpConnectData = {+ body: PipedreamConnectCompleteRequest;+ path?: never;+ query?: never;+ url: '/pipedream/mcp/connect/complete';+};++export type CompletePipedreamMcpConnectErrors = {+ 401: string;+ 404: ErrorResponse;+ 500: ErrorResponse;+ 501: ErrorResponse;+};++export type CompletePipedreamMcpConnectError = CompletePipedreamMcpConnectErrors[keyof CompletePipedreamMcpConnectErrors];++export type CompletePipedreamMcpConnectResponses = {+ 200: PipedreamConnectionResponse;+};++export type CompletePipedreamMcpConnectResponse = CompletePipedreamMcpConnectResponses[keyof CompletePipedreamMcpConnectResponses];+export type DeletePipedreamMcpConnectionData = {body?: never;path?: never;@@ -3554,7 +3622,7 @@ export type RecoverPipedreamMcpConnectionResponses = {export type RecoverPipedreamMcpConnectionResponse = RecoverPipedreamMcpConnectionResponses[keyof RecoverPipedreamMcpConnectionResponses];export type CreatePipedreamMcpTokenData = {- body?: never;+ body?: null | PipedreamTokenRequest;path?: never;query?: never;url: '/pipedream/mcp/token';diff --git a/packages/sdk/specs/cognition.json b/packages/sdk/specs/cognition.jsonindex ddd279c17b..78ce481e87 100644--- a/packages/sdk/specs/cognition.json+++ b/packages/sdk/specs/cognition.json@@ -2154,6 +2154,76 @@}}},+ "/pipedream/mcp/connect/complete": {+ "post": {+ "tags": ["pipedream-mcp"],+ "summary": "Record an app the user connected through Macro Connect.",+ "description": "Answers 404 until Connect lists an active connection for this user and\napp, so the frontend can poll it while the consent window is open.",+ "operationId": "complete_pipedream_mcp_connect",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PipedreamConnectCompleteRequest"+ }+ }+ },+ "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"],@@ -2420,9 +2490,25 @@"/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.",+ "summary": "Start a connect flow for the authenticated user.",+ "description": "By default, a short-lived Pipedream Connect token: the frontend opens\nPipedream's hosted Connect UI with it, and the user picks (or is\ndeep-linked into) an app and authorizes it there. When the body names an\napp Macro Connect serves and the `macro-connect` rollout is on for the\nuser, a Connect URL instead.","operationId": "create_pipedream_mcp_token",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/PipedreamTokenRequest"+ }+ ]+ }+ }+ }+ },"responses": {"200": {"description": "",@@ -5454,10 +5540,25 @@}}},+ "PipedreamConnectCompleteRequest": {+ "type": "object",+ "description": "Request body for recording a finished Macro Connect flow.",+ "required": ["app_slug"],+ "properties": {+ "app_slug": {+ "type": "string",+ "description": "The app that was connected, by Pipedream slug."+ },+ "server_name": {+ "type": ["string", "null"],+ "description": "Optional display name for the connector, as for completion."+ }+ }+ },"PipedreamConnectionResponse": {"type": "object","description": "A connected MCP app as returned by the API.",- "required": ["app_slug", "server_name", "enabled"],+ "required": ["app_slug", "server_name", "enabled", "provider"],"properties": {"app_slug": {"type": "string",@@ -5467,6 +5568,10 @@"type": "boolean","description": "Whether the connector is enabled for tool use."},+ "provider": {+ "$ref": "#/components/schemas/PipedreamProviderResponse",+ "description": "The backend holding the grant."+ },"server_name": {"type": "string","description": "Human-readable display name."@@ -5488,6 +5593,11 @@}}},+ "PipedreamProviderResponse": {+ "type": "string",+ "description": "Which backend a connection or connect flow uses.",+ "enum": ["pipedream", "connect"]+ },"PipedreamRecoverRequest": {"type": "object","description": "Request body for recovering a connect flow whose result the Connect UI\nnever reported.",@@ -5503,22 +5613,40 @@}}},+ "PipedreamTokenRequest": {+ "type": "object",+ "description": "Request body for starting a connect flow.",+ "properties": {+ "app_slug": {+ "type": ["string", "null"],+ "description": "The app to connect, by Pipedream slug. With it, an app Macro Connect\nserves can answer with a Connect URL instead of a Pipedream token."+ }+ }+ },"PipedreamTokenResponse": {"type": "object",- "description": "Response from creating a Pipedream Connect token.",- "required": ["token", "expires_at", "connect_link_url"],+ "description": "Response from starting a connect flow: a Pipedream Connect token, or for\n`provider = connect` a Macro Connect URL.",+ "required": ["provider"],"properties": {"connect_link_url": {- "type": "string",- "description": "Shareable link that opens the same connect flow in a browser tab."+ "type": ["string", "null"],+ "description": "Shareable link that opens the same connect flow in a browser tab.\nPipedream only."+ },+ "connect_url": {+ "type": ["string", "null"],+ "description": "URL to open in a popup or browser tab for Macro Connect's consent\nflow; once it finishes, call `/pipedream/mcp/connect/complete`.\nConnect only."},"expires_at": {- "type": "string",- "description": "RFC 3339 expiry of the token."+ "type": ["string", "null"],+ "description": "RFC 3339 expiry of the token. Pipedream only."+ },+ "provider": {+ "$ref": "#/components/schemas/PipedreamProviderResponse",+ "description": "The backend this flow connects through."},"token": {- "type": "string",- "description": "Short-lived token to open the Pipedream Connect UI with."+ "type": ["string", "null"],+ "description": "Short-lived token to open the Pipedream Connect UI with. Pipedream only."}}},diff --git a/packages/sdk/src/coverage/skipped.ts b/packages/sdk/src/coverage/skipped.tsindex e2068199b0..6fa5fbba64 100644--- a/packages/sdk/src/coverage/skipped.ts+++ b/packages/sdk/src/coverage/skipped.ts@@ -164,6 +164,7 @@ export const cognitionExcluded = ['addMcpServer','browsePipedreamMcpCatalog','callTool',+ 'completePipedreamMcpConnect','completePipedreamMcpConnection','createPipedreamMcpToken','deletePipedreamMcpConnection',diff --git a/services/agent_harness_service/src/cognition/api.rs b/services/agent_harness_service/src/cognition/api.rsindex 99e4f74f0e..c3264ec575 100644--- a/services/agent_harness_service/src/cognition/api.rs+++ b/services/agent_harness_service/src/cognition/api.rs@@ -164,7 +164,9 @@ fn api_router(api_context: ApiContext) -> Router {.merge(mcp_client::inbound::mcp_oauth_callback_router(mcp_state)).merge(granola_sync::inbound::webhook_router(api_context.granola_sync.clone(),- ));+ ))+ // Macro Connect's consent finishes on this page; it records nothing.+ .merge(pipedream_mcp::inbound::pipedream_connect_callback_router());match api_context.config.pipedream_webhook_secret.value() {Some(secret) => app.merge(pipedream_mcp::inbound::pipedream_webhook_router(diff --git a/services/agent_harness_service/src/cognition/api/context.rs b/services/agent_harness_service/src/cognition/api/context.rsindex a27eb30969..b3294a99bb 100644--- a/services/agent_harness_service/src/cognition/api/context.rs+++ b/services/agent_harness_service/src/cognition/api/context.rs@@ -128,11 +128,11 @@ pub type DcsOnboardingService = onboarding::domain::service::OnboardingServiceIm>;/// Concrete Pipedream MCP router state for DCS: the Postgres connection-/// store plus the Pipedream client (None when not configured — endpoints+/// store plus the connector backends (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,+ pipedream_mcp::outbound::dispatch::ConnectorBackends,DcsAuthorizationService,>;diff --git a/services/agent_harness_service/src/cognition/api/swagger.rs b/services/agent_harness_service/src/cognition/api/swagger.rsindex 87fd2011e1..1c03e1eb05 100644--- a/services/agent_harness_service/src/cognition/api/swagger.rs+++ b/services/agent_harness_service/src/cognition/api/swagger.rs@@ -32,8 +32,9 @@ use memory::inbound::axum_router::{self as memory_api, MemoryErrorBody, MemoryReuse onboarding::inbound::axum_router::{self as onboarding_api, CompleteOnboardingRequest};use pipedream_mcp::inbound::axum_router::{self as pipedream_api, PipedreamCatalogEntryResponse, PipedreamCatalogResponse,- PipedreamCompleteRequest, PipedreamConnectionResponse, PipedreamOverlayResponse,- PipedreamRecoverRequest, PipedreamTokenResponse, PipedreamUpdateRequest,+ PipedreamCompleteRequest, PipedreamConnectCompleteRequest, PipedreamConnectionResponse,+ PipedreamOverlayResponse, PipedreamProviderResponse, PipedreamRecoverRequest,+ PipedreamTokenRequest, PipedreamTokenResponse, PipedreamUpdateRequest,};use crate::cognition::api::preview::get_batch_preview::{@@ -124,6 +125,7 @@ use utoipa::OpenApi;pipedream_api::create_connect_token,pipedream_api::complete_connection,pipedream_api::recover_connection,+ pipedream_api::complete_connect,pipedream_api::browse_catalog_handler,pipedream_api::list_overlays),@@ -273,7 +275,10 @@ use utoipa::OpenApi;// Pipedream MCP connectorsPipedreamConnectionResponse,PipedreamUpdateRequest,+ PipedreamTokenRequest,PipedreamTokenResponse,+ PipedreamProviderResponse,+ PipedreamConnectCompleteRequest,PipedreamCompleteRequest,PipedreamRecoverRequest,PipedreamCatalogResponse,diff --git a/services/agent_harness_service/src/cognition/config.rs b/services/agent_harness_service/src/cognition/config.rsindex 192105064d..780363aae6 100644--- a/services/agent_harness_service/src/cognition/config.rs+++ b/services/agent_harness_service/src/cognition/config.rs@@ -68,6 +68,9 @@ maybe_env_vars!(pub struct PosthogApiKey;/// PostHog ingestion origin. Falls back to the US origin when unset.pub struct PosthogHost;+ /// Macro's customer key for the Macro Connect API. When unset, Connect+ /// is off and every connection goes through Pipedream.+ pub struct ConnectCustomerKey;);/// The configuration parameters for the application.@@ -152,6 +155,9 @@ pub struct Config {pub posthog_api_key: PosthogApiKey,/// PostHog ingestion origin for integration analytics.pub posthog_host: PosthogHost,+ /// Customer key for Macro Connect, which serves the apps it has in its+ /// catalog to users in the `macro-connect` rollout.+ pub connect_customer_key: ConnectCustomerKey,/// The internal api keypub internal_api_key: InternalApiKey,/// AI editing worker URL@@ -255,6 +261,7 @@ impl Config {pipedream_webhook_secret: PipedreamWebhookSecret::Unset,posthog_api_key: PosthogApiKey::Unset,posthog_host: PosthogHost::Unset,+ connect_customer_key: ConnectCustomerKey::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/agent_harness_service/src/cognition/server.rs b/services/agent_harness_service/src/cognition/server.rsindex f83d127487..bc8b0b24b1 100644--- a/services/agent_harness_service/src/cognition/server.rs+++ b/services/agent_harness_service/src/cognition/server.rs@@ -594,7 +594,7 @@ pub async fn build(// endpoints answer 501 and its toolsets come up empty. Connect-flow// webhooks need both URI and secret; a half-set pair is ignored so we// never mint a callback we cannot serve.- let pipedream_client: ai_tools::ToolPipedreamConnection = match (+ let pipedream_client: Option<Arc<pipedream_mcp::outbound::api::PipedreamClient>> = match (config.pipedream_client_id.value(),config.pipedream_client_secret.value(),config.pipedream_project_id.value(),@@ -664,6 +664,23 @@ pub async fn build(None}};+ // Macro Connect beside Pipedream: a user the `macro-connect` rollout is+ // on for is on Connect alone; everyone else stays on Pipedream.+ let connect_adapter = ai_tools::connect_adapter(config.connect_customer_key.value())?;+ let rollout = ai_tools::macro_connect_rollout(+ config.posthog_api_key.value(),+ config.posthog_host.value(),+ )?;+ let connectors: ai_tools::ToolPipedreamConnection = pipedream_client.as_ref().map(|client| {+ let backends = pipedream_mcp::outbound::dispatch::ConnectorBackends::new(+ client.clone(),+ connect_adapter.clone(),+ );+ Arc::new(match &rollout {+ Some(rollout) => backends.with_rollout(rollout.clone()),+ None => backends,+ })+ });let pipedream_repo =pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo::new(db.clone());let granola_sync: Option<Arc<dyn granola_sync::domain::service::SyncService>> =@@ -698,7 +715,7 @@ pub async fn build(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()),+ Arc::new(connectors.clone()),));// Nudges the user's connected clients when import rows flip, so setup@@ -761,20 +778,20 @@ pub async fn build(Arc::new(import_linear::outbound::client::PipedreamLinearConnections::new(Arc::new(pipedream_repo.clone()),- pipedream_client.clone(),+ connectors.clone(),),),Arc::new(import_jira::outbound::client::PipedreamJiraConnections::new(Arc::new(pipedream_repo.clone()),- pipedream_client.clone(),+ connectors.clone(),),),).with_notion_connections(Arc::new(import_notion::outbound::pipedream::PipedreamNotionConnections::new(Arc::new(pipedream_repo.clone()),- pipedream_client.clone(),+ connectors.clone(),),)).with_admission(admission.clone())@@ -1080,7 +1097,7 @@ pub async fn build();let pipedream_state = pipedream_mcp::inbound::PipedreamRouterState::new(pipedream_repo,- pipedream_client,+ connectors,authorization_state.clone(),).with_auth_completed_hook(pipedream_auth_hook)diff --git a/services/agent_harness_service/src/config.rs b/services/agent_harness_service/src/config.rsindex 90323fff82..55774e2808 100644--- a/services/agent_harness_service/src/config.rs+++ b/services/agent_harness_service/src/config.rs@@ -52,6 +52,9 @@ macro_env_var::maybe_env_vars!(pub struct PosthogApiKey;/// Regional PostHog ingestion origin; defaults to the US origin.pub struct PosthogHost;+ /// Macro's customer key for the Macro Connect API. When unset, Connect+ /// is off and every connection goes through Pipedream.+ pub struct ConnectCustomerKey;/// Dedicated KMS key for encrypted per-owner Codex OAuth state.pub struct CodexOauthKmsKeyId;/// Rollout gate for sessions owned by a bot.@@ -110,6 +113,9 @@ pub struct Config {pub posthog_api_key: PosthogApiKey,/// Same regional origin as the frontend's PostHog project.pub posthog_host: PosthogHost,+ /// Customer key for Macro Connect; sandboxes reach Connect-held grants+ /// through its MCP gateway.+ pub connect_customer_key: ConnectCustomerKey,/// Pinned Deno executable. Unset hosts do not advertise code execution.pub deno_binary: Option<String>,/// Default-off quota admission and prospective usage counting.diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rsindex 7fd16626d5..fe5ec08538 100644--- a/services/agent_harness_service/src/main.rs+++ b/services/agent_harness_service/src/main.rs@@ -158,6 +158,7 @@ use mcp_client::outbound::pg_server_repo::PgServerRepo;use model_providers::{CursorModels, InMemoryModels, MacrodModels, VisibleHarnessAccess};use permission_policy::PgPermissionPolicySource;use pipedream_mcp::outbound::api::{PipedreamClient, PipedreamConfig};+use pipedream_mcp::outbound::dispatch::ConnectorBackends;use pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo;use rdkafka::consumer::CommitMode;use rdkafka::message::{BorrowedMessage, Message as _};@@ -493,6 +494,18 @@ async fn run() -> anyhow::Result<()> {allowed_origins: Vec::new(),}).context("failed to build Pipedream client")?;+ // Grants held by Macro Connect are reached through its MCP gateway; a+ // user on Connect alone gets no Pipedream grant.+ let mut connectors = ConnectorBackends::new(+ Arc::new(pipedream),+ ai_tools::connect_adapter(config.connect_customer_key.value())?,+ );+ if let Some(rollout) = ai_tools::macro_connect_rollout(+ config.posthog_api_key.value(),+ config.posthog_host.value(),+ )? {+ connectors = connectors.with_rollout(rollout);+ }// Every session's MCP servers: Macro's own under the reserved `macro`// slug, the owner's custom servers by URL key, then the owner's Pipedream@@ -501,7 +514,7 @@ async fn run() -> anyhow::Result<()> {// single-user and minutes from expiry.let mcp_credentials = WithMacroMcp::new(WithCustomMcp::new(- PipedreamMcpCredentials::new(Arc::clone(&mcp_connections), pipedream),+ PipedreamMcpCredentials::new(Arc::clone(&mcp_connections), connectors),Arc::clone(&mcp_servers),),MacroApiTokenSigner::new(