Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

fix(agents): stop asking twice for the same account while building an agent (#15669)

Hazem Adelf9b950e47ae9
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.md
index ada33e12d83..733c54b9d06 100644
--- a/brain/knowledge/ai-intelligence/ai-agents.md
+++ b/brain/knowledge/ai-intelligence/ai-agents.md
@@ -84,7 +84,7 @@ Paths verified 2026-07-17. An earlier version pointed at `packages/core/shared/s
- **Embeddings are stored at a fixed 768 dimensions, and most models do not return that.** `text-embedding-3-small` answers 1536, and the `dimensions` provider option is namespaced under `openai`, so the OpenRouter and managed paths never see it. `aiUtils.toStorageEmbedding` truncates and re-normalises instead, which is what the option does server-side and works whatever the provider returns. This only holds for Matryoshka-trained models — adding a model that is not one will truncate badly and silently.
- **Saving a saved agent publishes it.** `POST /v1/agents/:id` sets `goLive: true` unless the body says otherwise, so an ordinary save copies the draft over the published snapshot. There is no separate publish step in the UI, deliberately: two versions with no history means nobody can say which one a linked flow runs. The consequence is easy to trip over in tests and callers — anything that needs `draft` to differ from `published` has to write the row directly (`db.update('agent', id, { draft })`) or pass `goLive: false`, which is what the Test tab uses to stage a change it can run without shipping it. A test that edited the draft through the API to prove "a flow runs the published copy" was quietly moving the copy it was asserting about, and it only started failing when the save-publishes change merged from another branch.
-- **`ap_add_agent_tools` will save a tool with no connection pinned.** `connectionExternalId` is optional, so a tool the AI adds without one carries no `predefinedInput.auth` for good. The visible symptom is a connection picker card on *every* conversation with that agent, which reads as the card being broken or the credential expiring — it is neither. The agent has nothing to use, so it asks, and the answer only ever lands on the run (`__store_selected_connection` writes a map the agent tool set does not read), so the next conversation asks again. Fixing the card is the wrong end: pin a connection when the tool is created, and write a chosen or repaired one back into `draft.tools` via `editDraftTools`.
+- **`ap_add_agent_tools` will save a tool with no connection pinned.** `connectionExternalId` is optional, so a tool the AI adds without one carries no `predefinedInput.auth` for good. The visible symptom is a connection picker card on *every* conversation with that agent, which reads as the card being broken or the credential expiring — it is neither. The agent has nothing to use, so it asks, and the answer only ever lands on the run (`__store_selected_connection` writes a map the agent tool set does not read), so the next conversation asks again. Fixing the card is the wrong end: pin a connection when the tool is created, and write a chosen or repaired one back into `draft.tools` via `editDraftTools`. The same gap shows up one turn apart inside a single conversation: `selectedConnectionByPiece` is rebuilt empty per run in `execute-agent-run.ts`, and the picker's only skip check reads `piecesTheAuthorGaveAnAccount`, which is built empty unless `source === AgentRunSource.AGENT`. So on the chat surface the card re-asked for an account the user had picked ninety seconds earlier. The durable copy was already being written; nothing read it back. The picker now asks the server for it through `__get_selected_connection` and seeds the in-memory map from the answer, which fixes auth injection across turns too. Scope that skip to `ap_show_connection_picker` and nothing else: `ap_show_connection_required` is the reconnect card (`status: 'error'`), so refusing it because a selection exists would make a broken connection unrepairable, which is the one case the prompt insists must always be fixable inline. The picker takes `switchAccount` for when the user wants a different account. Leave the older `accountAlreadyChosenFor` refusal alone while you are in there: it fires only when a saved agent runs on a connection its author pinned, and it deliberately blocks both switching and reconnecting, because the card offers "use a different account" and the person chatting with someone else's agent should not be able to repoint that credential. Compose the two guards at the call site rather than nesting one inside the other, or a reviewer reads the pre-existing rule as part of the new one.
- **An agent asked to change itself will send back the entire system prompt as its new brief.** `ap_update_agent` replaces the instructions rather than patching them, so the note tells the agent to read its current brief first. On an agent run that brief is the *top* of the system prompt and every run note is appended under it, and the model reads "your current instructions above" as the whole message: a 183 character brief came back as 3,156, carrying the capabilities note, the connection guidance and the self-edit note itself, which would then be appended again on the next run and grow every turn. `agentSurfaceNotes.stripRunNotes` cuts the payload at the first run-note heading and both write paths go through it. It needs a heading on its own line and two of them present, because a hand-written brief may legitimately contain one of those strings and truncating it silently is worse than the pollution.
- **The taint flag must be set where the tool's `execute` is built, not where the group is assembled.** `TaintState` is one mutable object per job, and the two readers are the action-preview gate and the refusal to change a saved agent after a read. Three paths reached the model without marking, each because it joined the tool set past the policy: the provider's native web search, the flow step's MCP tools (merged in `run(stepMcpToolSet)`), and the conversation MCP set (through `agentMcpClient.withToolTimeouts`). Set it in `withToolTimeouts` and the configured-tool factories, before awaiting, so a same-batch call cannot slip through. Plugin-mode provider search (`AI_PROVIDER_CAPABILITIES[...].webSearch === 'plugin'`, OpenRouter and the managed provider) injects results with **no tool call at all**, so there is nothing to wrap and it is suppressed on any run that can reach the self-edit tools. A server-reported mark would not help here: MCP reads never touch the API, so the worker would be vouching for itself.
- **A step only persists the inputs its pinned piece version declares.** `validateProps` in `flow-version-validator-util.ts` builds `cleanInput` from `Object.keys(propsSchema.shape)`, so any key the pinned version does not know is dropped on save with no error. This bit the agent picker: `AgentLink` rendered on every Run Agent step, but `agentId` only exists from `@activepieces/[email protected]`, so on an older pinned step linking looked like it worked and was gone on reload. Anything that writes a new prop from a custom component has to gate on that prop being in the step's `selectedAction.props`, not on a plan flag. Two dev-environment corollaries: `packages/web` consumes `@activepieces/core-piece-types` from its **built dist**, so a branch that adds an enum member needs that package rebuilt before web typechecks, and the API caches dev piece metadata in memory, so a piece version bump needs the API restarted before the builder pins the new version. **You cannot fake the new version locally to test the prop**: inserting the row into `piece_metadata` by hand works for a few minutes and then `pieceSyncService` reconciles the table against the published registry and deletes a version that is not there, so the builder goes back to pinning the old one. A prop added to a piece is only exercisable end to end in the builder once that piece version is actually published, which is why the linked-step behaviour is pinned by `agent-run-link.test.ts` at the API level rather than by a browser pass.
diff --git a/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts b/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts
index 6acd40c44a7..520b368d50f 100644
--- a/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts
+++ b/packages/server/api/src/app/ee/agent/rpc/tool-execution-rpc.ts
@@ -239,6 +239,14 @@ export const toolExecutionRpc = (log: FastifyBaseLogger) => ({
log.info({ flow: { id: flowId }, hasWrites: writeSteps.length > 0, writeStepCount: writeSteps.length }, '[agentRpc#executeAgentTool] Flow write check')
return { result: { hasWrites: writeSteps.length > 0, flowName: flow.version.displayName, writeSteps } }
}
+ if (input.toolName === '__get_selected_connection') {
+ const { pieceName } = input.toolInput
+ if (typeof input.conversationId === 'string' && typeof pieceName === 'string') {
+ const selected = await agentApprovalGate.getSelectedConnection({ conversationId: input.conversationId, pieceName })
+ return { result: selected }
+ }
+ return { result: null }
+ }
if (input.toolName === '__get_available_connections') {
const { pieceName } = input.toolInput
if (typeof input.conversationId === 'string' && typeof pieceName === 'string') {
@@ -273,7 +281,7 @@ export const toolExecutionRpc = (log: FastifyBaseLogger) => ({
const MAX_APPROVAL_BLOCK_MS = 50_000
const CHAT_ONLY_TOOL_PREFIX = '__'
const OWNER_SCOPED_TOOLS = ['ap_remember']
-const ATTENDED_STATE_TOOLS = ['__cancel_check', '__approval_wait', '__store_pending_gate', '__store_selected_connection']
+const ATTENDED_STATE_TOOLS = ['__cancel_check', '__approval_wait', '__store_pending_gate', '__store_selected_connection', '__get_selected_connection']
const SOURCE_EXTRA_TOOLS: Partial<Record<AgentRunSource, readonly string[]>> = {
[AgentRunSource.AGENT_BUILDER]: AGENT_SURFACE_TOOLS,
[AgentRunSource.AGENT]: AGENT_SELF_EDIT_TOOLS,
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
index ee569479d54..6f24b37da96 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/execute-agent-run.ts
@@ -616,6 +616,25 @@ function buildToolSet({ ctx, eventEmitter, log, phaseState, taintState, mcpToolS
waitForApproval,
displayToolTimeoutMs: DISPLAY_TOOL_TIMEOUT_MS,
accountAlreadyChosenFor: (pieceName) => piecesTheAuthorGaveAnAccount.has(pieceName),
+ connectionChosenEarlierFor: async (pieceName) => {
+ const inThisRun = selectedConnectionByPiece.get(pieceName)
+ if (!isNil(inThisRun)) {
+ return { externalId: inThisRun, label: inThisRun }
+ }
+ const { data: stored } = await tryCatch(() => ctx.apiClient.executeAgentTool({
+ toolName: '__get_selected_connection',
+ toolInput: { pieceName },
+ platformId, userId, source, conversationId,
+ }))
+ const selected = stored?.result
+ if (!isObject(selected) || typeof selected['externalId'] !== 'string') {
+ return null
+ }
+ const externalId = selected['externalId']
+ const label = selected['label']
+ selectedConnectionByPiece.set(pieceName, externalId)
+ return { externalId, label: typeof label === 'string' ? label : externalId }
+ },
onConnectionSelected: async ({ pieceName, connectionExternalId, label, projectId: connProjectId }) => {
selectedConnectionByPiece.set(pieceName, connectionExternalId)
await tryCatch(() => ctx.apiClient.executeAgentTool({
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/display-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/display-tools.ts
index e57d508410c..3cd39a715fb 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/display-tools.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/display-tools.ts
@@ -3,13 +3,14 @@ import { tool, ToolExecutionOptions, ToolSet } from 'ai'
import { z } from 'zod'
import { GateDecision, gateNoResponseMessage, normalizePieceName, questionTextSchema, questionTitleSchema, richOptionSchema } from './tool-primitives'
-export function createDisplayTools({ waitForApproval, displayToolTimeoutMs, onConnectionSelected, onConnectorReconnected, onGateOpened, accountAlreadyChosenFor }: {
+export function createDisplayTools({ waitForApproval, displayToolTimeoutMs, onConnectionSelected, onConnectorReconnected, onGateOpened, accountAlreadyChosenFor, connectionChosenEarlierFor }: {
waitForApproval: (params: { gateId: string, timeoutMs?: number }) => Promise<GateDecision>
displayToolTimeoutMs: number
onConnectionSelected?: (params: { pieceName: string, connectionExternalId: string, label: string, projectId: string }) => Promise<void>
onConnectorReconnected?: (connectorUuid: string) => void
onGateOpened?: (params: { gateId: string, toolName: string, displayName: string, toolInput: Record<string, unknown> }) => Promise<void>
accountAlreadyChosenFor?: (pieceName: string) => boolean
+ connectionChosenEarlierFor?: (pieceName: string) => Promise<{ externalId: string, label: string } | null>
}): ToolSet {
function refuseIfAccountAlreadyChosen(input: Record<string, unknown>): { content: { type: string, text: string }[] } | undefined {
const piece = typeof input['piece'] === 'string' ? input['piece'] : ''
@@ -20,16 +21,29 @@ export function createDisplayTools({ waitForApproval, displayToolTimeoutMs, onCo
return { content: [{ type: 'text', text: `This agent already runs on the ${displayName} account its author chose, so there is nothing to connect or reconnect here and this card was not shown. Use the ${displayName} tool. If it fails, say exactly what failed — do not describe it as a connection problem unless the failure says the credentials were rejected.` }] }
}
+ async function refuseIfPickedEarlierInConversation(input: Record<string, unknown>): Promise<{ content: { type: string, text: string }[] } | undefined> {
+ if (input['switchAccount'] === true) {
+ return undefined
+ }
+ const piece = typeof input['piece'] === 'string' ? input['piece'] : ''
+ const chosenEarlier = isNil(connectionChosenEarlierFor) ? null : await connectionChosenEarlierFor(normalizePieceName(piece))
+ if (isNil(chosenEarlier)) {
+ return undefined
+ }
+ const displayName = typeof input['displayName'] === 'string' ? input['displayName'] : piece
+ return { content: [{ type: 'text', text: `The user already picked the ${displayName} account "${chosenEarlier.label}" earlier in this conversation, so the card was not shown again. Use connectionExternalId "${chosenEarlier.externalId}" and carry on without asking. If they ask to use a different account, call this again with switchAccount true.` }] }
+ }
+
function blockingExecute({ dismissMessage, successKey, toolName, getDisplayName, onApproved, refuseWhen }: {
dismissMessage: string | ((input: Record<string, unknown>) => string)
successKey?: string
toolName: string
getDisplayName?: (input: Record<string, unknown>) => string
onApproved?: (params: { input: Record<string, unknown>, payload?: Record<string, unknown> }) => Promise<Record<string, unknown>>
- refuseWhen?: (input: Record<string, unknown>) => { content: { type: string, text: string }[] } | undefined
+ refuseWhen?: (input: Record<string, unknown>) => { content: { type: string, text: string }[] } | undefined | Promise<{ content: { type: string, text: string }[] } | undefined>
}) {
return async (input: Record<string, unknown>, options: ToolExecutionOptions<undefined>) => {
- const refusal = refuseWhen?.(input)
+ const refusal = await refuseWhen?.(input)
if (!isNil(refusal)) {
return refusal
}
@@ -113,10 +127,11 @@ export function createDisplayTools({ waitForApproval, displayToolTimeoutMs, onCo
inputSchema: z.object({
piece: z.string().describe('Piece short name'),
displayName: z.string().describe('Human-readable piece name'),
+ switchAccount: z.boolean().optional().describe('Set when the user asked to use a different account, so the card is shown again instead of reusing the one they already picked'),
}),
execute: blockingExecute({
toolName: 'ap_show_connection_picker',
- refuseWhen: refuseIfAccountAlreadyChosen,
+ refuseWhen: async (input) => refuseIfAccountAlreadyChosen(input) ?? await refuseIfPickedEarlierInConversation(input),
dismissMessage: (input) => `The user chose not to select a ${typeof input['displayName'] === 'string' ? input['displayName'] : 'service'} account. Do not pick one on their behalf. Ask: "Would you like me to continue building with a placeholder you can connect later, or would you prefer to stop here?"`,
onApproved: async ({ input, payload = {} }) => {
const connectionExternalId = payload['connectionExternalId']