Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(agents): discover and connect missing integrations (#7776)

Eric Hayes7c9f7fa9baa4
diff --git a/Cargo.lock b/Cargo.lock
index b91a11d032..f8875618aa 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -14401,6 +14401,7 @@ version = "0.1.0"
dependencies = [
"ai_toolset",
"anyhow",
+ "async-trait",
"axum",
"futures",
"macro_authorization",
diff --git a/apps/docs/AI/mcp/tools/discover-connectors.mdx b/apps/docs/AI/mcp/tools/discover-connectors.mdx
new file mode 100644
index 0000000000..10ee45ecff
--- /dev/null
+++ b/apps/docs/AI/mcp/tools/discover-connectors.mdx
@@ -0,0 +1,16 @@
+---
+title: DiscoverConnectors
+description: >-
+ Find an integration when an external app is missing or a workflow requires an
+ unconnected account, including native import tools that need a connector.
+---
+
+# DiscoverConnectors
+
+Find an integration when an external app is missing or a workflow requires an unconnected account, including native import tools that need a connector. Use SearchTools for available actions. Search by app name, then inspect a returned app_slug to see its actual tools and connection status. Only recommend connecting if an advertised tool supports the task; an app's name alone is not evidence. Inspection does not load or execute tools. If suitable and unconnected, include the returned connect_markup in your reply and explain what connecting enables. After connection, use SearchTools again in the same agent session to load and call the new tools.
+
+## Parameters
+
+| Parameter | Type | Required | Description |
+| --- | --- | --- | --- |
+| `request` | DiscoveryRequest | Yes | Search by app name, then inspect a returned slug before recommending auth. |
diff --git a/apps/docs/AI/mcp/tools/index.mdx b/apps/docs/AI/mcp/tools/index.mdx
index df2afc7998..9101c9f15a 100644
--- a/apps/docs/AI/mcp/tools/index.mdx
+++ b/apps/docs/AI/mcp/tools/index.mdx
@@ -35,6 +35,7 @@ These pages are generated from Macro's Rust MCP tool registry.
- [DeleteInitiative](/AI/mcp/tools/delete-initiative)
- [DeleteTag](/AI/mcp/tools/delete-tag)
- [DescribeDatabase](/AI/mcp/tools/describe-database)
+- [DiscoverConnectors](/AI/mcp/tools/discover-connectors)
- [DispatchCodingAgent](/AI/mcp/tools/dispatch-coding-agent)
- [DisplayResults](/AI/mcp/tools/display-results)
- [EditBookingLink](/AI/mcp/tools/edit-booking-link)
diff --git a/apps/docs/config/tool-pages.json b/apps/docs/config/tool-pages.json
index c6fa1a3481..8ac49b4246 100644
--- a/apps/docs/config/tool-pages.json
+++ b/apps/docs/config/tool-pages.json
@@ -26,6 +26,7 @@
"AI/mcp/tools/delete-initiative",
"AI/mcp/tools/delete-tag",
"AI/mcp/tools/describe-database",
+ "AI/mcp/tools/discover-connectors",
"AI/mcp/tools/dispatch-coding-agent",
"AI/mcp/tools/display-results",
"AI/mcp/tools/edit-booking-link",
diff --git a/apps/docs/docs.json b/apps/docs/docs.json
index 2c35aa6780..924e8d7120 100644
--- a/apps/docs/docs.json
+++ b/apps/docs/docs.json
@@ -97,6 +97,7 @@
"AI/mcp/tools/delete-initiative",
"AI/mcp/tools/delete-tag",
"AI/mcp/tools/describe-database",
+ "AI/mcp/tools/discover-connectors",
"AI/mcp/tools/dispatch-coding-agent",
"AI/mcp/tools/display-results",
"AI/mcp/tools/edit-booking-link",
diff --git a/apps/web/src/features/block-agent/component/AgentConnections.test.tsx b/apps/web/src/features/block-agent/component/AgentConnections.test.tsx
new file mode 100644
index 0000000000..56393b969e
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/AgentConnections.test.tsx
@@ -0,0 +1,122 @@
+import { AppConnectionContext } from '@core/pipedream/connection-context';
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from '@solidjs/testing-library';
+import { useContext } from 'solid-js';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { AgentConnections } from './AgentConnections';
+
+const mocks = vi.hoisted(() => ({
+ owner: 'owner',
+ viewer: 'owner',
+ turn: 'idle',
+ revision: 0,
+ connect: vi.fn(),
+ issue: vi.fn(),
+ notify: vi.fn(),
+}));
+vi.mock('@queries/pipedream-connectors', () => ({
+ connectPipedreamApp: mocks.connect,
+}));
+vi.mock('@core/component/Toast/Toast', () => ({
+ toast: { alert: mocks.notify },
+}));
+vi.mock('./prompt-action', () => ({
+ promptActionOf: (prompt: string) => ({ type: 'prompt', prompt }),
+}));
+vi.mock('../context/AgentSessionContext', () => ({
+ useAgentSession: () => ({
+ sessionId: () => 'agent-session',
+ pending: () => false,
+ loadFailed: () => false,
+ session: () => ({ canEdit: true, ownerId: mocks.owner }),
+ userId: () => mocks.viewer,
+ turn: () => mocks.turn,
+ queue: { entries: () => [] },
+ messages: () => [{ turn: mocks.revision, author: { kind: 'agent' } }],
+ issue: mocks.issue,
+ }),
+}));
+function Button() {
+ const context = useContext(AppConnectionContext)!;
+ return (
+ <button
+ disabled={context.disabled()}
+ onClick={() => context.connect({ appSlug: 'notion', name: 'Notion' })}
+ >
+ Connect Notion
+ </button>
+ );
+}
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.owner = 'owner';
+ mocks.viewer = 'owner';
+ mocks.turn = 'idle';
+ mocks.revision = 0;
+ mocks.issue.mockResolvedValue({ isErr: () => false });
+});
+afterEach(cleanup);
+
+it('registers then issues exactly one agent prompt without touching the composer', async () => {
+ mocks.connect.mockResolvedValue('connected');
+ render(() => (
+ <AgentConnections>
+ <Button />
+ <textarea />
+ </AgentConnections>
+ ));
+ fireEvent.input(screen.getByRole('textbox'), {
+ target: { value: 'unsent draft' },
+ });
+ fireEvent.click(screen.getByRole('button'));
+ await waitFor(() =>
+ expect(mocks.issue).toHaveBeenCalledExactlyOnceWith({
+ type: 'prompt',
+ prompt:
+ 'I connected Notion. Continue my previous request using the newly available tools.',
+ })
+ );
+ expect((screen.getByRole('textbox') as HTMLTextAreaElement).value).toBe(
+ 'unsent draft'
+ );
+});
+it('cancellation never prompts the agent', async () => {
+ mocks.connect.mockResolvedValue('closed');
+ render(() => (
+ <AgentConnections>
+ <Button />
+ </AgentConnections>
+ ));
+ fireEvent.click(screen.getByRole('button'));
+ await waitFor(() =>
+ expect((screen.getByRole('button') as HTMLButtonElement).disabled).toBe(
+ false
+ )
+ );
+ expect(mocks.issue).not.toHaveBeenCalled();
+});
+it('collaborators cannot connect their account on behalf of the session owner', () => {
+ mocks.viewer = 'collaborator';
+ render(() => (
+ <AgentConnections>
+ <Button />
+ </AgentConnections>
+ ));
+ expect((screen.getByRole('button') as HTMLButtonElement).disabled).toBe(true);
+});
+it('surfaces a rejected continuation', async () => {
+ mocks.connect.mockResolvedValue('connected');
+ mocks.issue.mockResolvedValue({ isErr: () => true });
+ render(() => (
+ <AgentConnections>
+ <Button />
+ </AgentConnections>
+ ));
+ fireEvent.click(screen.getByRole('button'));
+ await waitFor(() => expect(mocks.notify).toHaveBeenCalledOnce());
+});
diff --git a/apps/web/src/features/block-agent/component/AgentConnections.tsx b/apps/web/src/features/block-agent/component/AgentConnections.tsx
new file mode 100644
index 0000000000..32a353a88c
--- /dev/null
+++ b/apps/web/src/features/block-agent/component/AgentConnections.tsx
@@ -0,0 +1,45 @@
+import { toast } from '@core/component/Toast/Toast';
+import { AppConnectionContext } from '@core/pipedream/connection-context';
+import { connectPipedreamApp } from '@queries/pipedream-connectors';
+import type { ParentProps } from 'solid-js';
+import { useAgentSession } from '../context/AgentSessionContext';
+import { createConnectorContinuation } from '../primitives/create-connector-continuation';
+import { promptActionOf } from './prompt-action';
+
+/** Authorization belongs to the session transcript, independently of its draft. */
+export function AgentConnections(props: ParentProps) {
+ const state = useAgentSession();
+ const continuation = createConnectorContinuation({
+ disabled: () =>
+ !state.sessionId() ||
+ state.pending() ||
+ state.loadFailed() ||
+ state.session()?.canEdit !== true ||
+ state.session()?.ownerId !== state.userId() ||
+ state.session()?.isArchived === true ||
+ !['idle', 'disconnected'].includes(state.turn()) ||
+ state.queue.entries().length > 0,
+ revision: () =>
+ `${state.sessionId()}:${state
+ .messages()
+ .map((message) => `${message.turn}:${message.author.kind}`)
+ .join(',')}`,
+ connect: connectPipedreamApp,
+ resume: async (name) => {
+ const result = await state.issue(
+ promptActionOf(
+ `I connected ${name}. Continue my previous request using the newly available tools.`,
+ []
+ )
+ );
+ if (!result || result.isErr())
+ throw new Error('Could not continue the agent session');
+ },
+ notify: (message) => toast.alert(message),
+ });
+ return (
+ <AppConnectionContext.Provider value={continuation}>
+ {props.children}
+ </AppConnectionContext.Provider>
+ );
+}
diff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsx
index 606e0c0eef..eeeeaaea0d 100644
--- a/apps/web/src/features/block-agent/component/Block.tsx
+++ b/apps/web/src/features/block-agent/component/Block.tsx
@@ -33,6 +33,7 @@ import { useAgentSession } from '../context/AgentSessionContext';
import { parseAgentMessageTarget } from '../core/search-location';
import { createAgentRouteTarget } from '../primitives/create-agent-route-target';
import { AgentComposer } from './AgentComposer';
+import { AgentConnections } from './AgentConnections';
import { AgentPreviewBanner } from './AgentPreviewBanner';
import { AgentSessionReadMarker } from './AgentSessionReadMarker';
import { AgentSplitHeader } from './AgentSplitHeader';
@@ -158,7 +159,9 @@ function AgentBlockContent(props: {
{/* The Changes pane opens beside the transcript; closed, the
transcript keeps the whole width. */}
<ChangesSplit>
- <Transcript searchTarget={searchTarget()} />
+ <AgentConnections>
+ <Transcript searchTarget={searchTarget()} />
+ </AgentConnections>
{/* Full-frame mobile: composer + queue float in the bottom
accessory region above the dock; desktop stays inline. */}
<AgentComposerRegion>
diff --git a/apps/web/src/features/block-agent/primitives/create-connector-continuation.test.ts b/apps/web/src/features/block-agent/primitives/create-connector-continuation.test.ts
new file mode 100644
index 0000000000..20bf750a3b
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/create-connector-continuation.test.ts
@@ -0,0 +1,79 @@
+import type { PipedreamConnectOutcome } from '@queries/pipedream-connectors';
+import { createRoot } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import { createConnectorContinuation } from './create-connector-continuation';
+
+function setup() {
+ let finish!: (outcome: PipedreamConnectOutcome) => void;
+ const outcome = new Promise<PipedreamConnectOutcome>((resolve) => {
+ finish = resolve;
+ });
+ const deps = {
+ disabled: () => false,
+ revision: () => 'session:message',
+ connect: vi.fn(() => outcome),
+ resume: vi.fn(async () => {}),
+ notify: vi.fn(),
+ };
+ let dispose!: () => void;
+ const flow = createRoot((cleanup) => {
+ dispose = cleanup;
+ return createConnectorContinuation(deps);
+ });
+ return { deps, flow, finish, dispose };
+}
+const app = { appSlug: 'linear', name: 'Linear' };
+
+describe('connector continuation', () => {
+ it('waits for verified completion and continues exactly once', async () => {
+ const { deps, flow, finish, dispose } = setup();
+ const pending = flow.connect(app);
+ await flow.connect(app);
+ expect(deps.connect).toHaveBeenCalledTimes(1);
+ expect(deps.resume).not.toHaveBeenCalled();
+ finish('connected');
+ await pending;
+ expect(deps.resume).toHaveBeenCalledExactlyOnceWith('Linear');
+ expect(flow.disabled()).toBe(false);
+ dispose();
+ });
+
+ it.each(['closed', 'unsupported'] as const)(
+ 'does not resume after %s',
+ async (outcome) => {
+ const { deps, flow, finish, dispose } = setup();
+ const pending = flow.connect(app);
+ finish(outcome);
+ await pending;
+ expect(deps.resume).not.toHaveBeenCalled();
+ dispose();
+ }
+ );
+
+ it.each(['changed', 'generating', 'unmounted'] as const)(
+ 'does not resume a session that is %s',
+ async (state) => {
+ const { deps, flow, finish, dispose } = setup();
+ const pending = flow.connect(app);
+ if (state === 'changed') deps.revision = () => 'session:new-message';
+ if (state === 'generating') deps.disabled = () => true;
+ if (state === 'unmounted') dispose();
+ finish('connected');
+ await pending;
+ expect(deps.resume).not.toHaveBeenCalled();
+ if (state !== 'unmounted') dispose();
+ }
+ );
+
+ it('reports registration failure without sending a continuation', async () => {
+ const { deps, flow, dispose } = setup();
+ deps.connect = vi.fn(async () => {
+ throw new Error('registration failed');
+ });
+ await flow.connect(app);
+ expect(deps.resume).not.toHaveBeenCalled();
+ expect(deps.notify).toHaveBeenCalledOnce();
+ expect(flow.disabled()).toBe(false);
+ dispose();
+ });
+});
diff --git a/apps/web/src/features/block-agent/primitives/create-connector-continuation.ts b/apps/web/src/features/block-agent/primitives/create-connector-continuation.ts
new file mode 100644
index 0000000000..09855de107
--- /dev/null
+++ b/apps/web/src/features/block-agent/primitives/create-connector-continuation.ts
@@ -0,0 +1,54 @@
+import type { PipedreamConnectOutcome } from '@queries/pipedream-connectors';
+import { createSignal, onCleanup } from 'solid-js';
+
+/** Resume only the agent turn that initiated a successful connection. */
+export function createConnectorContinuation(deps: {
+ disabled: () => boolean;
+ revision: () => string;
+ connect: (app: {
+ appSlug: string;
+ serverName: string;
+ }) => Promise<PipedreamConnectOutcome>;
+ resume: (name: string) => Promise<void>;
+ notify: (message: string) => void;
+}) {
+ const [pending, setPending] = createSignal(false);
+ let disposed = false;
+ onCleanup(() => {
+ disposed = true;
+ });
+ const disabled = () => pending() || deps.disabled();
+
+ async function connect(app: { appSlug: string; name: string }) {
+ if (disposed || disabled()) return;
+ const revision = deps.revision();
+ setPending(true);
+ try {
+ const outcome = await deps.connect({
+ appSlug: app.appSlug,
+ serverName: app.name,
+ });
+ if (disposed) return;
+ if (outcome === 'unsupported') {
+ deps.notify('Connectors are not available on this deployment');
+ return;
+ }
+ if (outcome !== 'connected') return;
+ if (deps.disabled() || revision !== deps.revision()) {
+ deps.notify(
+ `${app.name} connected. Send a message when you are ready to continue.`
+ );
+ return;
+ }
+ await deps.resume(app.name);
+ } catch {
+ if (!disposed)
+ deps.notify(
+ `Could not connect ${app.name} and continue. Please try again.`
+ );
+ } finally {
+ setPending(false);
+ }
+ }
+ return { connect, disabled };
+}
diff --git a/apps/web/src/features/block-agent/state/tool-approval-wording.ts b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
index 551039696c..65660d9cc2 100644
--- a/apps/web/src/features/block-agent/state/tool-approval-wording.ts
+++ b/apps/web/src/features/block-agent/state/tool-approval-wording.ts
@@ -113,6 +113,7 @@ const MACRO_TOOLS: Record<MacroToolName, Wording | null> = {
SaveDatabaseView: (whose) => `save a view in ${whose} databases`,
SearchSkills: (whose) => `search ${whose} skills`,
SearchTools: null,
+ DiscoverConnectors: null,
SelfKnowledge: null,
SendChannelMessage: (whose) => `post a message from ${whose} account`,
SendConfirmedEmail: (whose) => `send email from ${whose} account`,
diff --git a/apps/web/src/lib/core/component/AI/component/tool/DiscoverConnectors.tsx b/apps/web/src/lib/core/component/AI/component/tool/DiscoverConnectors.tsx
new file mode 100644
index 0000000000..4076271969
--- /dev/null
+++ b/apps/web/src/lib/core/component/AI/component/tool/DiscoverConnectors.tsx
@@ -0,0 +1,67 @@
+import CaretRight from '@phosphor-icons/core/regular/caret-right.svg';
+import MagnifyingGlass from '@phosphor-icons/core/regular/magnifying-glass.svg';
+import { createSignal, For, Show } from 'solid-js';
+import { BaseTool } from './BaseTool';
+import { createToolRenderer } from './ToolRenderer';
+
+export const discoverConnectorsHandler = createToolRenderer({
+ name: 'DiscoverConnectors',
+ render: (ctx) => {
+ const [expanded, setExpanded] = createSignal(false);
+ const result = () => ctx.response?.data.result;
+ const entries = () => {
+ const response = result();
+ if (!response) return [];
+ return response.operation === 'search'
+ ? response.apps.map((app) => ({
+ name: app.name,
+ description: app.description,
+ }))
+ : response.tools;
+ };
+ const summary = () => {
+ const response = result();
+ if (!response) return '';
+ return response.operation === 'search'
+ ? `${response.apps.length} apps found${response.more_results ? ' (narrow search for more)' : ''}`
+ : `${response.app.name}: ${response.connected ? 'connected' : 'not connected'} · ${response.tools.length}${response.tools_truncated ? '+' : ''} tools`;
+ };
+ return (
+ <BaseTool
+ icon={MagnifyingGlass}
+ renderContext={ctx.renderContext}
+ type="call"
+ response={
+ <Show when={expanded()}>
+ <ul class="space-y-2 text-xs">
+ <For each={entries()}>
+ {(entry) => (
+ <li>
+ <span class="font-medium">{entry.name}</span>
+ <p class="text-ink-muted">{entry.description}</p>
+ </li>
+ )}
+ </For>
+ </ul>
+ </Show>
+ }
+ >
+ <span class="flex-1">Discover connectors</span>
+ <Show when={ctx.response}>
+ <span class="text-ink-muted text-xs">{summary()}</span>
+ <button
+ type="button"
+ aria-label="Show connector results"
+ aria-expanded={expanded()}
+ onClick={() => setExpanded((value) => !value)}
+ >
+ <CaretRight
+ class="size-4"
+ classList={{ 'rotate-90': expanded() }}
+ />
+ </button>
+ </Show>
+ </BaseTool>
+ );
+ },
+});
diff --git a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
index e66d2730bf..c47cc6309b 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/handler.tsx
@@ -58,6 +58,7 @@ import {
readIllustratorDocumentHandler,
readPhotoshopDocumentHandler,
} from './DesignDocument';
+import { discoverConnectorsHandler } from './DiscoverConnectors';
import { displayResultsHandler } from './DisplayResults';
import {
commentOnDocumentHandler,
@@ -210,6 +211,7 @@ const toolHandlers: ToolHandlerMap<RenderContext> = {
MoveToProject: moveToProjectHandler,
BashCodeExecution: bashCodeExecutionHandler,
DisplayResults: displayResultsHandler,
+ DiscoverConnectors: discoverConnectorsHandler,
ContentSearch: contentSearchHandler,
CreateDocument: createDocumentHandler,
UploadFile: uploadFileHandler,
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx
index 590197c137..0bc9b5f999 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.test.tsx
@@ -67,6 +67,7 @@ vi.mock('@queries/auth/cursor-api-key', () => ({
// than the context object this chip reads its selection from.
vi.mock('../../plugins', () => ({}));
+import { AppConnectionContext } from '@core/pipedream/connection-context';
import { ConnectApp } from './ConnectApp';
beforeEach(() => {
@@ -81,6 +82,49 @@ beforeEach(() => {
});
describe('connect-app chip', () => {
+ it('connects in place when an agent session owns the continuation', () => {
+ const connect = vi.fn(async () => {});
+ render(() => (
+ <AppConnectionContext.Provider value={{ connect, disabled: () => false }}>
+ <ConnectApp
+ appSlug="linear"
+ name="Linear"
+ target="connections"
+ key="node"
+ theme={{}}
+ />
+ </AppConnectionContext.Provider>
+ ));
+ fireEvent.click(screen.getByRole('button', { name: 'Connect Linear' }));
+ expect(connect).toHaveBeenCalledExactlyOnceWith({
+ appSlug: 'linear',
+ name: 'Linear',
+ });
+ expect(mocks.openAgentsPage).not.toHaveBeenCalled();
+ expect(mocks.requestConnectApp).not.toHaveBeenCalled();
+ });
+
+ it('disables connection while the agent session cannot safely continue', () => {
+ const connect = vi.fn(async () => {});
+ render(() => (
+ <AppConnectionContext.Provider value={{ connect, disabled: () => true }}>
+ <ConnectApp
+ appSlug="linear"
+ name="Linear"
+ target="connections"
+ key="node"
+ theme={{}}
+ />
+ </AppConnectionContext.Provider>
+ ));
+ expect(
+ screen
+ .getByRole('button', { name: 'Connect Linear' })
+ .hasAttribute('disabled')
+ ).toBe(true);
+ expect(connect).not.toHaveBeenCalled();
+ });
+
it('sends a Pipedream chip to Connections with the app queued', () => {
render(() => (
<ConnectApp
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx
index f70cded705..8ff1b60607 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/ConnectApp.tsx
@@ -4,6 +4,7 @@ import { HarnessIcon } from '@core/component/HarnessIcon';
import { useSettingsState } from '@core/constant/SettingsState';
import { useUserId } from '@core/context/user';
import { PipedreamConnectorIcon } from '@core/pipedream/ConnectorIcon';
+import { AppConnectionContext } from '@core/pipedream/connection-context';
import { requestConnectApp } from '@core/pipedream/pendingConnect';
import type { ConnectAppDecoratorProps } from '@macro-inc/lexical-core';
import ArrowUpRightIcon from '@phosphor/arrow-up-right.svg';
@@ -29,6 +30,7 @@ export function ConnectApp(props: ConnectAppDecoratorProps) {
}
function ConnectPipedreamApp(props: ConnectAppDecoratorProps) {
+ const inChat = useContext(AppConnectionContext);
const layout = useSplitLayout();
const connections = usePipedreamConnectedSlugs();
return (
@@ -38,7 +40,12 @@ function ConnectPipedreamApp(props: ConnectAppDecoratorProps) {
connections.ready() && connections.slugs().has(props.appSlug)
}
icon={<PipedreamConnectorIcon appSlug={props.appSlug} class="size-3.5" />}
+ disabled={inChat?.disabled}
onConnect={() => {
+ if (inChat) {
+ void inChat.connect({ appSlug: props.appSlug, name: props.name });
+ return;
+ }
// Connections picks this up and starts the Connect flow.
requestConnectApp(props.appSlug);
openAgentsPage(layout, 'connections');
@@ -68,6 +75,7 @@ function ConnectChip(
connected: Accessor<boolean>;
icon: JSX.Element;
onConnect: () => void;
+ disabled?: Accessor<boolean>;
}
) {
const lexicalWrapper = useContext(LexicalWrapperContext);
@@ -87,6 +95,7 @@ function ConnectChip(
return (
<button
type="button"
+ disabled={props.disabled?.()}
data-connect-app={props.appSlug}
data-connect-target={props.target}
aria-label={
diff --git a/apps/web/src/lib/core/pipedream/connect-ui.test.ts b/apps/web/src/lib/core/pipedream/connect-ui.test.ts
new file mode 100644
index 0000000000..92be50c562
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/connect-ui.test.ts
@@ -0,0 +1,70 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { openPipedreamConnectUI } from './connect-ui';
+
+afterEach(() => {
+ document.body.innerHTML = '';
+});
+
+describe('Pipedream Connect events', () => {
+ it('accepts only the current iframe at the exact hosted origin', () => {
+ const onEvent = vi.fn();
+ const ui = openPipedreamConnectUI({
+ token: 'test-token',
+ app: 'linear',
+ onEvent,
+ });
+ const frame = document.querySelector('iframe')!;
+ const data = { type: 'success', authProvisionId: 'apn_test' };
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ origin: 'https://notpipedream.com',
+ source: frame.contentWindow,
+ data,
+ })
+ );
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ origin: 'https://pipedream.com',
+ source: window,
+ data,
+ })
+ );
+ expect(onEvent).not.toHaveBeenCalled();
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ origin: 'https://pipedream.com',
+ source: frame.contentWindow,
+ data,
+ })
+ );
+ expect(onEvent).toHaveBeenCalledExactlyOnceWith({
+ type: 'success',
+ accountId: 'apn_test',
+ });
+ ui.close();
+ expect(document.querySelector('iframe')).toBeNull();
+ });
+
+ it('closing removes the iframe and listener without reporting success', () => {
+ const onEvent = vi.fn();
+ openPipedreamConnectUI({ token: 'test-token', app: 'linear', onEvent });
+ const source = document.querySelector('iframe')!.contentWindow;
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ origin: 'https://pipedream.com',
+ source,
+ data: { type: 'close' },
+ })
+ );
+ expect(onEvent).toHaveBeenCalledExactlyOnceWith({ type: 'close' });
+ expect(document.querySelector('iframe')).toBeNull();
+ window.dispatchEvent(
+ new MessageEvent('message', {
+ origin: 'https://pipedream.com',
+ source,
+ data: { type: 'success', authProvisionId: 'apn_test' },
+ })
+ );
+ expect(onEvent).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/apps/web/src/lib/core/pipedream/connect-ui.ts b/apps/web/src/lib/core/pipedream/connect-ui.ts
index be4836f926..1aa21a0bc9 100644
--- a/apps/web/src/lib/core/pipedream/connect-ui.ts
+++ b/apps/web/src/lib/core/pipedream/connect-ui.ts
@@ -61,8 +61,13 @@ export function openPipedreamConnectUI(options: {
};
const onMessage = (event: MessageEvent) => {
- // The hosted page posts from pipedream.com; ignore everything else.
- if (!String(event.origin).endsWith('pipedream.com')) return;
+ // Only this hosted iframe can complete the flow. A lookalike origin or
+ // another Connect window must not resume the chat waiting on this one.
+ if (
+ event.origin !== new URL(CONNECT_UI_URL).origin ||
+ event.source !== iframe.contentWindow
+ )
+ return;
const data = event.data as
| { type?: string; authProvisionId?: string; error?: string }
| undefined;
diff --git a/apps/web/src/lib/core/pipedream/connection-context.ts b/apps/web/src/lib/core/pipedream/connection-context.ts
new file mode 100644
index 0000000000..50899b13fd
--- /dev/null
+++ b/apps/web/src/lib/core/pipedream/connection-context.ts
@@ -0,0 +1,7 @@
+import { createContext } from 'solid-js';
+
+/** An agent session may handle connection in place and resume its own pending request. */
+export const AppConnectionContext = createContext<{
+ connect: (app: { appSlug: string; name: string }) => Promise<void>;
+ disabled: () => boolean;
+}>();
diff --git a/apps/web/src/lib/queries/pipedream-connectors.test.ts b/apps/web/src/lib/queries/pipedream-connectors.test.ts
new file mode 100644
index 0000000000..a5fc2befc9
--- /dev/null
+++ b/apps/web/src/lib/queries/pipedream-connectors.test.ts
@@ -0,0 +1,78 @@
+import { ok } from 'neverthrow';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ open: vi.fn(),
+ close: vi.fn(),
+ complete: vi.fn(),
+ setData: vi.fn(),
+ invalidate: vi.fn(async () => {}),
+}));
+vi.mock('@core/pipedream/connect-ui', () => ({
+ openPipedreamConnectUI: mocks.open,
+}));
+vi.mock('@queries/client', () => ({
+ queryClient: {
+ setQueryData: mocks.setData,
+ invalidateQueries: mocks.invalidate,
+ },
+}));
+vi.mock('@service-cognition/client', () => ({
+ PIPEDREAM_DISABLED: 'PIPEDREAM_DISABLED',
+ cognitionApiServiceClient: {
+ createPipedreamToken: async () => ok({ token: 'fixture' }),
+ completePipedreamConnection: mocks.complete,
+ },
+}));
+
+import { connectPipedreamApp } from './pipedream-connectors';
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.open.mockImplementation(() => ({ close: mocks.close }));
+});
+
+async function connect() {
+ const pending = connectPipedreamApp({ appSlug: 'linear' });
+ await vi.waitFor(() => expect(mocks.open).toHaveBeenCalledOnce());
+ const event = mocks.open.mock.calls[0][0].onEvent;
+ return { pending, event };
+}
+
+describe('verified Pipedream connection completion', () => {
+ it('reports success only after the requested enabled connection is registered', async () => {
+ mocks.complete.mockResolvedValue(ok({ app_slug: 'linear', enabled: true }));
+ const { pending, event } = await connect();
+ event({ type: 'success', accountId: 'apn_test' });
+ event({ type: 'success', accountId: 'apn_test' });
+ expect(await pending).toBe('connected');
+ expect(mocks.complete).toHaveBeenCalledOnce();
+ expect(mocks.invalidate).toHaveBeenCalledOnce();
+ expect(mocks.close).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ { app_slug: 'slack', enabled: true },
+ { app_slug: 'linear', enabled: false },
+ ])(
+ 'does not report connected for $app_slug with enabled=$enabled',
+ async (connection) => {
+ mocks.complete.mockResolvedValue(ok(connection));
+ const { pending, event } = await connect();
+ const rejected = expect(pending).rejects.toThrow(
+ 'requested connector was not enabled'
+ );
+ event({ type: 'success', accountId: 'apn_test' });
+ await rejected;
+ expect(mocks.setData).not.toHaveBeenCalled();
+ expect(mocks.close).toHaveBeenCalledOnce();
+ }
+ );
+
+ it('cancelling does not register an account', async () => {
+ const { pending, event } = await connect();
+ event({ type: 'close' });
+ expect(await pending).toBe('closed');
+ expect(mocks.complete).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/web/src/lib/queries/pipedream-connectors.ts b/apps/web/src/lib/queries/pipedream-connectors.ts
index 6f3394b0c1..5826ad9913 100644
--- a/apps/web/src/lib/queries/pipedream-connectors.ts
+++ b/apps/web/src/lib/queries/pipedream-connectors.ts
@@ -74,9 +74,9 @@ export function usePipedreamConnectedSlugs(options?: {
const slugs = createMemo<ReadonlySet<string>>(
() =>
new Set(
- (queryReadyGate(query) ? query.data : NO_CONNECTIONS).map(
- (connection) => connection.app_slug
- )
+ (queryReadyGate(query) ? query.data : NO_CONNECTIONS)
+ .filter((connection) => connection.enabled)
+ .map((connection) => connection.app_slug)
)
);
const ready = () => !query.isPlaceholderData && queryReadyGate(query);
@@ -236,6 +236,9 @@ export async function connectPipedreamApp(args: {
server_name: args.serverName,
})
);
+ if (connection.app_slug !== args.appSlug || !connection.enabled) {
+ throw new Error('The requested connector was not enabled');
+ }
upsertConnection(connection);
await invalidateConnections();
resolve('connected');
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index f716ffcfcc..6d94cb0425 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -4005,6 +4005,75 @@ export const ToolDatabaseSchema = z.object({
),
});
+export const DiscoverConnectors = z.object({
+ request: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({ query: z.string(), operation: z.literal('search') }),
+ z.object({ app_slug: z.string(), operation: z.literal('inspect') }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+});
+
+export const DiscoverConnectorsResponse = z.object({
+ result: z.any().superRefine((x, ctx) => {
+ const schemas = [
+ z.object({
+ apps: z.array(
+ z.object({
+ app_slug: z.string(),
+ name: z.string(),
+ description: z.union([z.string(), z.null()]).optional(),
+ })
+ ),
+ more_results: z.boolean(),
+ operation: z.literal('search'),
+ }),
+ z.object({
+ app: z.object({
+ app_slug: z.string(),
+ name: z.string(),
+ description: z.union([z.string(), z.null()]).optional(),
+ }),
+ connected: z.boolean(),
+ tools: z.array(z.object({ name: z.string(), description: z.string() })),
+ tools_truncated: z.boolean(),
+ operation: z.literal('inspect'),
+ }),
+ ];
+ const errors = schemas.reduce<z.ZodError[]>(
+ (errors, schema) =>
+ ((result) => (result.error ? [...errors, result.error] : errors))(
+ schema.safeParse(x)
+ ),
+ []
+ );
+ if (schemas.length - errors.length !== 1) {
+ ctx.addIssue({
+ path: ctx.path,
+ code: 'invalid_union',
+ unionErrors: errors,
+ message: 'Invalid input: Should pass single schema',
+ });
+ }
+ }),
+ connect_markup: z.union([z.string(), z.null()]).optional(),
+});
+
export const DispatchCodingAgent = z
.object({ agent_id: z.string().uuid(), prompt: z.string() })
.strict();
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
index 3f547002a9..a715421c50 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/tool.ts
@@ -95,6 +95,10 @@ type ToolParserMap = {
call: types.DescribeDatabase;
response: types.ToolDatabaseSchema;
};
+ DiscoverConnectors: {
+ call: types.DiscoverConnectors;
+ response: types.DiscoverConnectorsResponse;
+ };
DispatchCodingAgent: {
call: types.DispatchCodingAgent;
response: types.DispatchedCodingAgent;
@@ -453,6 +457,10 @@ const toolParserMap = {
call: schemas.DescribeDatabase,
response: schemas.ToolDatabaseSchema,
},
+ DiscoverConnectors: {
+ call: schemas.DiscoverConnectors,
+ response: schemas.DiscoverConnectorsResponse,
+ },
DispatchCodingAgent: {
call: schemas.DispatchCodingAgent,
response: schemas.DispatchedCodingAgent,
@@ -855,6 +863,10 @@ type ToolDataMap = {
call: types.DescribeDatabase;
response: types.ToolDatabaseSchema;
};
+ DiscoverConnectors: {
+ call: types.DiscoverConnectors;
+ response: types.DiscoverConnectorsResponse;
+ };
DispatchCodingAgent: {
call: types.DispatchCodingAgent;
response: types.DispatchedCodingAgent;
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 1ac6a6551d..81c139a835 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -956,6 +956,55 @@ export type ColumnType =
* A column type as SQL spells it: text, number, boolean, date, link, select, select_number, tag, entity(KIND) or relation, with [] when a select or reference column holds several values (select[], entity(USER)).
*/
export type SpelledColumnType = string;
+/**
+ * Search by app name, then inspect a returned slug before recommending auth.
+ */
+export type DiscoveryRequest =
+ | {
+ /**
+ * App name, e.g. "LinkedIn" or "Linear", not a task description.
+ */
+ query: string;
+ operation: 'search';
+ }
+ | {
+ /**
+ * Exact app slug from search results.
+ */
+ app_slug: string;
+ operation: 'inspect';
+ };
+/**
+ * Discovery results never execute tools or change connections.
+ */
+export type DiscoveryResult =
+ | {
+ /**
+ * Matching apps.
+ */
+ apps: DiscoveredApp[];
+ /**
+ * Narrow the app name if this is true.
+ */
+ more_results: boolean;
+ operation: 'search';
+ }
+ | {
+ app: DiscoveredApp;
+ /**
+ * Whether this caller has an enabled connection.
+ */
+ connected: boolean;
+ /**
+ * Advertised tools. Use SearchTools after connecting to load them.
+ */
+ tools: ConnectorTool[];
+ /**
+ * True when some advertised tools were omitted.
+ */
+ tools_truncated: boolean;
+ operation: 'inspect';
+ };
/**
* Targeted layout operations. Removing placements always retains response columns.
*/
@@ -7358,6 +7407,52 @@ export interface ToolRelation {
*/
tableId: string;
}
+/**
+ * Find an integration when an external app is missing or a workflow requires an unconnected account, including native import tools that need a connector. Use SearchTools for available actions. Search by app name, then inspect a returned app_slug to see its actual tools and connection status. Only recommend connecting if an advertised tool supports the task; an app's name alone is not evidence. Inspection does not load or execute tools. If suitable and unconnected, include the returned connect_markup in your reply and explain what connecting enables. After connection, use SearchTools again in the same agent session to load and call the new tools.
+ */
+export interface DiscoverConnectors {
+ request: DiscoveryRequest;
+}
+/**
+ * Discovery metadata and optional markup for a user-controlled auth flow.
+ */
+export interface DiscoverConnectorsResponse {
+ result: DiscoveryResult;
+ /**
+ * Include verbatim only if an advertised tool supports the requested task.
+ */
+ connect_markup?: string | null;
+}
+/**
+ * A verified app identity from the directory.
+ */
+export interface DiscoveredApp {
+ /**
+ * Exact identity to inspect or connect.
+ */
+ app_slug: string;
+ /**
+ * Human-readable app name.
+ */
+ name: string;
+ /**
+ * Directory description; inspect tools to verify specific capabilities.
+ */
+ description?: string | null;
+}
+/**
+ * An advertised action, not a tool loaded into the current turn.
+ */
+export interface ConnectorTool {
+ /**
+ * Upstream tool name.
+ */
+ name: string;
+ /**
+ * What the action supports.
+ */
+ description: string;
+}
/**
* Start a new coding agent session for a task using an agent returned by ListCodingAgents. Pass a self-contained task with the relevant repository, requirements, findings, and acceptance criteria; the coding agent does not inherit this conversation. Returns a live session reference after its first prompt is accepted, not completed code. Dispatch once per task and do not retry automatically after an uncertain failure.
*/
diff --git a/crates/agent_harness/src/domain/ports.rs b/crates/agent_harness/src/domain/ports.rs
index 82325d25df..d876153fe1 100644
--- a/crates/agent_harness/src/domain/ports.rs
+++ b/crates/agent_harness/src/domain/ports.rs
@@ -390,7 +390,7 @@ pub trait RuntimeConnections: Send + Sync + 'static {
/// A port rather than domain code because both halves are adapter work the
/// domain has no business knowing: signing a JWT needs a key, and enumerating
/// the owner's MCP servers needs their rows. What the domain keeps is *when* -
-/// once, at spawn, for the session's own owner.
+/// at spawn and native turn boundaries, for the session's own owner and policy.
pub trait SandboxEgressProvisioner: Send + Sync + 'static {
/// Internal session tools at an address reachable by an external runtime.
fn external_mcp_servers(
diff --git a/crates/agent_harness/src/domain/service.rs b/crates/agent_harness/src/domain/service.rs
index f917e7c276..b497915652 100644
--- a/crates/agent_harness/src/domain/service.rs
+++ b/crates/agent_harness/src/domain/service.rs
@@ -22,6 +22,7 @@ mod lifecycle;
mod lifecycle_events;
mod open;
mod queue;
+pub mod session_mcp;
mod warm;
use std::sync::Arc;
diff --git a/crates/agent_harness/src/domain/service/session_mcp.rs b/crates/agent_harness/src/domain/service/session_mcp.rs
new file mode 100644
index 0000000000..fd202e42e3
--- /dev/null
+++ b/crates/agent_harness/src/domain/service/session_mcp.rs
@@ -0,0 +1,128 @@
+//! Resolve current connections without changing a session's selected-app policy.
+use crate::domain::{model::SandboxEgress, ports::SandboxEgressProvisioner};
+use agent_egress::domain::model::SessionToken;
+use agent_session::domain::{model::AgentSessionId, ports::AgentSessionRepo};
+
+/// Authenticate the existing session credential and rebuild its permitted list.
+#[tracing::instrument(skip_all, fields(session_id = %id), err)]
+pub async fn refresh<R: AgentSessionRepo, P: SandboxEgressProvisioner>(
+ sessions: &R,
+ provisioner: &P,
+ id: AgentSessionId,
+ token: SessionToken,
+) -> anyhow::Result<SandboxEgress> {
+ let session = sessions
+ .find_by_egress_token_hash(&token.hash())
+ .await?
+ .ok_or_else(|| anyhow::anyhow!("Unknown session credential"))?;
+ anyhow::ensure!(
+ session.id == id && !session.is_archived,
+ "Session is not available for connector refresh"
+ );
+ Ok(provisioner
+ .restore(
+ session.owner_user()?,
+ token.as_str().to_owned(),
+ &session.mcp_servers,
+ )
+ .await?)
+}
+
+#[cfg(test)]
+mod test {
+ use super::*;
+ use crate::domain::{error::Result, model::ProvisionedEgress};
+ use agent_session::{
+ domain::model::AgentMcpServers,
+ testing::{InMemoryAgentSessionRepo, test_agent_session},
+ };
+ use macro_user_id::user_id::MacroUserIdStr;
+ use std::sync::Mutex;
+
+ #[derive(Default)]
+ struct RecordingProvisioner(Mutex<Vec<(String, AgentMcpServers)>>);
+ impl SandboxEgressProvisioner for RecordingProvisioner {
+ async fn provision(
+ &self,
+ _: AgentSessionId,
+ _: &MacroUserIdStr<'static>,
+ _: &AgentMcpServers,
+ ) -> Result<ProvisionedEgress> {
+ panic!("refresh must not mint credentials")
+ }
+ async fn restore(
+ &self,
+ owner: &MacroUserIdStr<'static>,
+ token: String,
+ selection: &AgentMcpServers,
+ ) -> Result<SandboxEgress> {
+ self.0
+ .lock()
+ .unwrap()
+ .push((owner.to_string(), selection.clone()));
+ Ok(SandboxEgress {
+ session_token: token,
+ ..crate::testing::helpers::egress::test_egress()
+ })
+ }
+ }
+
+ #[tokio::test]
+ async fn refresh_preserves_owner_selection_and_credential() {
+ for selection in [
+ AgentMcpServers::OwnerConnections,
+ AgentMcpServers::Selected { servers: vec![] },
+ ] {
+ let repo = InMemoryAgentSessionRepo::new();
+ let mut session = test_agent_session(AgentSessionId::new());
+ session.mcp_servers = selection.clone();
+ let id = session.id;
+ let owner = session.owner_user().unwrap().to_string();
+ repo.insert_session(session);
+ repo.set_egress_token_hash(id, &SessionToken::new("credential").hash())
+ .await
+ .unwrap();
+ let provisioner = RecordingProvisioner::default();
+ let result = refresh(&repo, &provisioner, id, SessionToken::new("credential"))
+ .await
+ .unwrap();
+ assert_eq!(result.session_token, "credential");
+ assert_eq!(*provisioner.0.lock().unwrap(), vec![(owner, selection)]);
+ }
+ }
+
+ #[tokio::test]
+ async fn unknown_mismatched_and_archived_sessions_cannot_refresh() {
+ let repo = InMemoryAgentSessionRepo::new();
+ let mut session = test_agent_session(AgentSessionId::new());
+ let id = session.id;
+ repo.insert_session(session.clone());
+ repo.set_egress_token_hash(id, &SessionToken::new("credential").hash())
+ .await
+ .unwrap();
+ let provisioner = RecordingProvisioner::default();
+ assert!(
+ refresh(&repo, &provisioner, id, SessionToken::new("unknown"))
+ .await
+ .is_err()
+ );
+ assert!(
+ refresh(
+ &repo,
+ &provisioner,
+ AgentSessionId::new(),
+ SessionToken::new("credential")
+ )
+ .await
+ .is_err()
+ );
+ session.is_archived = true;
+ repo.insert_session(session);
+ assert!(
+ refresh(&repo, &provisioner, id, SessionToken::new("credential"))
+ .await
+ .is_err()
+ );
+ assert!(provisioner.0.lock().unwrap().is_empty());
+ }
+}
diff --git a/crates/agent_inmem/src/domain/agent.rs b/crates/agent_inmem/src/domain/agent.rs
index c4d2769284..99dfb1ca36 100644
--- a/crates/agent_inmem/src/domain/agent.rs
+++ b/crates/agent_inmem/src/domain/agent.rs
@@ -136,6 +136,8 @@ pub struct AgentState {
/// The tools of those servers, once dialed; `None` until then or when
/// there were none.
pub mcp_tools: Mutex<Option<RemoteMcpToolSet>>,
+ /// Attached entries retain the credential used to resolve live connections.
+ pub mcp_servers: Mutex<Vec<AcpMcpServer>>,
/// In-flight `connect_mcp` from `session/new` / `session/resume`. The
/// handshake does not join it; the first turn does, so SearchTools still
/// sees the catalog.
@@ -150,7 +152,7 @@ pub struct AgentState {
impl AgentState {
/// Dial the servers a session request carried and keep their tools for
- /// every turn that follows. Started at `session/new`/`session/resume` so
+ /// the next turn. Started at `session/new`/`session/resume` so
/// the handshake is not held by `tools/list`; the first turn joins the
/// same work so SearchTools still has the catalog.
async fn connect_mcp(&self, servers: Vec<AcpMcpServer>) {
@@ -173,6 +175,10 @@ impl AgentState {
/// Start [`Self::connect_mcp`] without joining it. `session/new` and
/// `session/resume` call this so create can return while listing runs.
fn start_connect_mcp(self: &Arc<Self>, servers: Vec<AcpMcpServer>) {
+ *self
+ .mcp_servers
+ .lock()
+ .expect("mcp servers lock should not be poisoned") = servers.clone();
let state = Arc::clone(self);
let handle = tokio::spawn(async move {
state.connect_mcp(servers).await;
@@ -183,9 +189,9 @@ impl AgentState {
.expect("mcp connect lock should not be poisoned") = Some(handle);
}
- /// The tools the next turn should compose, waiting out an in-flight
- /// connect so the searchable catalog is not empty on turn one.
- async fn mcp_tools_for_turn(&self) -> Option<RemoteMcpToolSet> {
+ /// Wait for the initial listing, then refresh permitted connections so
+ /// authorization or disconnection takes effect without a new session.
+ async fn mcp_tools_for_turn(&self) -> anyhow::Result<Option<RemoteMcpToolSet>> {
let handle = self
.mcp_connect
.lock()
@@ -194,10 +200,19 @@ impl AgentState {
if let Some(handle) = handle {
let _ = handle.await;
}
- self.mcp_tools
+ let advertised = self
+ .mcp_servers
+ .lock()
+ .expect("mcp servers lock should not be poisoned")
+ .clone();
+ if let Some(servers) = self.mcp.refresh_dyn(self.session_id, advertised).await? {
+ self.connect_mcp(servers).await;
+ }
+ Ok(self
+ .mcp_tools
.lock()
.expect("mcp tools lock should not be poisoned")
- .clone()
+ .clone())
}
fn expect_session(&self, requested: &SessionId) -> Result<(), AcpError> {
@@ -830,7 +845,7 @@ async fn run_turn(
let mcp_tools = tokio::select! {
biased;
_ = cancel.cancelled() => return Ok(StopReason::Cancelled),
- tools = state.mcp_tools_for_turn() => tools,
+ tools = state.mcp_tools_for_turn() => tools.map_err(|error| AcpError::new(-32603, format!("Could not refresh connector tools: {error}")))?,
};
let TurnInput {
messages,
diff --git a/crates/agent_inmem/src/domain/agent/test.rs b/crates/agent_inmem/src/domain/agent/test.rs
index c8442da504..cc8905e4e4 100644
--- a/crates/agent_inmem/src/domain/agent/test.rs
+++ b/crates/agent_inmem/src/domain/agent/test.rs
@@ -104,6 +104,7 @@ async fn with_model_access<Engine: TurnEngine, Out>(
turn_lock: tokio::sync::Mutex::new(()),
mcp: Arc::new(crate::domain::mcp::NoMcpServers),
mcp_tools: std::sync::Mutex::new(None),
+ mcp_servers: std::sync::Mutex::new(Vec::new()),
mcp_connect: std::sync::Mutex::new(None),
client_renders_forms: AtomicBool::new(false),
enable_dev_commands: true,
@@ -959,6 +960,7 @@ async fn serve_with_mcp(
enable_dev_commands: false,
mcp,
mcp_tools: std::sync::Mutex::new(None),
+ mcp_servers: std::sync::Mutex::new(Vec::new()),
mcp_connect: std::sync::Mutex::new(None),
client_renders_forms: AtomicBool::new(false),
});
@@ -986,6 +988,83 @@ async fn serve_with_mcp(
(connection, session, abort)
}
+#[derive(Default)]
+struct RefreshingConnector {
+ connected: AtomicBool,
+ fail: AtomicBool,
+ asked: std::sync::Mutex<Vec<Vec<String>>>,
+}
+
+impl crate::domain::mcp::McpToolConnector for Arc<RefreshingConnector> {
+ async fn refresh(
+ &self,
+ _: AgentSessionId,
+ advertised: Vec<AcpMcpServer>,
+ ) -> anyhow::Result<Option<Vec<AcpMcpServer>>> {
+ anyhow::ensure!(!self.fail.load(Ordering::SeqCst), "refresh failed");
+ assert!(
+ !advertised.is_empty(),
+ "retain the attached session credential"
+ );
+ let servers = if self.connected.load(Ordering::SeqCst) {
+ vec![AcpMcpServer::Http(
+ agent_client_protocol::schema::v1::McpServerHttp::new(
+ "notion",
+ "https://egress.test/mcp/notion",
+ ),
+ )]
+ } else {
+ vec![]
+ };
+ Ok(Some(servers))
+ }
+ async fn connect(
+ &self,
+ servers: Vec<agent_client_protocol::schema::v1::McpServerHttp>,
+ ) -> Option<RemoteMcpToolSet> {
+ self.asked
+ .lock()
+ .unwrap()
+ .push(servers.into_iter().map(|server| server.name).collect());
+ None
+ }
+}
+
+#[tokio::test]
+async fn each_turn_refreshes_newly_connected_apps_without_recreating_the_session() {
+ let connector = Arc::new(RefreshingConnector::default());
+ let state = Arc::new(AgentState {
+ session_id: AgentSessionId::new(),
+ owner: model_owner::Owner::User(MacroUserIdStr::try_from_email("[email protected]").unwrap()),
+ engine: Arc::new(ScriptedEngine::new(vec![])),
+ admission: Arc::new(DisabledAiAdmissionService),
+ model_access: Arc::new(crate::testing::TestModelAccess::paid()),
+ store: Arc::new(SessionStore::new()),
+ active_cancel: std::sync::Mutex::new(Vec::new()),
+ turn_lock: tokio::sync::Mutex::new(()),
+ enable_dev_commands: false,
+ mcp: Arc::new(connector.clone()),
+ mcp_tools: std::sync::Mutex::new(None),
+ mcp_servers: std::sync::Mutex::new(Vec::new()),
+ mcp_connect: std::sync::Mutex::new(None),
+ client_renders_forms: AtomicBool::new(false),
+ });
+ state.start_connect_mcp(test_mcp_servers());
+ state.mcp_tools_for_turn().await.unwrap();
+ assert!(connector.asked.lock().unwrap().last().unwrap().is_empty());
+ connector.connected.store(true, Ordering::SeqCst);
+ state.mcp_tools_for_turn().await.unwrap();
+ assert_eq!(
+ connector.asked.lock().unwrap().last().unwrap(),
+ &vec!["notion".to_string()]
+ );
+ connector.connected.store(false, Ordering::SeqCst);
+ state.mcp_tools_for_turn().await.unwrap();
+ assert!(connector.asked.lock().unwrap().last().unwrap().is_empty());
+ connector.fail.store(true, Ordering::SeqCst);
+ assert!(state.mcp_tools_for_turn().await.is_err());
+}
+
/// The servers `session/new` carries are dialed in the background, minus
/// Macro's own, whose tools this runtime already has natively.
#[tokio::test]
@@ -1015,6 +1094,7 @@ async fn session_new_dials_the_advertised_servers_except_macros_own() {
enable_dev_commands: false,
mcp: Arc::new(Arc::clone(&spy)),
mcp_tools: std::sync::Mutex::new(None),
+ mcp_servers: std::sync::Mutex::new(Vec::new()),
mcp_connect: std::sync::Mutex::new(None),
client_renders_forms: AtomicBool::new(false),
});
@@ -1104,6 +1184,7 @@ async fn first_prompt_waits_for_background_mcp_connect() {
enable_dev_commands: false,
mcp: Arc::new(Arc::clone(&connector)),
mcp_tools: std::sync::Mutex::new(None),
+ mcp_servers: std::sync::Mutex::new(Vec::new()),
mcp_connect: std::sync::Mutex::new(None),
client_renders_forms: AtomicBool::new(false),
});
@@ -1208,6 +1289,7 @@ where
client_renders_forms: AtomicBool::new(false),
mcp: Arc::new(crate::domain::mcp::NoMcpServers),
mcp_tools: std::sync::Mutex::new(None),
+ mcp_servers: std::sync::Mutex::new(Vec::new()),
mcp_connect: std::sync::Mutex::new(None),
enable_dev_commands,
});
diff --git a/crates/agent_inmem/src/domain/mcp.rs b/crates/agent_inmem/src/domain/mcp.rs
index a37f732ffd..be3cf6f61b 100644
--- a/crates/agent_inmem/src/domain/mcp.rs
+++ b/crates/agent_inmem/src/domain/mcp.rs
@@ -9,8 +9,21 @@
//! app they have not connected with a result the model can act on.
use agent_client_protocol::schema::v1::{McpServer as AcpMcpServer, McpServerHttp};
+use agent_session::domain::model::AgentSessionId;
+use futures::future::BoxFuture;
use mcp_toolset::RemoteMcpToolSet;
+/// Resolves the session's current permitted servers before a new turn.
+pub trait SessionMcpSource: Send + Sync + 'static {
+ /// The advertised list carries the existing session credential. Implementations
+ /// must resolve its owner and policy before adding any connected app.
+ fn servers<'a>(
+ &'a self,
+ session: AgentSessionId,
+ advertised: Vec<AcpMcpServer>,
+ ) -> std::pin::Pin<Box<dyn Future<Output = anyhow::Result<Vec<AcpMcpServer>>> + Send + 'a>>;
+}
+
#[cfg(test)]
mod test;
@@ -49,6 +62,14 @@ pub fn dialable_servers(servers: Vec<AcpMcpServer>) -> Vec<McpServerHttp> {
/// A port because it is transport work: the production adapter speaks
/// streamable HTTP through the egress proxy, tests hand back nothing.
pub trait McpToolConnector: Send + Sync + 'static {
+ /// Refresh supported runtimes; other connectors retain their attached list.
+ fn refresh(
+ &self,
+ _session: AgentSessionId,
+ _advertised: Vec<AcpMcpServer>,
+ ) -> impl Future<Output = anyhow::Result<Option<Vec<AcpMcpServer>>>> + Send {
+ async { Ok(None) }
+ }
/// Connect to every server, skipping any that fail, and return the tools
/// found. `None` when no server yielded any tool.
///
@@ -70,6 +91,12 @@ pub trait McpToolConnector: Send + Sync + 'static {
/// Erased form of [`McpToolConnector`] for storage on the agent state.
pub trait DynMcpToolConnector: Send + Sync + 'static {
+ /// See [`McpToolConnector::refresh`].
+ fn refresh_dyn(
+ &self,
+ session: AgentSessionId,
+ advertised: Vec<AcpMcpServer>,
+ ) -> BoxFuture<'_, anyhow::Result<Option<Vec<AcpMcpServer>>>>;
/// See [`McpToolConnector::connect`].
fn connect_dyn(
&self,
@@ -81,6 +108,13 @@ pub trait DynMcpToolConnector: Send + Sync + 'static {
}
impl<C: McpToolConnector> DynMcpToolConnector for C {
+ fn refresh_dyn(
+ &self,
+ session: AgentSessionId,
+ advertised: Vec<AcpMcpServer>,
+ ) -> BoxFuture<'_, anyhow::Result<Option<Vec<AcpMcpServer>>>> {
+ Box::pin(self.refresh(session, advertised))
+ }
fn connect_dyn(
&self,
servers: Vec<McpServerHttp>,
diff --git a/crates/agent_inmem/src/outbound/acp_mcp.rs b/crates/agent_inmem/src/outbound/acp_mcp.rs
index 1fffcb1d4e..3f35f17bf9 100644
--- a/crates/agent_inmem/src/outbound/acp_mcp.rs
+++ b/crates/agent_inmem/src/outbound/acp_mcp.rs
@@ -70,6 +70,7 @@ fn place_header(name: &str, value: &str) -> Option<HeaderPlacement> {
pub struct AcpMcpConnector<Client> {
client: Client,
pool: Arc<ServerPool>,
+ source: Option<Arc<dyn crate::domain::mcp::SessionMcpSource>>,
}
impl<Client> AcpMcpConnector<Client>
@@ -92,7 +93,17 @@ where
}
});
}
- Self { client, pool }
+ Self {
+ client,
+ pool,
+ source: None,
+ }
+ }
+
+ /// Refresh the session's permitted app list before each native turn.
+ pub fn with_source(mut self, source: Arc<dyn crate::domain::mcp::SessionMcpSource>) -> Self {
+ self.source = Some(source);
+ self
}
/// The pooled session for `server`, dialing it only when this connector
@@ -177,6 +188,16 @@ impl<Client> McpToolConnector for AcpMcpConnector<Client>
where
Client: StreamableHttpClient + Send + Sync,
{
+ async fn refresh(
+ &self,
+ session: agent_session::domain::model::AgentSessionId,
+ advertised: Vec<agent_client_protocol::schema::v1::McpServer>,
+ ) -> anyhow::Result<Option<Vec<agent_client_protocol::schema::v1::McpServer>>> {
+ match &self.source {
+ Some(source) => source.servers(session, advertised).await.map(Some),
+ None => Ok(None),
+ }
+ }
#[tracing::instrument(
skip_all,
fields(
diff --git a/crates/agent_inmem/src/outbound/manager.rs b/crates/agent_inmem/src/outbound/manager.rs
index 475f01ed02..0112ce95af 100644
--- a/crates/agent_inmem/src/outbound/manager.rs
+++ b/crates/agent_inmem/src/outbound/manager.rs
@@ -185,6 +185,7 @@ impl InMemAgentManager {
turn_lock: tokio::sync::Mutex::new(()),
mcp: Arc::clone(&self.mcp),
mcp_tools: std::sync::Mutex::new(None),
+ mcp_servers: std::sync::Mutex::new(Vec::new()),
mcp_connect: std::sync::Mutex::new(None),
client_renders_forms: AtomicBool::new(false),
enable_dev_commands: self.enable_dev_commands,
diff --git a/crates/agent_session/src/domain/model.rs b/crates/agent_session/src/domain/model.rs
index c7ac60b389..3505fabe9c 100644
--- a/crates/agent_session/src/domain/model.rs
+++ b/crates/agent_session/src/domain/model.rs
@@ -178,9 +178,9 @@ pub enum SessionStatus {
}
/// Which Pipedream MCP servers a session is handed: the agent's own choice,
-/// snapshotted onto the session at creation like `instructions`. The ACP
-/// agent is given its server list once per attach and cannot refresh it, so
-/// the snapshot is what every later attach re-advertises; editing the agent
+/// snapshotted onto the session at creation like `instructions`. The native
+/// runtime refreshes connections within this policy before each turn. Other
+/// ACP runtimes receive the list on attach; editing the agent's selection
/// applies to its next session.
pub use bots::domain::models::{AgentMcpServer, AgentMcpServers};
diff --git a/crates/ai_tools/src/build_context.rs b/crates/ai_tools/src/build_context.rs
index 61d2a82996..116dbda2d1 100644
--- a/crates/ai_tools/src/build_context.rs
+++ b/crates/ai_tools/src/build_context.rs
@@ -499,6 +499,10 @@ pub async fn build_tool_service_context_from_env(
let recorder = ai_usage::pg_recorder_with_enforcement(pool.clone(), enforcement);
Ok(ToolServiceContext {
+ connector_tool_context: crate::tool_context::build_connector_tool_context(
+ pool.clone(),
+ crate::mcp_app_catalog::pipedream_client_from_env()?,
+ ),
search_service_client: search_client.clone(),
email_service_client: email_ext_client,
soup_service,
diff --git a/crates/ai_tools/src/lib.rs b/crates/ai_tools/src/lib.rs
index eb82dddd8c..30d01f6aad 100644
--- a/crates/ai_tools/src/lib.rs
+++ b/crates/ai_tools/src/lib.rs
@@ -96,6 +96,7 @@ pub use tool_context::{
build_task_properties_adapter, build_team_calendar_tool_context, build_team_repository,
build_team_tool_context,
};
+pub use tool_context::{ToolConnectorToolContext, build_connector_tool_context};
#[cfg(any(test, feature = "test-support"))]
pub use tool_context::{build_image_generation_tool_context_test, no_op_schedule_context};
pub type AiToolSet = AsyncToolCollection<ToolServiceContext>;
@@ -203,6 +204,7 @@ pub const EAGER_TOOLS: &[&str] = &[
"ContentSearch",
"CreateDocument",
"DisplayResults",
+ "DiscoverConnectors",
"EditDocument",
"GetThread",
"ListEntities",
@@ -261,6 +263,15 @@ pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {
}
AiHost::ChannelBot | AiHost::Mcp => toolset,
};
+ // Connector discovery belongs to agent sessions. Their runtime refreshes
+ // the permitted connector list before the next turn after authorization.
+ let toolset = match host {
+ AiHost::AgentSession => toolset.add_tool::<
+ pipedream_mcp::inbound::toolset::DiscoverConnectors,
+ ToolConnectorToolContext,
+ >(),
+ AiHost::Chat | AiHost::ChannelBot | AiHost::Mcp => toolset,
+ };
// External MCP clients have no `LoadTools`, so they get every schema.
let deferred = match host {
AiHost::Chat | AiHost::AgentSession | AiHost::ChannelBot => {
@@ -299,7 +310,7 @@ pub fn tools_for(host: AiHost) -> ToolSetWithPrompt {
/// sent to AI providers.
pub fn all_tool_frontend_schemas() -> FrontendSchemas {
frontend_schemas_builder()
- .merge(&tools_for(AiHost::Chat))
+ .merge(&tools_for(AiHost::AgentSession))
.merge(&read::read_thread())
.build()
}
diff --git a/crates/ai_tools/src/mcp_app_catalog.rs b/crates/ai_tools/src/mcp_app_catalog.rs
index f0880ae45c..fb079baaa2 100644
--- a/crates/ai_tools/src/mcp_app_catalog.rs
+++ b/crates/ai_tools/src/mcp_app_catalog.rs
@@ -23,6 +23,8 @@ maybe_env_var! {
PipedreamEnvironment,
/// Base URL of the Pipedream API.
PipedreamApiUrl,
+ /// Base URL of the Pipedream MCP server, shared with execution.
+ PipedreamMcpUrl,
}
}
@@ -69,7 +71,12 @@ pub fn pipedream_client_from_env() -> anyhow::Result<Option<Arc<PipedreamClient>
environment,
allowed_origins: Vec::new(),
api_url,
- mcp_url: DEFAULT_MCP_URL.to_owned(),
+ mcp_url: env
+ .pipedream_mcp_url
+ .as_ref()
+ .and_then(|value| value.value())
+ .unwrap_or(DEFAULT_MCP_URL)
+ .to_owned(),
})
.context("building Pipedream client for MCP app lookup")?;
Ok(Some(Arc::new(client)))
diff --git a/crates/ai_tools/src/test.rs b/crates/ai_tools/src/test.rs
index 97206c1d69..9c23255eb1 100644
--- a/crates/ai_tools/src/test.rs
+++ b/crates/ai_tools/src/test.rs
@@ -15,6 +15,25 @@
use super::*;
use ai_toolset::ToolSet as _;
+#[test]
+fn connector_discovery_is_eager_only_in_agent_sessions() {
+ assert!(EAGER_TOOLS.contains(&"DiscoverConnectors"));
+ assert!(
+ tools_for(AiHost::AgentSession)
+ .toolset
+ .tools
+ .contains_key("DiscoverConnectors")
+ );
+ for host in [AiHost::Chat, AiHost::ChannelBot, AiHost::Mcp] {
+ assert!(
+ !tools_for(host)
+ .toolset
+ .tools
+ .contains_key("DiscoverConnectors")
+ );
+ }
+}
+
#[test]
fn subagent_toolset_passes_schema_validation() {
let tools = subagent_toolset();
@@ -213,15 +232,15 @@ fn the_agent_session_host_keeps_chats_user_tools_with_the_review_prompt() {
assert!(prompt.contains("review card"));
assert!(!prompt.contains("PendingUserExecution"));
assert_eq!(
- session
- .toolset
- .request_schemas()
- .map(|schemas| schemas.len()),
+ session.toolset.request_schemas().map(|schemas| schemas
+ .into_iter()
+ .filter(|schema| schema.name != "DiscoverConnectors")
+ .count()),
tools_for(AiHost::Chat)
.toolset
.request_schemas()
.map(|schemas| schemas.len()),
- "the same tools as chat"
+ "the same tools as chat except agent-session connector discovery"
);
}
@@ -281,6 +300,10 @@ fn frontend_schemas_build() {
assert!(names.insert(name), "duplicate frontend tool: {name}");
}
assert!(names.contains("QueryDatabase"));
+ assert!(names.contains("DiscoverConnectors"));
+ for name in tools_for(AiHost::Chat).toolset.tools.keys() {
+ assert!(names.contains(name.as_str()), "missing chat tool: {name}");
+ }
for name in [
"CreateDatabase",
"CreateTable",
@@ -419,7 +442,7 @@ fn the_mcp_host_defers_nothing() {
#[test]
fn every_eager_tool_exists() {
- let tools = tools_for(AiHost::Chat);
+ let tools = tools_for(AiHost::AgentSession);
for name in EAGER_TOOLS {
assert!(
tools.toolset.tools.contains_key(*name),
diff --git a/crates/ai_tools/src/tool_context.rs b/crates/ai_tools/src/tool_context.rs
index 23b69fb4a0..4cceaa84a4 100644
--- a/crates/ai_tools/src/tool_context.rs
+++ b/crates/ai_tools/src/tool_context.rs
@@ -1602,6 +1602,8 @@ pub fn no_op_schedule_context() -> RoutineToolContext {
/// Individual tools should extract only the clients they need via `FromRef`.
#[derive(Clone, FromRef)]
pub struct ToolServiceContext {
+ /// Read-only discovery of connectors the caller has not yet authorized.
+ pub connector_tool_context: ToolConnectorToolContext,
pub search_service_client: Arc<search_service_client::SearchServiceClient>,
pub email_service_client: Arc<email_service_client::EmailServiceClientExternal>,
pub soup_service: Arc<ToolSoupService>,
@@ -1651,6 +1653,27 @@ pub struct ToolServiceContext {
pub usage_context: ai_usage::UsageContext,
}
+/// Pipedream discovery dependencies shared by chat tools.
+pub type ToolConnectorToolContext = pipedream_mcp::inbound::toolset::ConnectorToolContext<
+ pipedream_mcp::outbound::api::PipedreamClient,
+ pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo,
+>;
+
+/// Wire connector discovery at the composition boundary.
+pub fn build_connector_tool_context(
+ pool: sqlx::PgPool,
+ client: Option<Arc<pipedream_mcp::outbound::api::PipedreamClient>>,
+) -> ToolConnectorToolContext {
+ pipedream_mcp::inbound::toolset::ConnectorToolContext {
+ service: Arc::new(
+ pipedream_mcp::domain::service::discovery::ConnectorDiscovery::new(
+ client,
+ Arc::new(pipedream_mcp::outbound::pg_connection_repo::PgConnectionRepo::new(pool)),
+ ),
+ ),
+ }
+}
+
impl FromRef<ToolServiceContext> for AnthropicToolContext {
fn from_ref(context: &ToolServiceContext) -> Self {
let mut tools = context.anthropic_tool_context.clone();
diff --git a/crates/pipedream_mcp/Cargo.toml b/crates/pipedream_mcp/Cargo.toml
index f1bbdb549d..6fa0d89f9b 100644
--- a/crates/pipedream_mcp/Cargo.toml
+++ b/crates/pipedream_mcp/Cargo.toml
@@ -7,6 +7,7 @@ publish = false
[dependencies]
ai_toolset = { path = "../ai_toolset" }
anyhow.workspace = true
+async-trait.workspace = true
axum.workspace = true
futures.workspace = true
macro_authorization = { path = "../macro_authorization", default-features = false, features = [
@@ -24,6 +25,7 @@ serde_json.workspace = true
sqlx.workspace = true
thiserror.workspace = true
tracing.workspace = true
+tokio.workspace = true
utoipa.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/pipedream_mcp/src/domain/ports.rs b/crates/pipedream_mcp/src/domain/ports.rs
index 90b703cb6c..3eaf0283e0 100644
--- a/crates/pipedream_mcp/src/domain/ports.rs
+++ b/crates/pipedream_mcp/src/domain/ports.rs
@@ -111,3 +111,13 @@ pub trait ConnectorDirectory: Send + Sync + 'static {
app_slug: &str,
) -> impl Future<Output = anyhow::Result<Option<CatalogEntry>>> + Send;
}
+
+/// Read an app's advertised capabilities without invoking any of its tools.
+pub trait ConnectorCapabilities: Send + Sync + 'static {
+ /// List tools, including for apps this user has not connected yet.
+ fn tools(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ app_slug: &str,
+ ) -> impl Future<Output = anyhow::Result<Vec<super::service::discovery::ConnectorTool>>> + Send;
+}
diff --git a/crates/pipedream_mcp/src/domain/service/discovery.rs b/crates/pipedream_mcp/src/domain/service/discovery.rs
new file mode 100644
index 0000000000..c2f07549e3
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/service/discovery.rs
@@ -0,0 +1,149 @@
+//! Read-only discovery of apps and their actual MCP capabilities.
+
+use crate::domain::{
+ models::MacroUserIdStr,
+ ports::{ConnectionStore, ConnectorCapabilities, ConnectorDirectory},
+};
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+
+#[cfg(test)]
+mod test;
+
+const MAX_TOOLS: usize = 100;
+
+/// Search by app name, then inspect a returned slug before recommending auth.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[serde(tag = "operation", rename_all = "snake_case")]
+pub enum DiscoveryRequest {
+ /// Find connectable apps by name.
+ Search {
+ /// App name, e.g. "LinkedIn" or "Linear", not a task description.
+ query: String,
+ },
+ /// Verify capabilities and connection status for one catalog app.
+ Inspect {
+ /// Exact app slug from search results.
+ app_slug: String,
+ },
+}
+
+/// An advertised action, not a tool loaded into the current turn.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct ConnectorTool {
+ /// Upstream tool name.
+ pub name: String,
+ /// What the action supports.
+ pub description: String,
+}
+
+/// A verified app identity from the directory.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DiscoveredApp {
+ /// Exact identity to inspect or connect.
+ pub app_slug: String,
+ /// Human-readable app name.
+ pub name: String,
+ /// Directory description; inspect tools to verify specific capabilities.
+ pub description: Option<String>,
+}
+
+/// Discovery results never execute tools or change connections.
+#[derive(Debug, Serialize, JsonSchema)]
+#[serde(tag = "operation", rename_all = "snake_case")]
+pub enum DiscoveryResult {
+ /// Candidate apps; none has had its capabilities verified yet.
+ Search {
+ /// Matching apps.
+ apps: Vec<DiscoveredApp>,
+ /// Narrow the app name if this is true.
+ more_results: bool,
+ },
+ /// Verified identity, capabilities and this caller's connection status.
+ Inspect {
+ /// App from the directory.
+ app: DiscoveredApp,
+ /// Whether this caller has an enabled connection.
+ connected: bool,
+ /// Advertised tools. Use SearchTools after connecting to load them.
+ tools: Vec<ConnectorTool>,
+ /// True when some advertised tools were omitted.
+ tools_truncated: bool,
+ },
+}
+
+/// Orchestrates discovery through directory, capability, and connection ports.
+pub struct ConnectorDiscovery<D, S> {
+ directory: Option<Arc<D>>,
+ connections: Arc<S>,
+}
+
+impl<D: ConnectorDirectory + ConnectorCapabilities, S: ConnectionStore> ConnectorDiscovery<D, S> {
+ /// An absent directory makes unconfigured deployments fail explicitly.
+ pub fn new(directory: Option<Arc<D>>, connections: Arc<S>) -> Self {
+ Self {
+ directory,
+ connections,
+ }
+ }
+
+ /// Scope connection status to the authenticated caller. Inspection only
+ /// lists metadata; it neither grants access nor invokes an app action.
+ #[tracing::instrument(skip_all, err)]
+ pub async fn discover(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ request: &DiscoveryRequest,
+ ) -> anyhow::Result<DiscoveryResult> {
+ let Some(directory) = &self.directory else {
+ anyhow::bail!("Connector discovery is not configured on this deployment");
+ };
+ match request {
+ DiscoveryRequest::Search { query } => {
+ if 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?;
+ 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 {
+ anyhow::bail!("No connectable app has that slug; search the catalog first");
+ };
+ let connected = self
+ .connections
+ .load(user_id, &app.app_slug)
+ .await
+ .map_err(|error| {
+ anyhow::anyhow!("Could not check connector status: {error:?}")
+ })?
+ .is_some_and(|connection| connection.enabled);
+ let mut tools = directory.tools(user_id, &app.app_slug).await?;
+ let tools_truncated = tools.len() > MAX_TOOLS;
+ tools.truncate(MAX_TOOLS);
+ Ok(DiscoveryResult::Inspect {
+ app: app.into(),
+ connected,
+ tools,
+ tools_truncated,
+ })
+ }
+ }
+ }
+}
+
+impl From<crate::domain::models::CatalogEntry> for DiscoveredApp {
+ fn from(app: crate::domain::models::CatalogEntry) -> Self {
+ Self {
+ app_slug: app.app_slug,
+ name: app.display_name,
+ description: app.description,
+ }
+ }
+}
diff --git a/crates/pipedream_mcp/src/domain/service/discovery/test.rs b/crates/pipedream_mcp/src/domain/service/discovery/test.rs
new file mode 100644
index 0000000000..8af7e12f9f
--- /dev/null
+++ b/crates/pipedream_mcp/src/domain/service/discovery/test.rs
@@ -0,0 +1,221 @@
+use super::*;
+use crate::domain::models::{CatalogEntry, CatalogPage, PipedreamConnection};
+use std::sync::Mutex;
+
+struct Directory {
+ fail_tools: bool,
+ tool_count: usize,
+ seen: Mutex<Vec<String>>,
+}
+
+fn entry() -> CatalogEntry {
+ CatalogEntry {
+ app_slug: "linear".into(),
+ display_name: "Linear".into(),
+ description: None,
+ icon_url: None,
+ }
+}
+
+impl ConnectorDirectory for Directory {
+ async fn search(
+ &self,
+ search: Option<&str>,
+ _cursor: Option<&str>,
+ limit: u32,
+ ) -> anyhow::Result<CatalogPage> {
+ assert_eq!(search, Some("Linear"));
+ assert_eq!(limit, 10);
+ Ok(CatalogPage {
+ entries: vec![entry()],
+ next_cursor: Some("next".into()),
+ })
+ }
+ async fn retrieve(&self, slug: &str) -> anyhow::Result<Option<CatalogEntry>> {
+ Ok((slug == "linear").then(entry))
+ }
+}
+
+impl ConnectorCapabilities for Directory {
+ async fn tools(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ slug: &str,
+ ) -> anyhow::Result<Vec<ConnectorTool>> {
+ self.seen.lock().unwrap().push(user.to_string());
+ assert_eq!(slug, "linear");
+ if self.fail_tools {
+ anyhow::bail!("upstream unavailable");
+ }
+ Ok((0..self.tool_count)
+ .map(|i| ConnectorTool {
+ name: format!("tool_{i}"),
+ description: "Find issues".into(),
+ })
+ .collect())
+ }
+}
+
+struct Store {
+ enabled: Option<bool>,
+ seen: Mutex<Vec<String>>,
+}
+impl ConnectionStore for Store {
+ type Err = String;
+ async fn save(&self, _: &PipedreamConnection) -> Result<(), String> {
+ panic!("discovery must not write")
+ }
+ async fn delete(&self, _: &MacroUserIdStr<'static>, _: &str) -> Result<(), String> {
+ panic!("discovery must not delete")
+ }
+ async fn list(&self, _: &MacroUserIdStr<'static>) -> Result<Vec<PipedreamConnection>, String> {
+ panic!("inspect only the requested app")
+ }
+ async fn load(
+ &self,
+ user: &MacroUserIdStr<'static>,
+ slug: &str,
+ ) -> Result<Option<PipedreamConnection>, String> {
+ self.seen.lock().unwrap().push(user.to_string());
+ Ok(self.enabled.map(|enabled| PipedreamConnection {
+ user_id: user.clone(),
+ app_slug: slug.into(),
+ server_name: "Linear".into(),
+ account_id: "account".into(),
+ enabled,
+ }))
+ }
+}
+
+fn service(
+ enabled: Option<bool>,
+ fail_tools: bool,
+ tool_count: usize,
+) -> ConnectorDiscovery<Directory, Store> {
+ ConnectorDiscovery::new(
+ Some(Arc::new(Directory {
+ fail_tools,
+ tool_count,
+ seen: Mutex::default(),
+ })),
+ Arc::new(Store {
+ enabled,
+ seen: Mutex::default(),
+ }),
+ )
+}
+fn user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+fn inspect(slug: &str) -> DiscoveryRequest {
+ DiscoveryRequest::Inspect {
+ app_slug: slug.into(),
+ }
+}
+
+#[tokio::test]
+async fn search_is_bounded_and_does_not_read_accounts_or_tools() {
+ let svc = service(None, false, 1);
+ let result = svc
+ .discover(
+ &user(),
+ &DiscoveryRequest::Search {
+ query: " Linear ".into(),
+ },
+ )
+ .await
+ .unwrap();
+ assert!(matches!(
+ result,
+ DiscoveryResult::Search {
+ more_results: true,
+ ..
+ }
+ ));
+ assert!(svc.connections.seen.lock().unwrap().is_empty());
+ assert!(
+ svc.directory
+ .as_ref()
+ .unwrap()
+ .seen
+ .lock()
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn inspection_scopes_status_and_capabilities_to_caller() {
+ for enabled in [None, Some(false), Some(true)] {
+ let svc = service(enabled, false, 1);
+ let DiscoveryResult::Inspect {
+ connected, tools, ..
+ } = svc.discover(&user(), &inspect("linear")).await.unwrap()
+ else {
+ panic!("inspection expected")
+ };
+ assert_eq!(connected, enabled == Some(true));
+ assert_eq!(tools[0].description, "Find issues");
+ assert_eq!(*svc.connections.seen.lock().unwrap(), [user().to_string()]);
+ assert_eq!(
+ *svc.directory.as_ref().unwrap().seen.lock().unwrap(),
+ [user().to_string()]
+ );
+ }
+}
+
+#[tokio::test]
+async fn invented_slug_is_rejected_before_account_or_capability_lookup() {
+ let svc = service(None, false, 1);
+ assert!(svc.discover(&user(), &inspect("invented")).await.is_err());
+ assert!(svc.connections.seen.lock().unwrap().is_empty());
+ assert!(
+ svc.directory
+ .as_ref()
+ .unwrap()
+ .seen
+ .lock()
+ .unwrap()
+ .is_empty()
+ );
+}
+
+#[tokio::test]
+async fn capability_failure_is_not_misrepresented_as_supported() {
+ assert!(
+ service(None, true, 1)
+ .discover(&user(), &inspect("linear"))
+ .await
+ .is_err()
+ );
+}
+
+#[tokio::test]
+async fn large_capability_lists_report_truncation() {
+ let result = service(None, false, 101)
+ .discover(&user(), &inspect("linear"))
+ .await
+ .unwrap();
+ let DiscoveryResult::Inspect {
+ tools,
+ tools_truncated,
+ ..
+ } = result
+ else {
+ panic!("inspection expected")
+ };
+ assert_eq!(tools.len(), MAX_TOOLS);
+ assert!(tools_truncated);
+}
+
+#[tokio::test]
+async fn unconfigured_deployments_and_empty_searches_fail_explicitly() {
+ let mut svc = service(None, false, 0);
+ assert!(
+ svc.discover(&user(), &DiscoveryRequest::Search { query: " ".into() })
+ .await
+ .is_err()
+ );
+ svc.directory = None;
+ assert!(svc.discover(&user(), &inspect("linear")).await.is_err());
+}
diff --git a/crates/pipedream_mcp/src/domain/service/mod.rs b/crates/pipedream_mcp/src/domain/service/mod.rs
index bf04315320..6e37998dd9 100644
--- a/crates/pipedream_mcp/src/domain/service/mod.rs
+++ b/crates/pipedream_mcp/src/domain/service/mod.rs
@@ -2,6 +2,8 @@
pub mod catalog;
/// Completion and revocation of Pipedream connections.
pub mod connect;
+/// Discover suitable connectors before asking a user to authorize them.
+pub mod discovery;
/// The Pipedream MCP tool set.
pub mod toolset;
diff --git a/crates/pipedream_mcp/src/inbound/mod.rs b/crates/pipedream_mcp/src/inbound/mod.rs
index 706dfa0d6d..1a8b701e41 100644
--- a/crates/pipedream_mcp/src/inbound/mod.rs
+++ b/crates/pipedream_mcp/src/inbound/mod.rs
@@ -1,4 +1,6 @@
/// Axum HTTP adapter for Pipedream MCP connector management.
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};
diff --git a/crates/pipedream_mcp/src/inbound/toolset.rs b/crates/pipedream_mcp/src/inbound/toolset.rs
new file mode 100644
index 0000000000..ff8ec56292
--- /dev/null
+++ b/crates/pipedream_mcp/src/inbound/toolset.rs
@@ -0,0 +1,91 @@
+//! Thin AI adapter for connector discovery.
+
+use crate::domain::{
+ ports::{ConnectionStore, ConnectorCapabilities, ConnectorDirectory},
+ service::discovery::{ConnectorDiscovery, DiscoveryRequest, DiscoveryResult},
+};
+use ai_toolset::{
+ AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
+ ToolResult,
+};
+use async_trait::async_trait;
+use schemars::JsonSchema;
+use serde::{Deserialize, Serialize};
+use std::sync::Arc;
+
+/// Dependencies for the discovery tool.
+pub struct ConnectorToolContext<D, S> {
+ /// Domain service, constructed by the host.
+ pub service: Arc<ConnectorDiscovery<D, S>>,
+}
+
+impl<D, S> Clone for ConnectorToolContext<D, S> {
+ fn clone(&self) -> Self {
+ Self {
+ service: self.service.clone(),
+ }
+ }
+}
+
+/// Discover apps when the current tools cannot perform the user's task.
+#[derive(Debug, Deserialize, JsonSchema)]
+#[schemars(
+ title = "DiscoverConnectors",
+ description = "Find an integration when an external app is missing or a workflow requires an unconnected account, including native import tools that need a connector. Use SearchTools for available actions. Search by app name, then inspect a returned app_slug to see its actual tools and connection status. Only recommend connecting if an advertised tool supports the task; an app's name alone is not evidence. Inspection does not load or execute tools. If suitable and unconnected, include the returned connect_markup in your reply and explain what connecting enables. After connection, use SearchTools again in the same agent session to load and call the new tools."
+)]
+pub struct DiscoverConnectors {
+ /// Search for an app, or inspect a catalog result's actual capabilities.
+ pub request: DiscoveryRequest,
+}
+
+/// Discovery metadata and optional markup for a user-controlled auth flow.
+#[derive(Debug, Serialize, JsonSchema)]
+pub struct DiscoverConnectorsResponse {
+ /// Catalog or capability results.
+ pub result: DiscoveryResult,
+ /// Include verbatim only if an advertised tool supports the requested task.
+ pub connect_markup: Option<String>,
+}
+
+impl ToolAnnotated for DiscoverConnectors {
+ const ANNOTATIONS: ToolAnnotations = ToolAnnotations::read_only("Discover connectors");
+}
+
+#[async_trait]
+impl<D: ConnectorDirectory + ConnectorCapabilities, S: ConnectionStore>
+ AsyncTool<ConnectorToolContext<D, S>> for DiscoverConnectors
+{
+ type Output = DiscoverConnectorsResponse;
+
+ #[tracing::instrument(skip_all, err)]
+ async fn call(
+ &self,
+ context: ServiceContext<ConnectorToolContext<D, S>>,
+ request: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ let result = context
+ .service
+ .discover(&request.user_id, &self.request)
+ .await
+ .map_err(|error| ToolCallError {
+ description: error.to_string(),
+ internal_error: error,
+ })?;
+ let connect_markup = match &result {
+ DiscoveryResult::Inspect {
+ app,
+ connected: false,
+ tools,
+ ..
+ } if !tools.is_empty() => {
+ let payload = serde_json::json!({"appSlug": app.app_slug, "name": app.name});
+ Some(format!("<m-connect-app>{payload}</m-connect-app>"))
+ }
+ _ => None,
+ };
+ Ok(DiscoverConnectorsResponse {
+ result,
+ connect_markup,
+ })
+ }
+}
diff --git a/crates/pipedream_mcp/src/outbound/api.rs b/crates/pipedream_mcp/src/outbound/api.rs
index ae145a05e2..3281b67a85 100644
--- a/crates/pipedream_mcp/src/outbound/api.rs
+++ b/crates/pipedream_mcp/src/outbound/api.rs
@@ -13,6 +13,8 @@ use std::sync::Mutex;
use std::time::{Duration, Instant};
use url::Url;
+mod capabilities;
+
/// Default base URL of the Pipedream REST API.
pub const DEFAULT_API_URL: &str = "https://api.pipedream.com";
diff --git a/crates/pipedream_mcp/src/outbound/api/capabilities.rs b/crates/pipedream_mcp/src/outbound/api/capabilities.rs
new file mode 100644
index 0000000000..5a06e12534
--- /dev/null
+++ b/crates/pipedream_mcp/src/outbound/api/capabilities.rs
@@ -0,0 +1,46 @@
+use super::PipedreamClient;
+use crate::domain::{
+ models::{MacroUserIdStr, PipedreamConnection},
+ ports::{ConnectorCapabilities, McpConnection},
+ service::discovery::ConnectorTool,
+};
+use std::time::Duration;
+
+#[cfg(test)]
+mod test;
+
+impl ConnectorCapabilities for PipedreamClient {
+ #[tracing::instrument(skip_all, err)]
+ async fn tools(
+ &self,
+ user_id: &MacroUserIdStr<'static>,
+ app_slug: &str,
+ ) -> anyhow::Result<Vec<ConnectorTool>> {
+ // Pipedream exposes tools/list before user auth. This session is used
+ // only for discovery, never tools/call, and carries no account grant.
+ let record = PipedreamConnection {
+ user_id: user_id.clone(),
+ app_slug: app_slug.to_owned(),
+ server_name: app_slug.to_owned(),
+ account_id: String::new(),
+ enabled: false,
+ };
+ 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"))?
+ }
+}
diff --git a/crates/pipedream_mcp/src/outbound/api/capabilities/test.rs b/crates/pipedream_mcp/src/outbound/api/capabilities/test.rs
new file mode 100644
index 0000000000..ad617476a9
--- /dev/null
+++ b/crates/pipedream_mcp/src/outbound/api/capabilities/test.rs
@@ -0,0 +1,73 @@
+use super::*;
+use crate::outbound::api::PipedreamConfig;
+use axum::{
+ Json, Router,
+ extract::State,
+ http::{HeaderMap, StatusCode},
+ response::IntoResponse,
+ routing::post,
+};
+use serde_json::{Value, json};
+use std::sync::{Arc, Mutex};
+
+async fn mcp(
+ State(calls): State<Arc<Mutex<Vec<String>>>>,
+ headers: HeaderMap,
+ Json(body): Json<Value>,
+) -> axum::response::Response {
+ assert_eq!(headers["x-pd-external-user-id"], "macro|[email protected]");
+ assert_eq!(headers["x-pd-app-slug"], "linear");
+ 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":"find_issues","description":"Find Linear issues","inputSchema":{"type":"object","properties":{}}}]})
+ }
+ other => panic!("Discovery must never invoke a tool: {other}"),
+ };
+ Json(json!({"jsonrpc":"2.0","id":body["id"],"result":result})).into_response()
+}
+
+#[tokio::test]
+async fn discovery_uses_real_mcp_handshake_without_executing_tools() {
+ let calls = Arc::new(Mutex::new(Vec::new()));
+ let app = Router::new()
+ .route(
+ "/v1/oauth/token",
+ post(|| async { Json(json!({"access_token":"fixture","expires_in":3600})) }),
+ )
+ .route("/mcp", post(mcp))
+ .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 = PipedreamClient::new(PipedreamConfig {
+ client_id: "fixture".into(),
+ client_secret: "fixture".into(),
+ project_id: "fixture".into(),
+ environment: "development".into(),
+ allowed_origins: vec![],
+ api_url: format!("http://{address}"),
+ mcp_url: format!("http://{address}/mcp"),
+ })
+ .unwrap();
+ let tools = client
+ .tools(
+ &MacroUserIdStr::try_from_email("[email protected]").unwrap(),
+ "linear",
+ )
+ .await
+ .unwrap();
+ assert_eq!(tools.len(), 1);
+ assert_eq!(tools[0].name, "find_issues");
+ assert_eq!(tools[0].description, "Find Linear issues");
+ assert_eq!(
+ *calls.lock().unwrap(),
+ ["initialize", "notifications/initialized", "tools/list"]
+ );
+ server.abort();
+}
diff --git a/crates/prompt/src/agent_session.rs b/crates/prompt/src/agent_session.rs
index 42b1f03b28..f2f3a7ebf8 100644
--- a/crates/prompt/src/agent_session.rs
+++ b/crates/prompt/src/agent_session.rs
@@ -10,6 +10,7 @@ static INSTRUCTIONS: &str = r##"You are a Macro agent working inside an agent se
- Be concise and directly useful. Respond in Markdown.
- When you reference a Macro document, channel, chat, project, task, email thread, calendar event, person, date/time, agent session, or other mentionable chip, emit the matching XML mention tag (see the mentioning rules). Those tags render as clickable chips in the session and in the channel thread. Do not use plain Markdown links or bare names for Macro items.
- You have no shell and no filesystem. Everything you can do, you do through the tools you are given.
+- When a request needs an external app (for example, "import my Notion docs"), use SearchTools for its actions. If the app is missing or a workflow needs an unconnected account, use DiscoverConnectors to search for the app and inspect its actual capabilities and connection status. This also applies when a native import tool exists but requires that app's connection. For a suitable unconnected app, include the returned connect_markup and tell the owner to connect to continue; do not substitute instructions to find Settings or ask for document URLs before resolving the missing connection. After authorization the session resumes automatically, and SearchTools can load the refreshed tools. Never claim an app supports an action merely because its name matches.
- Work autonomously: nobody can approve intermediate questions mid-turn, so make reasonable assumptions, state them briefly, and proceed.
- Every prompt opens with a private context block naming the session's owner, whose access you act with, and who sent the prompt. Follow its note on what a prompt from someone else may do.
"##;
diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rs
index 97a44dffa2..f4766eeeb7 100644
--- a/crates/prompt/src/mentions.rs
+++ b/crates/prompt/src/mentions.rs
@@ -67,7 +67,7 @@ Date/time chips do not need a looked-up id. `date` is an ISO 8601 datetime; `dis
Agent session chips reference an existing session by id from a tool result. An empty `label` is fine. Set `"expanded":true` to insert the card (Magic Chip) that follows the session's latest turn instead of the compact underlined title. Do not invent session ids.
-If a tool result tells you an app is not connected for the person you are working for and hands you a `<m-connect-app>{"appSlug":"...","name":"..."}</m-connect-app>` tag, include that tag verbatim in your reply: it renders as a button that connects the app. Never invent one; only repeat the tag a tool result gave you. End that reply by asking them to let you know once they have connected the app so you can try again.
+If a tool result tells you an app is not connected for the person you are working for and hands you a `<m-connect-app>{"appSlug":"...","name":"..."}</m-connect-app>` tag, include that tag verbatim in your reply: it renders as a button that connects the app. Never invent one; only repeat the tag a tool result gave you. In agent sessions, where `DiscoverConnectors` is available, the button resumes the conversation after a successful connection; tell the user to connect to continue, without asking for a separate confirmation message. In other hosts, ask them to let you know once they have connected the app so you can try again.
Only the tag formats listed here can be mentioned. Never invent a tag name or put an id in the wrong tag. A calendar itself is NOT a mentionable entity: never put a `calendarId` (e.g. from ListCalendars) in a mention tag — the frontend cannot resolve it and renders a broken chip. Refer to a calendar by name in plain text and mention only individual events on it. The same goes for any other id with no mention format listed here: plain text, never an improvised tag.
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index a6b50eb626..5bf5e48720 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -5,6 +5,29 @@ User-sent messages in chat and agent transcripts use an ink-colored bubble with
lighter bubble with the normal text palette. Preview Markdown and controls at
`/app/debug/ui?ui=invert-util` under **User-sent AI message**.
+## Connecting an app from an agent session
+
+When existing tools cannot handle a request, agent sessions can use
+`DiscoverConnectors` to search Pipedream by app name and inspect an app's actual
+tool list. Expand the discovery row to see the results. An app name alone does
+not establish that the requested action is supported.
+
+For a suitable unconnected app, the assistant offers **Connect <app>**. Clicking
+it opens the hosted authorization flow over the agent transcript. After the
+backend verifies and registers the connection, the agent session sends a visible
+continuation message in the same conversation. The native Macro runtime refreshes
+the session’s permitted connector tools before the next turn. The unsent draft
+is preserved. Closing authorization or a failed registration sends no message.
+If the conversation changed or was closed during auth, there is no automatic
+continuation; the connected app remains available for the next request.
+
+Verify with an unconnected app: inspect its tools, click Connect, cancel once,
+then complete authorization and check that exactly one continuation appears and
+the assistant can discover the app's tools. Also verify a disabled connection
+does not display as connected. Regular AI chat does not expose discovery or
+automatic continuation. A selected-app agent keeps its configured MCP scope;
+authorization does not add apps outside that scope.
+
## Checking first-response latency
From outside an editor, press `c`, then `a`, type a prompt, and press Enter.
diff --git a/services/agent_harness_service/Cargo.toml b/services/agent_harness_service/Cargo.toml
index 6434eafc6b..d425998f49 100644
--- a/services/agent_harness_service/Cargo.toml
+++ b/services/agent_harness_service/Cargo.toml
@@ -17,6 +17,7 @@ name = "agent_harness_service_doppler_config"
path = "src/doppler_config.rs"
[dependencies]
+agent-client-protocol.workspace = true
ai_billing = { path = "../../crates/ai_billing", features = ["pg-admission"] }
roles_and_permissions = { path = "../../crates/roles_and_permissions", default-features = false, features = ["outbound"] }
teams = { path = "../../crates/teams", default-features = false, features = ["outbound"] }
diff --git a/services/agent_harness_service/src/main.rs b/services/agent_harness_service/src/main.rs
index 51c24b44d3..db9b8e51f0 100644
--- a/services/agent_harness_service/src/main.rs
+++ b/services/agent_harness_service/src/main.rs
@@ -21,6 +21,7 @@ mod model_providers;
mod permission_policy;
mod routine_sessions;
mod runtime_commands;
+mod session_mcp;
mod trigger;
#[cfg(test)]
@@ -501,10 +502,17 @@ async fn run() -> anyhow::Result<()> {
// server's session for the life of the egress token, so a replaced agent
// task and the catalog's listing reuse the handshake instead of opening
// a second set of clients and dropping them when the listing ends.
- let mcp_connector = Arc::new(AcpMcpConnector::new(EgressMcpClient::new(
- Arc::clone(&egress),
- &egress_base_url,
- )));
+ let mcp_connector = Arc::new(
+ AcpMcpConnector::new(EgressMcpClient::new(Arc::clone(&egress), &egress_base_url))
+ .with_source(Arc::new(session_mcp::SessionConnectors {
+ sessions: session_repo.clone(),
+ provisioner: Arc::new(EgressProvisioner::new(
+ Arc::clone(&mcp_connections),
+ Arc::clone(&mcp_servers),
+ &egress_base_url,
+ )),
+ })),
+ );
let tool_catalog: Arc<dyn agent_session::domain::ports::SessionToolCatalog> =
Arc::new(McpToolCatalog::new(Arc::clone(&mcp_connector)));
let sessions = sessions.with_tool_catalog(Arc::clone(&tool_catalog));
diff --git a/services/agent_harness_service/src/session_mcp.rs b/services/agent_harness_service/src/session_mcp.rs
new file mode 100644
index 0000000000..46736978f4
--- /dev/null
+++ b/services/agent_harness_service/src/session_mcp.rs
@@ -0,0 +1,48 @@
+//! Adapt the native runtime's advertised credential to the harness refresh use case.
+use agent_client_protocol::schema::v1::McpServer;
+use agent_egress::domain::model::SessionToken;
+use agent_harness::domain::ports::SandboxEgressProvisioner;
+use agent_inmem::domain::mcp::SessionMcpSource;
+use agent_session::domain::{model::AgentSessionId, ports::AgentSessionRepo};
+use std::{pin::Pin, sync::Arc};
+
+pub struct SessionConnectors<R, P> {
+ pub sessions: R,
+ pub provisioner: Arc<P>,
+}
+
+impl<R: AgentSessionRepo, P: SandboxEgressProvisioner> SessionMcpSource
+ for SessionConnectors<R, P>
+{
+ fn servers<'a>(
+ &'a self,
+ session: AgentSessionId,
+ advertised: Vec<McpServer>,
+ ) -> Pin<Box<dyn Future<Output = anyhow::Result<Vec<McpServer>>> + Send + 'a>> {
+ Box::pin(async move {
+ let token = advertised
+ .iter()
+ .find_map(|server| match server {
+ McpServer::Http(server)
+ if server.name == agent_inmem::domain::mcp::MACRO_MCP_NAME =>
+ {
+ server
+ .headers
+ .iter()
+ .find(|header| header.name.eq_ignore_ascii_case("authorization"))
+ .and_then(|header| header.value.strip_prefix("Bearer "))
+ }
+ _ => None,
+ })
+ .ok_or_else(|| anyhow::anyhow!("Session MCP credential is missing"))?;
+ let egress = agent_harness::domain::service::session_mcp::refresh(
+ &self.sessions,
+ self.provisioner.as_ref(),
+ session,
+ SessionToken::new(token.to_owned()),
+ )
+ .await?;
+ Ok(egress.acp_servers())
+ })
+ }
+}
diff --git a/services/document_cognition_service/src/api/context/test.rs b/services/document_cognition_service/src/api/context/test.rs
index e63b25778c..5aca068c04 100644
--- a/services/document_cognition_service/src/api/context/test.rs
+++ b/services/document_cognition_service/src/api/context/test.rs
@@ -482,6 +482,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
);
let tool_service_context = ai_tools::ToolServiceContext {
+ connector_tool_context: ai_tools::build_connector_tool_context(pool.clone(), None),
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
soup_service: soup_service.clone(),
diff --git a/services/document_cognition_service/src/server.rs b/services/document_cognition_service/src/server.rs
index 7d5659e476..acd3f42d2a 100644
--- a/services/document_cognition_service/src/server.rs
+++ b/services/document_cognition_service/src/server.rs
@@ -713,6 +713,7 @@ pub async fn run() -> anyhow::Result<()> {
);
let tool_service_context = ai_tools::ToolServiceContext {
+ connector_tool_context: ai_tools::build_connector_tool_context(db.clone(), None),
search_service_client: search_service_client.clone(),
email_service_client: email_service_client_external.clone(),
soup_service: soup_service.clone(),
diff --git a/services/mcp_service/src/context.rs b/services/mcp_service/src/context.rs
index de56c577dc..76ce494252 100644
--- a/services/mcp_service/src/context.rs
+++ b/services/mcp_service/src/context.rs
@@ -452,6 +452,7 @@ async fn build_tool_context(args: ToolContextBuildArgs<'_>) -> anyhow::Result<To
ai_usage::pg_recorder_with_enforcement(db.clone(), config.enable_ai_usage_enforcement);
let tool_context = ToolServiceContext {
+ connector_tool_context: ai_tools::build_connector_tool_context(db.clone(), None),
email_service_client: Arc::new(EmailServiceClientExternal::new(
email_service_client.url().to_owned(),
)),