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): use the agent's flow tools when chatting with it directly (#15749)
Hazem Adel31f088794178
diff --git a/brain/knowledge/ai-intelligence/ai-agents.md b/brain/knowledge/ai-intelligence/ai-agents.mdindex aaaf2c6b2e7..0ffbc194f80 100644--- a/brain/knowledge/ai-intelligence/ai-agents.md+++ b/brain/knowledge/ai-intelligence/ai-agents.md@@ -44,6 +44,7 @@ A flow step type (the `run_agent` action of `@activepieces/piece-ai`) that runsServer-side `toolName` is log-only — `executePieceTool` / `executeFlowTool` / `executeKnowledgeBaseTool` route on `piece`, `flowId` and `knowledgeBaseFileId` — so rewriting it breaks no lookup. `stepResultFrom` must be passed the knowledge-base tools too, or its `ToolCallType.KNOWLEDGE_BASE` branch is unreachable and the card shows the rewritten key instead of the file name.- **A retired model is user config, and only a marker in the message says so.** A provider 400 stays `internal` by default; one whose *message* matches `MODEL_UNAVAILABLE_PATTERNS` is `user`. Two deliberate narrowings, both learned the hard way: the body is **never** scanned, because any 400 carrying an HTML error page that says "deprecated" in its footer would launder our own outage; and a retired model on the managed `activepieces` key is **ours**, since `resolveModelIdForProvider` substitutes `curatedModels[0]` for anything uncurated — a stale constant in our repo failing every platform at once must page, not read as "the customer picked a bad model". That substitution still classifies as `user` on a BYO key, which is the residual gap.- **The curated chat lists rot silently and nothing checks them, but "the ticket said it's deprecated" is not evidence.** `ALLOWED_CHAT_MODELS_BY_PROVIDER` (`core/piece-types/src/lib/ai-providers.ts`) is the only thing deciding what the pickers offer; the models.dev catalog is metadata keyed by id and adds or removes nothing. Check a suspected-dead id against models.dev before deleting it — of the four ENG-466 named, only `grok-4.1-fast` had actually gone; the Gemini 2.5 pair was live, current and the *cheapest* Google option. Removing a live model is not a cleanup: `resolveModelIdForProvider` falls through to `curatedModels[0]`, so a BYO customer pinned to Flash would have silently moved to a Pro preview at roughly five times the token price, on their own key, with no notice and no migration. Three things move together when editing a list: `CHAT_MODEL_LABELS` (a curated id with no label fails `ai-providers.test.ts`), `MANAGED_MODEL_WEIGHTS` in `flow-run-ai-usage-tracker.ts` (its `?? 2` default is *below* the table's floor of 6, so a forgotten managed model under-bills — every `x-ai/*` id does today), and the **order**, since `curatedModels[0]` is both the picker's first row and the fallback for every unrecognised selection.+- **An agent's tools reach the worker in two shapes, and only one of them can actually run a flow.** `ExecuteAgentRunJobData` carries `tools` (the raw `AgentTool[]`) *and* `flowTools` (resolved: `flowId`, `flowVersionId`, JSON input schema). The worker builds its flow tool set from `flowTools` alone — `data.tools` is only filtered for PIECE, MCP and KNOWLEDGE_BASE, so the `AgentToolType.FLOW` entries in it are inert. An enqueue site that fills only `tools` therefore drops every flow tool with no error and no log: the Configure panel still lists them, the chat footer still names them, and the model is simply told it has no such tool. This is how saved-agent chat shipped for three releases while the same agent worked inside a `Run Agent` step, which resolved them. Both enqueue paths now go through `agentHelpers.resolveFlowTools`, which takes the **whole** tool array and filters internally, so no caller can do half the job. Resolve against the project the run will execute in — `executeFlowTool` looks the flow up in the *conversation's* project and refuses anything else, so resolving elsewhere hands the model a `flowId` the RPC then rejects.- **Whatever enqueues an agent run must pre-check the same thing the worker resolves.** The chat route asked "is any provider enabled for chat" while the worker looked up the run's *pinned* provider, and the flow-step route checked nothing at all — so a run enqueued fine and could only fail. Both now call `agentHelpers.assertRunProviderConfigured`, which mirrors the worker's lookup. A pre-check that answers a *different* question than the worker is worse than none: it makes the failure look impossible.- **Everything the agent job does before its try/catch has no recovery.** `getAgentConfig` used to run outside it, so a config failure sent no error to the chat client and never called `releaseFlowStep` — the flow run sat PAUSED until `AP_PAUSED_FLOW_TIMEOUT_DAYS`. Anything added above that block needs its own failure path, or a paused run leaks.- **Build the unattended tool set as an allow-list.** Removing chat tools by name failed three times running — display tools, then build-plan and phase tools, then `ap_discover_action_auth` and `ap_load_guide`, which live with the local tools and so survived a filter written by tool group. Grouping tracks where a tool was constructed, not whether it assumes someone is reading. A flow step gets exactly what it is listed: its configured piece actions, the public-web readers, and the structured-output tool. Anything added to chat later stays out by default.diff --git a/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts b/packages/server/api/src/app/ee/agent/agent-conversation-controller.tsindex c123d2255d8..385130f60b1 100644--- a/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts+++ b/packages/server/api/src/app/ee/agent/agent-conversation-controller.ts@@ -18,6 +18,7 @@ import { agentService } from './agent-service'import { chatAnalyticsTelemetry } from './chat-analytics-sync'import { chatRolloutService } from './chat-rollout-service'import { agentPrompt } from './prompt/agent-prompt'+import { updateConversationForRun } from './rpc/rpc-shared'import { findConnectionsForPiece } from './tools/agent-tools'const CHAT_PRINCIPALS = [PrincipalType.USER] as const@@ -157,30 +158,6 @@ export const agentConversationController: FastifyPluginAsyncZod = async (app) =>const runId = typeof clientRunId === 'string' ? clientRunId : apId()const runLog = log.child({ run: { id: runId } })- // Claim ownership atomically in the DB — the single source of truth that- // saveAgentMessages/updateAgentProgress/heartbeat fence against. A late write from the- // preempted run is rejected as soon as this UPDATE commits (its runId no longer matches),- // with no Redis/DB split to race through. The prior owner is read from the same row.- const preemptedRunId = conversation.status === AgentConversationStatus.STREAMING- ? conversation.activeRunId- : null- await agentHelpers.conversationRepo().update(conversationId, { activeRunId: runId })-- if (conversation.status === AgentConversationStatus.STREAMING) {- log.info({ ...spreadIfDefined('preemptedRunId', preemptedRunId ?? undefined) }, '[agentConversationController] Cancelling in-flight run before new message')- const cancelPromises = [- agentApprovalGate.requestCancel({ conversationId }),- ]- if (preemptedRunId) {- cancelPromises.push(agentApprovalGate.requestCancel({ conversationId, runId: preemptedRunId }))- }- await Promise.all(cancelPromises)- await agentHelpers.conversationRepo().update(conversationId, {- status: AgentConversationStatus.IDLE,- })- await agentApprovalGate.clearPendingGate({ conversationId })- }-const agent = isNil(conversation.agentId)? null: await agentService(log).getOneOrThrowByPlatform({ id: conversation.agentId, platformId, userId })@@ -202,15 +179,46 @@ export const agentConversationController: FastifyPluginAsyncZod = async (app) =>conversationProjectId: conversation.projectId ?? null,projects: await agentHelpers.getUserProjects({ platformId, userId, log }),})+ const runScope = agentHelpers.runScopeOrThrow({ projectId: runProjectId })await agentHelpers.assertRunProviderConfigured({platformId,log,- scope: agentHelpers.runScopeOrThrow({ projectId: runProjectId }),+ scope: runScope,...spreadIfDefined('provider', agentConfig?.provider ?? undefined),...spreadIfDefined('providerConfigId', agentConfig?.providerConfigId ?? undefined),})await assertCreditsAndAppSumoNotExceeded({ platformId, log })+ const carriesConfiguredTools = !isNil(agentConfig) && !isBuilder+ const flowTools = carriesConfiguredTools+ ? await agentHelpers.resolveFlowTools({ projectId: runScope.projectId, tools: agentConfig.tools, log: runLog })+ : []++ // Claim ownership atomically in the DB — the single source of truth that+ // saveAgentMessages/updateAgentProgress/heartbeat fence against. A late write from the+ // preempted run is rejected as soon as this UPDATE commits (its runId no longer matches),+ // with no Redis/DB split to race through. The prior owner is read from the same row.+ const { preemptedRunId, wasStreaming } = await agentHelpers.claimConversationForRun({ conversationId, runId })++ if (wasStreaming) {+ log.info({ ...spreadIfDefined('preemptedRunId', preemptedRunId ?? undefined) }, '[agentConversationController] Cancelling in-flight run before new message')+ const cancelPromises = [+ agentApprovalGate.requestCancel({ conversationId }),+ ]+ if (preemptedRunId) {+ cancelPromises.push(agentApprovalGate.requestCancel({ conversationId, runId: preemptedRunId }))+ }+ await Promise.all(cancelPromises)+ const stillOwned = await updateConversationForRun({+ conversationId,+ runId,+ updates: { status: AgentConversationStatus.IDLE },+ })+ if (stillOwned) {+ await agentApprovalGate.clearPendingGate({ conversationId })+ }+ }+await jobQueue(runLog).add({id: apId(),type: JobType.ONE_TIME,@@ -225,10 +233,11 @@ export const agentConversationController: FastifyPluginAsyncZod = async (app) =>userMessage: content,modelName: conversation.modelName ?? null,files,+ flowTools,...spreadIfDefined('source', conversation.source === AgentRunSource.CHAT ? undefined : conversation.source),...spreadIfDefined('messageSource', request.body.messageSource),...(isBuilder ? { promptOverride: { system: agentPrompt.buildBuilderSystemPrompt({ agent }) } } : {}),- ...(isNil(agentConfig) || isBuilder ? {} : agentHelpers.jobFieldsFromConfig({ config: agentConfig })),+ ...(carriesConfiguredTools ? agentHelpers.jobFieldsFromConfig({ config: agentConfig }) : {}),},})runLog.info({ job: { type: WorkerJobType.EXECUTE_AGENT_RUN } }, '[agentConversationController] Enqueued chat agent job')diff --git a/packages/server/api/src/app/ee/agent/agent-helpers.ts b/packages/server/api/src/app/ee/agent/agent-helpers.tsindex aaba391f968..cfa1b87ab81 100644--- a/packages/server/api/src/app/ee/agent/agent-helpers.ts+++ b/packages/server/api/src/app/ee/agent/agent-helpers.ts@@ -1,15 +1,19 @@import { ExecuteAgentRunJobData } from '@activepieces/core-execution'-import { ActivepiecesAiBilling, ActivepiecesError, AIProviderName, apId, ErrorCode, isNil, spreadIfDefined, tryCatch, tryCatchSync, unique } from '@activepieces/core-utils'+import { ActivepiecesAiBilling, ActivepiecesError, AIProviderName, apId, assertNotNullOrUndefined, ErrorCode, isNil, spreadIfDefined, tryCatch, tryCatchSync, unique } from '@activepieces/core-utils'import { aiUtils } from '@activepieces/server-utils'-import { AgentConfig, AgentConversation, AgentConversationStatus, AI_PROVIDER_ENTITY_TYPES, AIProviderModelType, GetAgentMemoryResponse, GetProviderConfigResponse, Project, ProjectType, UserMemory } from '@activepieces/shared'+import { AgentConfig, AgentConversation, AgentConversationStatus, AgentFlowTool, AgentTool, AgentToolType, AI_PROVIDER_ENTITY_TYPES, AIProviderModelType, FlowVersionState, GetAgentMemoryResponse, GetProviderConfigResponse, Project, ProjectType, ResolvedAgentFlowTool, UserMemory } from '@activepieces/shared'import { SharedV3ProviderOptions } from '@ai-sdk/provider'import { EmbeddingModel, LanguageModel } from 'ai'import { FastifyBaseLogger } from 'fastify'import { Repository } from 'typeorm'+import { z } from 'zod'import { aiProviderService, ProviderScope } from '../../ai/ai-provider-service'import { repoFactory } from '../../core/db/repo-factory'import { transaction } from '../../core/db/transaction'import { redisConnections } from '../../database/redis-connections'+import { flowService } from '../../flows/flow/flow.service'+import { extractMcpTriggerInput } from '../../mcp/mcp-server-builder'+import { mcpToolInput } from '../../mcp/mcp-tool-input'import { projectService } from '../../project/project-service'import { userService } from '../../user/user-service'import { platformPlanService } from '../platform/platform-plan/platform-plan.service'@@ -67,7 +71,7 @@ async function getUserProjects({ platformId, userId, log }: { platformId: string// A run always resolves its credential inside a project. Coercing a missing project to platform// scope would make every key on the platform eligible, ignoring the project restrictions their// owner set, so a run with nowhere to happen is refused instead.-function runScopeOrThrow({ projectId }: { projectId: string | null }): ProviderScope {+function runScopeOrThrow({ projectId }: { projectId: string | null }): Extract<ProviderScope, { type: 'project' }> {if (isNil(projectId)) {throw new ActivepiecesError({code: ErrorCode.ENTITY_NOT_FOUND,@@ -306,6 +310,55 @@ function jobFieldsFromConfig({ config }: { config: AgentConfig }): AgentJobConfi}}+async function claimConversationForRun({ conversationId, runId }: { conversationId: string, runId: string }): Promise<{ preemptedRunId: string | null, wasStreaming: boolean }> {+ return transaction(async (entityManager) => {+ const repo = entityManager.getRepository(AgentConversationEntity)+ const current = await repo.findOne({ where: { id: conversationId }, lock: { mode: 'pessimistic_write' } })+ const wasStreaming = current?.status === AgentConversationStatus.STREAMING+ await repo.update(conversationId, { activeRunId: runId })+ return { preemptedRunId: wasStreaming ? current?.activeRunId ?? null : null, wasStreaming }+ })+}++async function resolveFlowTools({ projectId, tools, log }: { projectId: string, tools: AgentTool[], log: FastifyBaseLogger }): Promise<ResolvedAgentFlowTool[]> {+ const flowToolRequests = tools.filter((tool): tool is AgentFlowTool => tool.type === AgentToolType.FLOW)+ if (flowToolRequests.length === 0) {+ return []+ }+ const externalFlowIds = unique(flowToolRequests.map((tool) => tool.externalFlowId))+ const listFlows = (versionState: FlowVersionState) => flowService(log).list({+ projectIds: [projectId],+ externalIds: externalFlowIds,+ cursorRequest: null,+ includeTriggerSource: false,+ versionState,+ })+ const [published, drafts] = await Promise.all([listFlows(FlowVersionState.LOCKED), listFlows(FlowVersionState.DRAFT)])+ const publishedByExternalId = new Map(published.data.map((flow) => [flow.externalId, flow]))+ const runnableByExternalId = new Map(drafts.data.map((flow) => [flow.externalId, publishedByExternalId.get(flow.externalId) ?? flow]))+ const missing = flowToolRequests.filter((tool) => !runnableByExternalId.has(tool.externalFlowId))+ if (missing.length > 0) {+ throw new ActivepiecesError({+ code: ErrorCode.VALIDATION,+ params: { message: `An agent cannot use flow tool(s) ${unique(missing.map((tool) => tool.toolName)).join(', ')}: the referenced flow was not found in this project` },+ })+ }+ return flowToolRequests.map((toolRequest) => {+ const flow = runnableByExternalId.get(toolRequest.externalFlowId)+ assertNotNullOrUndefined(flow, `flow for tool ${toolRequest.toolName}`)+ const { toolDescription, mcpInputs, returnsResponse } = extractMcpTriggerInput(flow)+ const inputShape = mcpToolInput.modelInputShape({ properties: mcpInputs })+ return {+ toolName: toolRequest.toolName,+ flowId: flow.id,+ flowVersionId: flow.version.id,+ description: toolDescription.length > 0 ? toolDescription : `Run the flow "${flow.version.displayName}"`,+ inputSchema: z.toJSONSchema(z.object(inputShape)),+ returnsResponse,+ }+ })+}+async function agentsSurfaceAvailable({ platformId, log }: { platformId: string, log: FastifyBaseLogger }): Promise<boolean> {const { data: plan, error } = await tryCatch(() => platformPlanService(log).getOrCreateForPlatform(platformId))if (!isNil(error) || isNil(plan)) {@@ -327,6 +380,8 @@ async function assertAgentsSurfaceAvailable({ platformId, log }: { platformId: sexport const agentHelpers = {jobFieldsFromConfig,+ claimConversationForRun,+ resolveFlowTools,agentsSurfaceAvailable,assertAgentsSurfaceAvailable,getConversationOrThrow,diff --git a/packages/server/api/src/app/ee/agent/agent-run-controller.ts b/packages/server/api/src/app/ee/agent/agent-run-controller.tsindex e94d4d13927..59032293318 100644--- a/packages/server/api/src/app/ee/agent/agent-run-controller.ts+++ b/packages/server/api/src/app/ee/agent/agent-run-controller.ts@@ -1,18 +1,15 @@import { flowStructureUtil } from '@activepieces/core-execution'import { AGENT_STEP_TIMEOUT_MS } from '@activepieces/core-piece-types'-import { ActivepiecesError, apId, ApId, assertNotNullOrUndefined, ErrorCode, isNil, spreadIfDefined, tryCatch, unique } from '@activepieces/core-utils'-import { AgentConfig, AgentFlowTool, AgentOutputField, AgentPieceProps, AgentRunSource, AgentTool, AgentToolType, AIProviderName, DEFAULT_AGENT_MAX_STEPS, FlowVersionState, LATEST_JOB_DATA_SCHEMA_VERSION, MAX_AGENT_OUTPUT_FIELDS, MAX_AGENT_STEP_BUDGET, MAX_AGENT_TEXT_LENGTH, MAX_AGENT_TOOLS, PrincipalType, ResolvedAgentFlowTool, TASK_COMPLETION_TOOL_NAME, WorkerJobType } from '@activepieces/shared'+import { ActivepiecesError, apId, ApId, ErrorCode, isNil, spreadIfDefined, tryCatch, unique } from '@activepieces/core-utils'+import { AgentConfig, AgentOutputField, AgentPieceProps, AgentRunSource, AgentTool, AgentToolType, AIProviderName, DEFAULT_AGENT_MAX_STEPS, LATEST_JOB_DATA_SCHEMA_VERSION, MAX_AGENT_OUTPUT_FIELDS, MAX_AGENT_STEP_BUDGET, MAX_AGENT_TEXT_LENGTH, MAX_AGENT_TOOLS, PrincipalType, TASK_COMPLETION_TOOL_NAME, WorkerJobType } from '@activepieces/shared'import { FastifyBaseLogger } from 'fastify'import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'import { StatusCodes } from 'http-status-codes'import { z } from 'zod'import { securityAccess } from '../../core/security/authorization/fastify-security'import { redisConnections } from '../../database/redis-connections'-import { flowService } from '../../flows/flow/flow.service'import { flowRunService } from '../../flows/flow-run/flow-run-service'import { flowVersionService } from '../../flows/flow-version/flow-version.service'-import { extractMcpTriggerInput } from '../../mcp/mcp-server-builder'-import { mcpToolInput } from '../../mcp/mcp-tool-input'import { assertCreditsAndAppSumoNotExceeded } from '../../platform/billing-provider'import { projectService } from '../../project/project-service'import { waitpointService } from '../../waitpoints/waitpoint-service'@@ -57,7 +54,6 @@ export const agentRunController: FastifyPluginAsyncZod = async (app) => {const { tools, structuredOutput, provider } = runFieldsconst supportedToolTypes = [AgentToolType.PIECE, AgentToolType.MCP, AgentToolType.FLOW, AgentToolType.KNOWLEDGE_BASE]const supportedTools = (tools ?? []).filter((tool) => supportedToolTypes.includes(tool.type))- const flowToolRequests = (tools ?? []).filter((tool): tool is AgentFlowTool => tool.type === AgentToolType.FLOW)const unsupported = unique((tools ?? []).map((tool) => tool.type)).filter((type) => !supportedToolTypes.includes(type))if (unsupported.length > 0) {throw new ActivepiecesError({ code: ErrorCode.VALIDATION, params: { message: `An agent step cannot use ${unsupported.join(' or ')} tools yet` } })@@ -74,7 +70,7 @@ export const agentRunController: FastifyPluginAsyncZod = async (app) => {params: { message: `Two tools are both named ${duplicated.join(', ')}: each tool on a step needs its own name, or one silently replaces the other` },})}- const flowTools = await resolveFlowTools({ projectId, flowToolRequests, log: request.log })+ const flowTools = await agentHelpers.resolveFlowTools({ projectId, tools: tools ?? [], log: request.log })await agentHelpers.assertRunProviderConfigured({ platformId: platform.id, provider, providerConfigId: runFields.providerConfigId, scope: agentHelpers.runScopeOrThrow({ projectId }), log: request.log })await assertCreditsAndAppSumoNotExceeded({ platformId: platform.id, log: request.log })const { ownerId } = await projectService(request.log).getOneOrThrow(projectId)@@ -170,48 +166,6 @@ async function claimWaitpointOrThrow({ waitpointId }: { waitpointId: string }):}}-async function resolveFlowTools({ projectId, flowToolRequests, log }: {- projectId: string- flowToolRequests: AgentFlowTool[]- log: FastifyBaseLogger-}): Promise<ResolvedAgentFlowTool[]> {- if (flowToolRequests.length === 0) {- return []- }- const externalFlowIds = unique(flowToolRequests.map((tool) => tool.externalFlowId))- const listFlows = (versionState: FlowVersionState) => flowService(log).list({- projectIds: [projectId],- externalIds: externalFlowIds,- cursorRequest: null,- includeTriggerSource: false,- versionState,- })- const [published, drafts] = await Promise.all([listFlows(FlowVersionState.LOCKED), listFlows(FlowVersionState.DRAFT)])- const publishedByExternalId = new Map(published.data.map((flow) => [flow.externalId, flow]))- const runnableByExternalId = new Map(drafts.data.map((flow) => [flow.externalId, publishedByExternalId.get(flow.externalId) ?? flow]))- const missing = flowToolRequests.filter((tool) => !runnableByExternalId.has(tool.externalFlowId))- if (missing.length > 0) {- throw new ActivepiecesError({- code: ErrorCode.VALIDATION,- params: { message: `An agent step cannot use flow tool(s) ${unique(missing.map((tool) => tool.toolName)).join(', ')}: the referenced flow was not found in this project` },- })- }- return flowToolRequests.map((toolRequest) => {- const flow = runnableByExternalId.get(toolRequest.externalFlowId)- assertNotNullOrUndefined(flow, `flow for tool ${toolRequest.toolName}`)- const { toolDescription, mcpInputs, returnsResponse } = extractMcpTriggerInput(flow)- const inputShape = mcpToolInput.modelInputShape({ properties: mcpInputs })- return {- toolName: toolRequest.toolName,- flowId: flow.id,- flowVersionId: flow.version.id,- description: toolDescription.length > 0 ? toolDescription : `Run the flow "${flow.version.displayName}"`,- inputSchema: z.toJSONSchema(z.object(inputShape)),- returnsResponse,- }- })-}-const WAITPOINT_RESUME_LAG_ALLOWANCE_SECONDS = 60 * 60const AGENT_RUN_CLAIM_TTL_SECONDS = AGENT_STEP_TIMEOUT_MS / 1_000 + WAITPOINT_RESUME_LAG_ALLOWANCE_SECONDSdiff --git a/packages/server/api/test/integration/ee/agent/agent-turn.test.ts b/packages/server/api/test/integration/ee/agent/agent-turn.test.tsindex ad08a01eb2d..a6e7ae880f8 100644--- a/packages/server/api/test/integration/ee/agent/agent-turn.test.ts+++ b/packages/server/api/test/integration/ee/agent/agent-turn.test.ts@@ -1,16 +1,20 @@-import { AIProviderName, ErrorCode } from '@activepieces/core-utils'-import { AgentIcon, AgentRunSource, ColorName } from '@activepieces/shared'+import { AIProviderName, apId, ErrorCode } from '@activepieces/core-utils'+import { AgentConversationStatus, AgentIcon, AgentRunSource, AgentToolType, ColorName, Flow, FlowStatus, FlowTriggerType, FlowVersion, FlowVersionState, McpPropertyType, WorkerJobType } from '@activepieces/shared'import { FastifyInstance } from 'fastify'import { StatusCodes } from 'http-status-codes'-import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { agentApprovalGate } from '../../../../src/app/ee/agent/agent-approval-gate'import { agentHelpers } from '../../../../src/app/ee/agent/agent-helpers'+import * as jobQueueModule from '../../../../src/app/workers/job-queue/job-queue'import { db } from '../../../helpers/db'-import { mockAndSaveAIProvider } from '../../../helpers/mocks'+import { createMockFlow, createMockFlowVersion, mockAndSaveAIProvider } from '../../../helpers/mocks'import { createTestContext, TestContext } from '../../../helpers/test-context'import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'let app: FastifyInstance+const originalJobQueue = jobQueueModule.jobQueue+const CONVERSATIONS_URL = '/v1/agents/conversations'const CONFIGURED_MODEL = 'anthropic/claude-haiku-4.5'@@ -172,3 +176,173 @@ describe('the model an agent answers on', () => {expect(response.statusCode).toBe(StatusCodes.OK)})})++describe('the flow tools a chat turn hands to the worker', () => {+ let addSpy: ReturnType<typeof vi.fn>++ beforeEach(() => {+ addSpy = vi.fn()+ vi.spyOn(jobQueueModule, 'jobQueue').mockImplementation((log) => ({+ ...originalJobQueue(log),+ add: addSpy,+ }))+ })++ afterEach(() => {+ vi.restoreAllMocks()+ })++ it('resolves a configured flow tool, the only shape the worker can run one from', async () => {+ const ctx = await context()+ await enableForChat(ctx.platform.id, AIProviderName.OPENROUTER)+ const { flow, flowVersion } = await seedMcpToolFlow(ctx)+ const agent = await createAgent(ctx, {+ provider: AIProviderName.OPENROUTER,+ modelName: CONFIGURED_MODEL,+ tools: [{ type: AgentToolType.FLOW, toolName: 'check_order_status', externalFlowId: flow.externalId }],+ })+ const conversation = await startConversation(ctx, agent.id)++ const response = await ctx.post(`${CONVERSATIONS_URL}/${conversation.id}/messages`, { content: 'Where is order 12345?' })++ expect(response.statusCode).toBe(StatusCodes.OK)+ const job = addSpy.mock.calls.map(([call]) => call).find((call) => call.data.jobType === WorkerJobType.EXECUTE_AGENT_RUN)+ expect(job.data.flowTools).toEqual([{+ toolName: 'check_order_status',+ flowId: flow.id,+ flowVersionId: flowVersion.id,+ description: TOOL_DESCRIPTION,+ inputSchema: expect.objectContaining({+ properties: expect.objectContaining({ orderNumber: expect.anything() }),+ }),+ returnsResponse: true,+ }])+ })++ it('refuses the turn when a configured flow tool names a flow this project does not have', async () => {+ const ctx = await context()+ await enableForChat(ctx.platform.id, AIProviderName.OPENROUTER)+ const agent = await createAgent(ctx, {+ provider: AIProviderName.OPENROUTER,+ modelName: CONFIGURED_MODEL,+ tools: [{ type: AgentToolType.FLOW, toolName: 'check_order_status', externalFlowId: apId() }],+ })+ const conversation = await startConversation(ctx, agent.id)++ const response = await ctx.post(`${CONVERSATIONS_URL}/${conversation.id}/messages`, { content: 'Where is order 12345?' })++ expect(response.statusCode).toBe(StatusCodes.CONFLICT)+ expect(response.json().params.message).toContain('the referenced flow was not found in this project')+ expect(addSpy).not.toHaveBeenCalled()+ })++ it('refuses without taking the conversation over, so a reply already streaming survives', async () => {+ const ctx = await context()+ await enableForChat(ctx.platform.id, AIProviderName.OPENROUTER)+ const agent = await createAgent(ctx, {+ provider: AIProviderName.OPENROUTER,+ modelName: CONFIGURED_MODEL,+ tools: [{ type: AgentToolType.FLOW, toolName: 'check_order_status', externalFlowId: apId() }],+ })+ const conversation = await startConversation(ctx, agent.id)+ const streamingRunId = apId()+ await db.update('agent_conversation', conversation.id, {+ status: AgentConversationStatus.STREAMING,+ activeRunId: streamingRunId,+ })++ const response = await ctx.post(`${CONVERSATIONS_URL}/${conversation.id}/messages`, { content: 'Where is order 12345?' })++ expect(response.statusCode).toBe(StatusCodes.CONFLICT)+ const after = await agentHelpers.conversationRepo().findOneByOrFail({ id: conversation.id })+ expect(after.activeRunId).toBe(streamingRunId)+ expect(after.status).toBe(AgentConversationStatus.STREAMING)+ })++ it('cancels a run that started streaming while this turn was still being admitted', async () => {+ const ctx = await context()+ await enableForChat(ctx.platform.id, AIProviderName.OPENROUTER)+ const agent = await createAgent(ctx, { provider: AIProviderName.OPENROUTER, modelName: CONFIGURED_MODEL })+ const conversation = await startConversation(ctx, agent.id)++ const concurrentRunId = apId()+ const realGetUserProjects = agentHelpers.getUserProjects+ vi.spyOn(agentHelpers, 'getUserProjects').mockImplementation(async (args) => {+ await agentHelpers.conversationRepo().update(conversation.id, {+ activeRunId: concurrentRunId,+ status: AgentConversationStatus.STREAMING,+ })+ return realGetUserProjects(args)+ })++ const response = await ctx.post(`${CONVERSATIONS_URL}/${conversation.id}/messages`, { content: 'hello' })++ expect(response.statusCode).toBe(StatusCodes.OK)+ const after = await agentHelpers.conversationRepo().findOneByOrFail({ id: conversation.id })+ expect(after.activeRunId).not.toBe(concurrentRunId)+ expect(after.status).toBe(AgentConversationStatus.IDLE)+ })++ it('leaves a newer run alone when its own cancellation cleanup lands late', async () => {+ const ctx = await context()+ await enableForChat(ctx.platform.id, AIProviderName.OPENROUTER)+ const agent = await createAgent(ctx, { provider: AIProviderName.OPENROUTER, modelName: CONFIGURED_MODEL })+ const conversation = await startConversation(ctx, agent.id)+ await agentHelpers.conversationRepo().update(conversation.id, {+ status: AgentConversationStatus.STREAMING,+ activeRunId: apId(),+ })++ const newerRunId = apId()+ const realRequestCancel = agentApprovalGate.requestCancel+ vi.spyOn(agentApprovalGate, 'requestCancel').mockImplementation(async (args) => {+ await agentHelpers.conversationRepo().update(conversation.id, {+ activeRunId: newerRunId,+ status: AgentConversationStatus.STREAMING,+ })+ return realRequestCancel(args)+ })++ const response = await ctx.post(`${CONVERSATIONS_URL}/${conversation.id}/messages`, { content: 'hello' })++ expect(response.statusCode).toBe(StatusCodes.OK)+ const after = await agentHelpers.conversationRepo().findOneByOrFail({ id: conversation.id })+ expect(after.activeRunId).toBe(newerRunId)+ expect(after.status).toBe(AgentConversationStatus.STREAMING)+ })+})++async function seedMcpToolFlow(ctx: TestContext): Promise<{ flow: Flow, flowVersion: FlowVersion }> {+ const flow = createMockFlow({ projectId: ctx.project.id, status: FlowStatus.ENABLED })+ await db.save('flow', flow)+ const flowVersion = createMockFlowVersion({+ flowId: flow.id,+ updatedBy: ctx.user.id,+ state: FlowVersionState.LOCKED,+ valid: true,+ trigger: {+ type: FlowTriggerType.PIECE,+ name: 'trigger',+ displayName: 'MCP Tool',+ valid: true,+ lastUpdatedDate: new Date().toISOString(),+ settings: {+ pieceName: '@activepieces/piece-mcp',+ pieceVersion: '0.0.21',+ triggerName: 'mcp_tool',+ propertySettings: {},+ input: {+ toolName: 'check_order_status',+ toolDescription: TOOL_DESCRIPTION,+ inputSchema: [{ name: 'orderNumber', type: McpPropertyType.TEXT, required: true, description: 'The order number' }],+ returnsResponse: true,+ },+ },+ },+ })+ await db.save('flow_version', flowVersion)+ await db.update('flow', flow.id, { publishedVersionId: flowVersion.id })+ return { flow, flowVersion }+}++const TOOL_DESCRIPTION = 'Look up the delivery status of a customer order.'