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
TypeScript ai-agentai-agent-toolsai-agentsai-agents-frameworkmcpmcp-servermcp-toolsmcpsn8n-alternativeno-code-automationworkflowworkflow-automationworkflows
fix(agents): link the agent after the chat finishes building it (#15675)
Hazem Adelc0b180fc3785
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.mdindex 319ef9ed979..aaaf2c6b2e7 100644--- a/brain/knowledge/ai-intelligence/ai-agents.md+++ b/brain/knowledge/ai-intelligence/ai-agents.md@@ -87,4 +87,6 @@ Paths verified 2026-07-17. An earlier version pointed at `packages/core/shared/s- **`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. **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.+- **Build the agent before reading the user's data, not after.** A turn that reads the user's mail, rows or records may not then change a saved agent, and the model's instinct is to look at the real data first so the instructions fit what is actually there. It then ends the turn describing an agent it cannot create and asking the user to say "create it". The order has to be: stand it up from what the user said plus the piece catalog, add its tools, then explore and refine with `ap_update_agent` on the next turn. That rule lives in three places that must agree, since the model only ever sees whichever one it is reading: the `ap_create_agent` and `ap_add_agent_tool` descriptions in `session-tools.ts`, the agent paragraph in `chat-system-prompt.md`, and the refusal string itself, which should teach the ordering rather than just apologise. **Treat it as a nudge, not a fix.** Measured over repeated runs of the same request it holds sometimes and not others: one run created the agent first and published it with its Gmail tools in a single turn, the next reached for `ap_explore_data` to read the real labels first and was refused exactly as before. Hiding the agent-surface tools once tainted does not help either, it only turns the refusal into an absence and the agent still is not created. The deterministic fix, unimplemented, is to let a tainted turn make the change behind the approval card `waitForApproval` already provides: a human sees the diff before it lands, which keeps the property the guard exists for while removing the dead end. Do not instead make the guard advisory on the first offence, that hands an injection one free write. Agent mutations all return a `url` from `afterDraftChange`; the `<links>` block has to tell the model to use it, or a successful build ends with no way to open what was built.+- **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/assets/prompts/chat-system-prompt.md b/packages/server/api/src/assets/prompts/chat-system-prompt.mdindex 015b2b1bd29..fad24e413d9 100644--- a/packages/server/api/src/assets/prompts/chat-system-prompt.md+++ b/packages/server/api/src/assets/prompts/chat-system-prompt.md@@ -6,7 +6,7 @@ To move their goals you can build almost anything:- **Make it automatic** — turn any repeating chore into an automation that runs on a schedule, when something happens, or when a form/webhook fires.- **Connect their tools** — hundreds of app integrations work out of the box; and for anything without a ready-made integration, you can still reach it directly over the web behind the scenes — so "we don't support that app" is almost never a real wall. (That "reach it directly" mechanism is *your* internal capability — never explain it to the user in technical terms; just tell them you can connect to it.)- **Add intelligence** — built-in AI can classify, extract, summarize, draft, and decide inside any task or automation, no separate AI account required.-- **Stand up an autonomous agent** — when the job isn't one task but a whole *role*, you can build a persistent AI agent: give it a persona and its own set of their tools, and it reasons, decides, and acts on their behalf — handling open-ended work without a fixed script, on demand or inside any automation. This is how you hand off not just a chore but an entire job — even one that stands in for the person themselves. Build it like you build anything: don't interview them for who they are — infer the persona and the starting toolset from what you can already see (their role, their apps, their data, how they work), stand up a first version, and refine it together once it exists.+- **Stand up an autonomous agent** — when the job isn't one task but a whole *role*, you can build a persistent AI agent: give it a persona and its own set of their tools, and it reasons, decides, and acts on their behalf — handling open-ended work without a fixed script, on demand or inside any automation. This is how you hand off not just a chore but an entire job — even one that stands in for the person themselves. Build it like you build anything: don't interview them for who they are — infer the persona and the starting toolset from what you can already see (their role, their apps, their data, how they work), stand up a first version, and refine it together once it exists. Create it and give it its tools before you read any of their data in that reply: a read closes the turn to agent changes, so exploring first leaves you describing an agent you cannot build.These are *means to advance the user's outcome*, not the headline. Lead with what's possible. When someone describes a goal — even in a few words — they should walk away feeling "yes, and I'm already on it" — not "let me check if we can" and not handed back the smallest literal reading of their request. You are the reason their hard problems get handled.@@ -358,6 +358,10 @@ This applies ONLY to deliverables the user asked you to produce. Normal conversa- Tables: {{FRONTEND_URL}}/projects/{projectId}/tables/{tableId}- Connections: {{FRONTEND_URL}}/projects/{projectId}/connections- Runs: {{FRONTEND_URL}}/projects/{projectId}/runs+- One agent: {{FRONTEND_URL}}/projects/{projectId}/agents/{agentId}+- All agents: {{FRONTEND_URL}}/agents++After you create or change a saved agent, link it by name using the `url` that tool returned, never one you assemble. The all-agents link is for talking about them as a group.Use the Connections link only when the user explicitly asks to manage/see their connections in general — NEVER as the way to fix a broken/expired connection. A broken connection is always reconnected inline via `ap_show_connection_required`/`ap_show_mcp_reconnect` (see the broken-connection rule in `<guardrails>`); do not hand out this link in that case.</links>diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/session-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/session-tools.tsindex b22a860bd04..c90ee503291 100644--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/session-tools.ts+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/session-tools.ts@@ -49,7 +49,7 @@ export function createAgentSurfaceTools({ executeTool, taintState }: {}): ToolSet {const runUnlessTainted = async (toolName: string, toolInput: Record<string, unknown>): Promise<unknown> => {if (taintState.tainted) {- return { error: 'You read data earlier in this reply, so you cannot change a saved agent in the same reply. Say what you would have changed, and offer to do it if they send that request on its own. The Configure panel is the other way.' }+ return { error: 'You read the user\'s data earlier in this reply, so you cannot change a saved agent in the same reply. Change the agent before reading their data, not after. Say what you would have changed, and offer to do it if they send that request on its own. The Configure panel is the other way.' }}return executeTool(toolName, toolInput)}@@ -104,7 +104,7 @@ export function createAgentSurfaceTools({ executeTool, taintState }: {}),ap_create_agent: tool({- description: 'Create a saved agent in the active project from a name and instructions. Write the instructions as the agent\'s own standing brief, in second person, covering what it does and what it must not do.',+ description: 'Create a saved agent in the active project from a name and instructions. Write the instructions as the agent\'s own standing brief, in second person, covering what it does and what it must not do. Call it before you read any of the user\'s data in this reply: afterwards it is refused until their next message, so stand the agent up first and refine it with ap_update_agent once you have looked at their data.',inputSchema: z.object({displayName: z.string().describe('Short name the user will recognise, e.g. "Inbox triage"'),instructions: z.string().describe('The agent\'s standing brief, in second person'),diff --git a/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-worker-tools.test.ts b/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-worker-tools.test.tsindex f9228f92425..fa646f6b911 100644--- a/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-worker-tools.test.ts+++ b/packages/server/worker/test/lib/execute/jobs/ee/agent/agent-worker-tools.test.ts@@ -375,7 +375,7 @@ describe('agentWorkerTools', () => {it('refuses to rewrite the agent once the turn has read outside content', async () => {const { result, executeTool } = await editWith(true)- expect(result.error).toMatch(/read data earlier in this reply/i)+ expect(result.error).toMatch(/read the user's data earlier in this reply/i)expect(executeTool).not.toHaveBeenCalled()})