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 agent building from stalling halfway through (#15668)

Hazem Adel5e676cd007e9
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.md
index 733c54b9d06..319ef9ed979 100644
--- a/brain/knowledge/ai-intelligence/ai-agents.md
+++ b/brain/knowledge/ai-intelligence/ai-agents.md
@@ -86,5 +86,5 @@ Paths verified 2026-07-17. An earlier version pointed at `packages/core/shared/s
- **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`. 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.
+- **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. **But marking every MCP tool was too wide, and it broke agent building outright.** `ap_list_connections` and `ap_research_pieces` are MCP-served and return only the platform's own catalog, yet they tainted, so `ap_add_agent_tool` refused the write its own description had just told the model to prepare ("Look them up first"). Following the instructions correctly was what broke it. `agentToolPhases.taintsTurn` now exempts a short catalog-only list (`ap_research_pieces`, `ap_search_actions`, `ap_search_triggers`, `ap_list_connections`) and unknown names still taint, so a new tool is never silently exempt. It lives in `tool-phases.ts` beside `BUILD_ONLY_TOOL_NAMES` and `CHAT_HIDDEN_TOOL_NAMES` because it classifies the same name space; a near-twin already exists server-side as `PLATFORM_LEVEL_TOOL_NAMES` in the MCP registry, differing only by `+ap_list_connections` and `-ap_get_piece_props`. Keep anything that can reach a third party off the list however metadata-ish it looks: `ap_get_piece_props` and `ap_resolve_property_*` run a piece's dynamic-props function against its API when given `auth`, and `ap_list_ai_models` can fetch a provider's model list over the network. The two layers are not symmetric, and it matters which way you reconcile them. The server's Redis flag is set by three RPCs only, so it is blind to MCP and web reads: `ap_find_records`, `ap_list_runs` and every `mcp__connector__*` call never reach `markTurnAsHavingRead`. The worker is the only mark for those and has to stay wider, so the server is the tighter list for **catalog** tools, not the model to copy wholesale, and narrowing the worker to match it would reopen the hole. A server-owned mark is reachable in principle, contrary to what this note used to claim: the agent's MCP server is the API (`${frontendUrl}/mcp/platform`) and the worker already sends `x-ap-conversation-id` on every MCP request, so marking in the MCP tool-call handler would work given a `runId` alongside it. Nobody has done it, but do not cite impossibility as the reason to keep both copies.
- **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/bun.lock b/bun.lock
index 980e7617bde..c20f19e460e 100644
--- a/bun.lock
+++ b/bun.lock
@@ -165,7 +165,7 @@
},
"packages/core/shared": {
"name": "@activepieces/shared",
- "version": "0.174.0",
+ "version": "0.175.0",
"dependencies": {
"@activepieces/core-execution": "workspace:*",
"@activepieces/core-formula": "workspace:*",
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index bebf2a30040..cff62db368f 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.174.0",
+ "version": "0.175.0",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/ee/agent/tool-phases.ts b/packages/core/shared/src/lib/ee/agent/tool-phases.ts
index dea7fd7ed5f..b1462f48b75 100644
--- a/packages/core/shared/src/lib/ee/agent/tool-phases.ts
+++ b/packages/core/shared/src/lib/ee/agent/tool-phases.ts
@@ -49,6 +49,17 @@ const CHAT_HIDDEN_TOOL_NAMES = new Set<string>([
'ap_setup_guide',
])
+const CATALOG_ONLY_TOOL_NAMES = new Set<string>([
+ 'ap_research_pieces',
+ 'ap_search_actions',
+ 'ap_search_triggers',
+ 'ap_list_connections',
+])
+
+function taintsTurn(toolName: string): boolean {
+ return !CATALOG_ONLY_TOOL_NAMES.has(toolName)
+}
+
function activeToolsForPhase({ phase, allToolNames }: {
phase: AgentPhase
allToolNames: string[]
@@ -79,4 +90,5 @@ export const agentToolPhases = {
activeToolsForPhase,
isBuildOnlyTool,
isAgentHiddenTool,
+ taintsTurn,
}
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-mcp-client.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-mcp-client.ts
index 6b842dff208..92f7870b2ee 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-mcp-client.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/agent-mcp-client.ts
@@ -304,7 +304,9 @@ function withToolTimeouts({ mcpToolSet, brokenConnectors, taintState, getSelecte
if (toolConnectorUuid !== null && brokenConnectors.has(toolConnectorUuid)) {
return buildReconnectGuidance({ connectorUuid: toolConnectorUuid, alreadyFlagged: true })
}
- taintState.tainted = true
+ if (agentToolPhases.taintsTurn(name)) {
+ taintState.tainted = true
+ }
const { data: toolResult, error } = await tryCatch(() => agentWorkerTools.withToolTimeout({
fn: (timeoutSignal) => originalExecute(args, options ? { ...options, abortSignal: timeoutSignal } : undefined),
timeoutMs: agentWorkerTools.TOOL_EXECUTION_TIMEOUT_MS,
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/tool-primitives.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/tool-primitives.ts
index f1d261d0d6e..02f6071e8d8 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/tool-primitives.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/tool-primitives.ts
@@ -1,6 +1,6 @@
import { isNil, isObject, spreadIfDefined } from '@activepieces/core-utils'
import { largeResultUtils, MAX_TOOL_RESULT_BYTES } from '@activepieces/server-utils'
-import { ActionPreviewEvent, ActionReceiptEvent, agentToolClassification, BuildPlanEvent, FileProducedEvent, ImageGeneratedEvent, ToolProgressEvent } from '@activepieces/shared'
+import { ActionPreviewEvent, ActionReceiptEvent, agentToolClassification, agentToolPhases, BuildPlanEvent, FileProducedEvent, ImageGeneratedEvent, ToolProgressEvent } from '@activepieces/shared'
import { ToolExecutionOptions, ToolSet } from 'ai'
import { z } from 'zod'
@@ -189,7 +189,9 @@ export function wrapToolsWithTaint({ tools, taintState }: { tools: ToolSet, tain
return [name, {
...toolDef,
execute: async (input: unknown, options: ToolExecutionOptions<undefined>) => {
- taintState.tainted = true
+ if (agentToolPhases.taintsTurn(name)) {
+ taintState.tainted = true
+ }
return run(input, options)
},
}]
diff --git a/packages/server/worker/test/lib/agent/taints-turn.test.ts b/packages/server/worker/test/lib/agent/taints-turn.test.ts
new file mode 100644
index 00000000000..ae729bdfbdc
--- /dev/null
+++ b/packages/server/worker/test/lib/agent/taints-turn.test.ts
@@ -0,0 +1,70 @@
+import { agentToolPhases } from '@activepieces/shared'
+import { tool, ToolExecutionOptions } from 'ai'
+import { describe, expect, it } from 'vitest'
+import { z } from 'zod'
+import { agentWorkerTools } from '../../../src/lib/execute/jobs/ee/agent/agent-worker-tools'
+
+const { taintsTurn } = agentToolPhases
+const options: ToolExecutionOptions<undefined> = { toolCallId: 'call-1', messages: [] }
+
+describe('taintsTurn', () => {
+ it.each([
+ 'ap_research_pieces',
+ 'ap_search_actions',
+ 'ap_search_triggers',
+ 'ap_list_connections',
+ ])('lets %s run without closing the turn to agent edits, because it only reads the catalog', (toolName) => {
+ expect(taintsTurn(toolName)).toBe(false)
+ })
+
+ it.each([
+ 'ap_execute_action',
+ 'ap_explore_data',
+ 'ap_get_run',
+ 'ap_find_records',
+ 'ap_read_step_settings',
+ 'ap_get_piece_props',
+ 'ap_resolve_property_options',
+ 'ap_resolve_property_chain',
+ 'ap_list_ai_models',
+ ])('keeps %s tainting, since its result can carry third-party content', (toolName) => {
+ expect(taintsTurn(toolName)).toBe(true)
+ })
+
+ it('taints an unknown tool, so a new one is never silently exempt', () => {
+ expect(taintsTurn('ap_some_tool_added_next_quarter')).toBe(true)
+ })
+
+ it('taints a connector tool whose name is generated per connection', () => {
+ expect(taintsTurn('gmail_a1b2c3_mcp')).toBe(true)
+ })
+})
+
+describe('wrapToolsWithTaint', () => {
+ const runWrapped = async (name: string) => {
+ const taintState = { tainted: false }
+ let taintedDuringRun = false
+ const wrapped = agentWorkerTools.wrapToolsWithTaint({
+ tools: {
+ [name]: tool({
+ inputSchema: z.object({}),
+ execute: async () => {
+ taintedDuringRun = taintState.tainted
+ return 'ran'
+ },
+ }),
+ },
+ taintState,
+ })
+ const result = await wrapped[name].execute?.({}, options)
+ return { taintedDuringRun, tainted: taintState.tainted, result }
+ }
+
+ it('taints before the tool body runs, so a same-batch agent edit cannot slip through', async () => {
+ expect(await runWrapped('ap_explore_data')).toEqual({ taintedDuringRun: true, tainted: true, result: 'ran' })
+ })
+
+ it('leaves the turn clean for a catalog tool, so the agent can still be built', async () => {
+ expect(await runWrapped('ap_research_pieces')).toEqual({ taintedDuringRun: false, tainted: false, result: 'ran' })
+ })
+})