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(chat): chat follows a piece's own read or write label before running an action (#16962)

Hazem Adel147b3a28bd06
diff --git a/brain/knowledge/flows-execution/chat.md b/brain/knowledge/flows-execution/chat.md
index 146acfb0982..abac007c0f2 100644
--- a/brain/knowledge/flows-execution/chat.md
+++ b/brain/knowledge/flows-execution/chat.md
@@ -30,6 +30,7 @@ A turn is kept alive / reclaimed by three separate mechanisms in `execute-agent-
- **Stream idle watchdog** (`STREAM_IDLE_TIMEOUT_MS` 90s, in `streamChunksToClient`): aborts the turn if the drain-stream reader is silent 90s. It must be SUSPENDED while legitimate silent work is in flight — pending tool calls AND in-flight reasoning (`reasoning-start`→`reasoning-end`). **Reasoning-awareness was missing and caused the bug where long "thinking" on the Expert tier randomly aborted a healthy turn** (a >90s gap between reasoning deltas looked like a wedge). Backstop for a genuine mid-reasoning wedge is `MAX_TURN_WALL_CLOCK_MS` (20 min).
### Gotchas
+- **A piece's declared classification beats its action name.** `agentToolClassification` still guesses read or write from words in the action name, but a piece that declares `READ`, `SEARCH`, `WRITE` or `DESTRUCTIVE` wins: `mark_as_read` and `add_member_to_list` are writes. The API refuses a declared write in `ap_explore_data` (`runAgentAction`, `readOnlyOnly`), and the worker's approval card asks the API through `__action_read_only` before deciding. If that lookup fails, the gate falls back to the name rule. `custom_api_call` keeps following its HTTP method (AI-106).
- **Compaction is not metered.** `getAgentConfig` builds the compaction model with `aiUtils.createModel` and no `billing`, so the summarizing call on the main model never reaches credits or usage reporting. Count it by hand when measuring cost per turn.
- **Bedrock ignores our cache and thinking options.** `agentProviderOptions` sends `anthropic.cacheControl` and `anthropic.thinking` for BEDROCK, but `@ai-sdk/amazon-bedrock` reads only `bedrock`/`amazonBedrock` keys (`cachePoint`, `reasoningConfig`). Bedrock chat therefore runs with no prompt caching and default thinking.
- **Tiers only resolve on Anthropic-shaped providers.** `PublishedTier.nativeModelId` is a single Anthropic id. On OpenAI and Google both `fast` and `smart` fall to the first curated model; on Azure and Bedrock the fast model is passed `fallbackModelId: resolvedModelId`, so it equals the main model.
diff --git a/packages/core/shared/package.json b/packages/core/shared/package.json
index e196e26c389..3a2490ffce5 100644
--- a/packages/core/shared/package.json
+++ b/packages/core/shared/package.json
@@ -1,6 +1,6 @@
{
"name": "@activepieces/shared",
- "version": "0.209.0",
+ "version": "0.209.1",
"type": "commonjs",
"sideEffects": false,
"main": "./dist/src/index.js",
diff --git a/packages/core/shared/src/lib/ee/agent/tool-classification.ts b/packages/core/shared/src/lib/ee/agent/tool-classification.ts
index 6e7c6f5f1af..f30228a47af 100644
--- a/packages/core/shared/src/lib/ee/agent/tool-classification.ts
+++ b/packages/core/shared/src/lib/ee/agent/tool-classification.ts
@@ -14,11 +14,12 @@ function actionNameMatchesPatterns({ actionName, patterns }: { actionName: strin
return patterns.some((pattern) => words.includes(pattern))
}
-function requiresActionPreview({ actionName, input, needsConfirmation, tainted }: {
+function requiresActionPreview({ actionName, input, needsConfirmation, tainted, declaredReadOnly }: {
actionName: string
input?: Record<string, unknown>
needsConfirmation?: boolean
tainted?: boolean
+ declaredReadOnly?: boolean
}): boolean {
// Raw HTTP: skip the gate only for a provably read-only method (GET/HEAD/OPTIONS). A mutating
// method (POST/PUT/PATCH/DELETE) — or an unknown/unspecified one — must be confirmed, so chat
@@ -27,6 +28,9 @@ function requiresActionPreview({ actionName, input, needsConfirmation, tainted }
const method = typeof input?.['method'] === 'string' ? input['method'].toUpperCase() : undefined
return method === undefined || !READ_ONLY_HTTP_METHODS.includes(method)
}
+ if (declaredReadOnly !== undefined) {
+ return !declaredReadOnly
+ }
const isRead = actionNameMatchesPatterns({ actionName, patterns: READ_ACTION_PATTERNS })
const isWrite = actionNameMatchesPatterns({ actionName, patterns: WRITE_ACTION_PATTERNS })
@@ -46,15 +50,12 @@ function isReadActionName(actionName: string): boolean {
// custom_api_call carries no read/write verb in its name, so name-based classification
// wrongly blocks a read-only GET. Treat it as read-only when its HTTP method is safe.
-function isReadOnlyActionCall({ actionName, input }: { actionName: string, input?: Record<string, unknown> }): boolean {
- if (isReadActionName(actionName)) {
- return true
- }
+function isReadOnlyActionCall({ actionName, input, declaredReadOnly }: { actionName: string, input?: Record<string, unknown>, declaredReadOnly?: boolean }): boolean {
if (actionName === 'custom_api_call') {
const method = typeof input?.['method'] === 'string' ? input['method'].toUpperCase() : undefined
return method === undefined || READ_ONLY_HTTP_METHODS.includes(method)
}
- return false
+ return declaredReadOnly ?? isReadActionName(actionName)
}
function isWriteActionName(actionName: string): boolean {
diff --git a/packages/core/shared/test/ee/agent-tool-classification.test.ts b/packages/core/shared/test/ee/agent-tool-classification.test.ts
index 37cea437237..283820d7df1 100644
--- a/packages/core/shared/test/ee/agent-tool-classification.test.ts
+++ b/packages/core/shared/test/ee/agent-tool-classification.test.ts
@@ -119,3 +119,27 @@ describe('agentToolClassification.requiresActionPreview: an action whose name pr
expect(agentToolClassification.requiresActionPreview({ actionName: 'custom_api_call', input: { method: 'GET' } })).toBe(false)
})
})
+
+describe('agentToolClassification: a piece that declares its classification', () => {
+ it.each([
+ ['mark_as_read', false],
+ ['add_member_to_list', false],
+ ])('treats "%s" declared WRITE as a write, whatever its name says', (actionName, declaredReadOnly) => {
+ expect(agentToolClassification.isReadOnlyActionCall({ actionName, declaredReadOnly })).toBe(false)
+ expect(agentToolClassification.requiresActionPreview({ actionName, declaredReadOnly, needsConfirmation: false })).toBe(true)
+ expect(agentToolClassification.requiresActionPreview({ actionName, declaredReadOnly, tainted: true })).toBe(true)
+ })
+
+ it('treats an action declared READ as read-only, even when its name looks like a write', () => {
+ expect(agentToolClassification.isReadOnlyActionCall({ actionName: 'send_digest_preview', declaredReadOnly: true })).toBe(true)
+ expect(agentToolClassification.requiresActionPreview({ actionName: 'send_digest_preview', declaredReadOnly: true, tainted: true })).toBe(false)
+ })
+
+ it('falls back to the name when the piece declares nothing', () => {
+ expect(agentToolClassification.isReadOnlyActionCall({ actionName: 'mark_as_read' })).toBe(true)
+ })
+
+ it('keeps reading a custom API call from its HTTP method', () => {
+ expect(agentToolClassification.isReadOnlyActionCall({ actionName: 'custom_api_call', input: { method: 'DELETE' }, declaredReadOnly: true })).toBe(false)
+ })
+})
diff --git a/packages/server/api/src/app/ee/agent/tools/agent-tools.ts b/packages/server/api/src/app/ee/agent/tools/agent-tools.ts
index d3c694ac5e7..c7965bc1b60 100644
--- a/packages/server/api/src/app/ee/agent/tools/agent-tools.ts
+++ b/packages/server/api/src/app/ee/agent/tools/agent-tools.ts
@@ -1,4 +1,5 @@
import { isNil, isObject, isString, parseToJsonIfPossible, Permission, spreadIfDefined, tryCatch, unique } from '@activepieces/core-utils'
+import { ActionClassification, isReadOnlyClassification } from '@activepieces/pieces-framework'
import { agentAiUtils } from '@activepieces/server-utils'
import { Agent, AgentActionOutcome, AgentIcon, AgentRunSource, AgentTool, agentToolClassification, AgentToolType, AppConnectionStatus, AppConnectionType, ApplicationEventName, ColorName, DEFAULT_AGENT_MAX_STEPS, FileCompression, FileType, FlowRunStatus, FlowStatus, mcpToolNameUtils, Project, RunEnvironment } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
@@ -628,12 +629,13 @@ async function executeCrossProjectTool({ toolName, toolInput, platformId, userId
case 'ap_run_code': {
return runAgentCode({ toolInput, projects, platformId, userId, conversationId, log })
}
+ case '__action_read_only': {
+ const { pieceName, actionName } = runActionInput.pick({ pieceName: true, actionName: true }).parse(toolInput)
+ const target = await resolveActionTarget({ pieceName, actionName, projects, availableProjectIds, conversationId, platformId, log })
+ return 'error' in target ? null : target.declared.readOnly ?? null
+ }
case 'ap_explore_data': {
- const { actionName, input: exploreInput } = runActionInput.parse(toolInput)
- if (!agentToolClassification.isReadOnlyActionCall({ actionName, input: exploreInput })) {
- return agentToolClassification.readOnlyRejection(actionName)
- }
- return runAgentAction({ toolInput, projects, availableProjectIds, conversationId, platformId, userId, log })
+ return runAgentAction({ toolInput, projects, availableProjectIds, conversationId, platformId, userId, readOnlyOnly: true, log })
}
case 'ap_list_across_projects': {
const resource = toolInput.resource as string
@@ -703,7 +705,7 @@ function buildActionRunOffload({ projectId, platformId, conversationId, pieceNam
}
}
-async function runAgentAction({ toolInput, projects, availableProjectIds, conversationId, platformId, userId, requireWritePermission, log }: {
+async function runAgentAction({ toolInput, projects, availableProjectIds, conversationId, platformId, userId, requireWritePermission, readOnlyOnly, log }: {
toolInput: Record<string, unknown>
projects: Project[]
availableProjectIds: string[]
@@ -711,29 +713,17 @@ async function runAgentAction({ toolInput, projects, availableProjectIds, conver
platformId?: string
userId: string
requireWritePermission?: boolean
+ readOnlyOnly?: boolean
log: FastifyBaseLogger
}): Promise<unknown> {
const { pieceName, actionName, input: parsedInput } = runActionInput.parse(toolInput)
-
- const normalizedPiece = mcpUtils.normalizePieceName(pieceName) ?? pieceName
- let connectionExternalId: string | undefined
- let connectionLabel: string | undefined
- let connectionProjectId: string | undefined
- if (conversationId) {
- const selected = await agentApprovalGate.getSelectedConnection({ conversationId, pieceName: normalizedPiece })
- if (selected) {
- connectionExternalId = selected.externalId
- connectionLabel = selected.label
- connectionProjectId = selected.projectId
- }
+ const target = await resolveActionTarget({ pieceName, actionName, projects, availableProjectIds, conversationId, platformId, log })
+ if ('error' in target) {
+ return { success: false, error: target.error }
}
-
- const resolvedProjectId = connectionProjectId ?? projects[0]?.id
- if (!resolvedProjectId) {
- return { success: false, error: 'No projects available. Create a project first.' }
- }
- if (connectionProjectId && !availableProjectIds.includes(connectionProjectId)) {
- return { success: false, error: `Project ${connectionProjectId} is not accessible.` }
+ const { normalizedPiece, projectId: resolvedProjectId, connectionExternalId, connectionLabel, declared } = target
+ if (readOnlyOnly && !agentToolClassification.isReadOnlyActionCall({ actionName, input: parsedInput, declaredReadOnly: declared.readOnly })) {
+ return agentToolClassification.readOnlyRejection(actionName)
}
if (requireWritePermission) {
const denial = await checkWriteRunPermission({ userId, projectId: resolvedProjectId, toolName: 'ap_execute_action', log })
@@ -756,8 +746,9 @@ async function runAgentAction({ toolInput, projects, availableProjectIds, conver
const structured = !isNil(resultObj) && isObject(resultObj.structuredContent) ? resultObj.structuredContent : undefined
const errorSummary = typeof structured?.errorSummary === 'string' ? structured.errorSummary : undefined
- await recordChatAction({
+ recordChatAction({
piece: { pieceName: normalizedPiece, actionName },
+ declared,
input: parsedInput ?? {},
projectId: resolvedProjectId,
userId,
@@ -972,8 +963,9 @@ type RunCodeToolResult = {
export { executeCrossProjectTool, findConnectionsForPiece }
-async function recordChatAction({ piece, input, projectId, platformId, userId, conversationId, connection, outcome, log }: {
+function recordChatAction({ piece, declared, input, projectId, platformId, userId, conversationId, connection, outcome, log }: {
piece: { pieceName: string, actionName: string }
+ declared: DeclaredAction
input: Record<string, unknown>
projectId: string
platformId?: string
@@ -982,21 +974,83 @@ async function recordChatAction({ piece, input, projectId, platformId, userId, c
connection: { externalId?: string, label?: string }
outcome: AgentActionOutcome
log: FastifyBaseLogger
-}): Promise<void> {
+}): void {
if (isNil(platformId)) {
return
}
- const { data: metadata } = await tryCatch(() => pieceMetadataService(log).get({ name: piece.pieceName, projectId, platformId }))
- const action = metadata?.actions?.[piece.actionName]
recordAgentAction({
run: { projectId, platformId, userId, source: AgentRunSource.CHAT },
piece,
resolvedInput: input,
- names: { action: action?.displayName ?? piece.actionName, piece: metadata?.displayName ?? piece.pieceName },
+ names: { action: declared.actionDisplayName ?? piece.actionName, piece: declared.pieceDisplayName ?? piece.pieceName },
outcome,
connection,
log,
...spreadIfDefined('conversationId', conversationId),
- ...spreadIfDefined('classification', action?.classification),
+ ...spreadIfDefined('classification', declared.classification),
})
}
+
+async function resolveActionTarget({ pieceName, actionName, projects, availableProjectIds, conversationId, platformId, log }: {
+ pieceName: string
+ actionName: string
+ projects: Project[]
+ availableProjectIds: string[]
+ conversationId?: string
+ platformId?: string
+ log: FastifyBaseLogger
+}): Promise<ActionTarget | { error: string }> {
+ const normalizedPiece = mcpUtils.normalizePieceName(pieceName) ?? pieceName
+ const selected = isNil(conversationId) ? null : await agentApprovalGate.getSelectedConnection({ conversationId, pieceName: normalizedPiece })
+ const connectionProjectId = selected?.projectId
+ const projectId = connectionProjectId ?? projects[0]?.id
+ if (!projectId) {
+ return { error: 'No projects available. Create a project first.' }
+ }
+ if (connectionProjectId && !availableProjectIds.includes(connectionProjectId)) {
+ return { error: `Project ${connectionProjectId} is not accessible.` }
+ }
+ const declared = await declaredActionOf({ pieceName: normalizedPiece, actionName, projectId, platformId, log })
+ return {
+ normalizedPiece,
+ projectId,
+ ...spreadIfDefined('connectionExternalId', selected?.externalId),
+ ...spreadIfDefined('connectionLabel', selected?.label),
+ declared,
+ }
+}
+
+async function declaredActionOf({ pieceName, actionName, projectId, platformId, log }: {
+ pieceName: string
+ actionName: string
+ projectId?: string
+ platformId?: string
+ log: FastifyBaseLogger
+}): Promise<DeclaredAction> {
+ if (isNil(platformId)) {
+ return {}
+ }
+ const { data: metadata } = await tryCatch(() => pieceMetadataService(log).get({ name: pieceName, projectId, platformId }))
+ const action = metadata?.actions?.[actionName]
+ return {
+ ...spreadIfDefined('pieceDisplayName', metadata?.displayName),
+ ...spreadIfDefined('actionDisplayName', action?.displayName),
+ ...spreadIfDefined('classification', action?.classification),
+ ...spreadIfDefined('readOnly', isNil(action?.classification) ? undefined : isReadOnlyClassification(action.classification)),
+ }
+}
+
+type ActionTarget = {
+ normalizedPiece: string
+ projectId: string
+ connectionExternalId?: string
+ connectionLabel?: string
+ declared: DeclaredAction
+}
+
+type DeclaredAction = {
+ pieceDisplayName?: string
+ actionDisplayName?: string
+ classification?: ActionClassification
+ readOnly?: boolean
+}
diff --git a/packages/server/api/test/integration/ee/agent/agent-action-audit.test.ts b/packages/server/api/test/integration/ee/agent/agent-action-audit.test.ts
index b7a9c355d5c..da74d7c9804 100644
--- a/packages/server/api/test/integration/ee/agent/agent-action-audit.test.ts
+++ b/packages/server/api/test/integration/ee/agent/agent-action-audit.test.ts
@@ -2,14 +2,15 @@ import { tryCatch } from '@activepieces/core-utils'
import { AgentActionKind, AgentActionOutcome, AgentIcon, AgentRunSource, AIProviderName, apId, ApplicationEvent, ApplicationEventName, ColorName, summarizeApplicationEvent } from '@activepieces/shared'
import { FastifyInstance } from 'fastify'
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
+import { agentApprovalGate } from '../../../../src/app/ee/agent/agent-approval-gate'
import { agentRpcHandlers } from '../../../../src/app/ee/agent/agent-rpc-handlers'
import { executeCrossProjectTool } from '../../../../src/app/ee/agent/tools/agent-tools'
import { pieceToolRunner } from '../../../../src/app/ee/agent/tools/piece-tool-runner'
import * as mcpServerBuilder from '../../../../src/app/mcp/mcp-server-builder'
import * as flowRunUtils from '../../../../src/app/mcp/tools/flow-run-utils'
+import * as pieceMetadataModule from '../../../../src/app/pieces/metadata/piece-metadata-service'
import { db } from '../../../helpers/db'
-import { createMockFlow, createMockFlowRun, createMockFlowVersion } from '../../../helpers/mocks'
-import { mockAndSaveAIProvider } from '../../../helpers/mocks'
+import { createMockFlow, createMockFlowRun, createMockFlowVersion, createMockProject, mockAndSaveAIProvider } from '../../../helpers/mocks'
import { createTestContext, TestContext } from '../../../helpers/test-context'
import { setupTestEnvironment, teardownTestEnvironment } from '../../../helpers/test-setup'
@@ -371,3 +372,86 @@ describe('an action an agent ran reaches the audit log', () => {
expect(JSON.stringify(row.data)).not.toContain(RECIPIENT)
})
})
+
+describe('a chat action the piece declares as a write', () => {
+ function declareAction(classification: string): void {
+ const metadata = { displayName: 'Gmail', actions: { mark_as_read: { displayName: 'Mark as read', classification } } }
+ vi.spyOn(pieceMetadataModule, 'pieceMetadataService').mockReturnValue({ get: async () => metadata } as never)
+ }
+
+ it('is refused by ap_explore_data and never runs, whatever its name says', async () => {
+ const ctx = await contextWithProvider()
+ const { conversationId } = await conversationFor(ctx, { source: AgentRunSource.CHAT, withAgent: false })
+ declareAction('WRITE')
+ const run = vi.spyOn(flowRunUtils, 'executePieceActionRun').mockResolvedValue({ content: [] } as never)
+
+ const result = await executeCrossProjectTool({
+ toolName: 'ap_explore_data',
+ toolInput: { pieceName: '@activepieces/piece-gmail', actionName: 'mark_as_read', input: {} },
+ platformId: ctx.platform.id,
+ userId: ctx.user.id,
+ conversationId,
+ log: app.log,
+ })
+
+ expect(result).toMatchObject({ success: false })
+ expect(run).not.toHaveBeenCalled()
+ })
+
+ it('still runs through ap_explore_data when the piece declares it a read', async () => {
+ const ctx = await contextWithProvider()
+ const { conversationId } = await conversationFor(ctx, { source: AgentRunSource.CHAT, withAgent: false })
+ declareAction('READ')
+ const run = vi.spyOn(flowRunUtils, 'executePieceActionRun').mockResolvedValue({ content: [] } as never)
+
+ await executeCrossProjectTool({
+ toolName: 'ap_explore_data',
+ toolInput: { pieceName: '@activepieces/piece-gmail', actionName: 'mark_as_read', input: {} },
+ platformId: ctx.platform.id,
+ userId: ctx.user.id,
+ conversationId,
+ log: app.log,
+ })
+
+ expect(run).toHaveBeenCalledTimes(1)
+ })
+
+ it('looks the action up in the project it will run in, the selected connection\'s', async () => {
+ const ctx = await contextWithProvider()
+ const { conversationId } = await conversationFor(ctx, { source: AgentRunSource.CHAT, withAgent: false })
+ const connectionProject = createMockProject({ ownerId: ctx.user.id, platformId: ctx.platform.id })
+ await db.save('project', connectionProject)
+ await agentApprovalGate.storeSelectedConnection({ conversationId, pieceName: '@activepieces/piece-gmail', externalId: 'gmail-work', label: 'Work Gmail', projectId: connectionProject.id })
+ const lookedUpIn: (string | undefined)[] = []
+ const metadata = { displayName: 'Gmail', actions: { mark_as_read: { displayName: 'Mark as read', classification: 'WRITE' } } }
+ vi.spyOn(pieceMetadataModule, 'pieceMetadataService').mockReturnValue({ get: async ({ projectId }: { projectId?: string }) => {
+ lookedUpIn.push(projectId)
+ return metadata
+ } } as never)
+ vi.spyOn(flowRunUtils, 'executePieceActionRun').mockResolvedValue({ content: [] } as never)
+ const request = { platformId: ctx.platform.id, userId: ctx.user.id, conversationId, log: app.log }
+
+ const { result: lookup } = await agentRpcHandlers(app.log).executeAgentTool({ platformId: ctx.platform.id, userId: ctx.user.id, conversationId, source: AgentRunSource.CHAT, toolName: '__action_read_only', toolInput: { pieceName: '@activepieces/piece-gmail', actionName: 'mark_as_read' } })
+ await executeCrossProjectTool({ ...request, toolName: 'ap_execute_action', toolInput: { pieceName: '@activepieces/piece-gmail', actionName: 'mark_as_read', input: {} } })
+
+ expect(lookup).toBe(false)
+ expect(new Set(lookedUpIn)).toEqual(new Set([connectionProject.id]))
+ })
+
+ it('tells the worker what the piece declares, so the approval card follows it', async () => {
+ const ctx = await contextWithProvider()
+ const { conversationId } = await conversationFor(ctx, { source: AgentRunSource.CHAT, withAgent: false })
+ declareAction('WRITE')
+
+ const { result } = await agentRpcHandlers(app.log).executeAgentTool({
+ toolName: '__action_read_only',
+ toolInput: { pieceName: '@activepieces/piece-gmail', actionName: 'mark_as_read' },
+ platformId: ctx.platform.id,
+ userId: ctx.user.id,
+ source: AgentRunSource.CHAT,
+ conversationId,
+ })
+
+ expect(result).toBe(false)
+ })
+})
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 992d7e32d1a..9d9370d8bf0 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
@@ -741,6 +741,11 @@ function buildToolSet({ ctx, eventEmitter, log, taintState, mcpToolSet, webTools
}))
}
+ const isDeclaredReadOnly = async ({ pieceName, actionName }: { pieceName: string, actionName: string }): Promise<boolean | undefined> => {
+ const { result } = await ctx.apiClient.executeAgentTool({ toolName: '__action_read_only', toolInput: { pieceName, actionName }, platformId, userId, source, conversationId })
+ return typeof result === 'boolean' ? result : undefined
+ }
+
const piecesTheAuthorGaveAnAccount = new Set(source !== AgentRunSource.AGENT ? [] : configuredPieceTools
.filter((tool) => !isNil(tool.pieceMetadata.predefinedInput?.auth))
.map((tool) => tool.pieceMetadata.pieceName))
@@ -778,7 +783,7 @@ function buildToolSet({ ctx, eventEmitter, log, taintState, mcpToolSet, webTools
onConnectorReconnected: (connectorUuid) => brokenConnectors.delete(connectorUuid),
onGateOpened: storePendingGate,
})
- const crossProjectTools = agentWorkerTools.createCrossProjectTools({ executeTool: executeCrossProjectTool, eventEmitter: toolEventEmitter, waitForApproval, onGateOpened: storePendingGate, taintState })
+ const crossProjectTools = agentWorkerTools.createCrossProjectTools({ executeTool: executeCrossProjectTool, eventEmitter: toolEventEmitter, waitForApproval, onGateOpened: storePendingGate, isDeclaredReadOnly, taintState })
const agentSurfaceTools = agentsAvailable && !dryRun && !discoveryOnly
? agentWorkerTools.createAgentSurfaceTools({ executeTool: executeCrossProjectTool, taintState, eventEmitter: toolEventEmitter, waitForApproval, onGateOpened: storePendingGate })
: {}
diff --git a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/cross-project-tools.ts b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/cross-project-tools.ts
index be2e58a2ba5..3d6fb7cf2d0 100644
--- a/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/cross-project-tools.ts
+++ b/packages/server/worker/src/lib/execute/jobs/ee/agent/tools/cross-project-tools.ts
@@ -43,11 +43,12 @@ function createProgressGuard() {
}
}
-export function createCrossProjectTools({ executeTool, eventEmitter, waitForApproval, onGateOpened, taintState }: {
+export function createCrossProjectTools({ executeTool, eventEmitter, waitForApproval, onGateOpened, isDeclaredReadOnly, taintState }: {
executeTool: (toolName: string, toolInput: Record<string, unknown>) => Promise<unknown>
eventEmitter: AgentEventEmitter
waitForApproval: (params: { gateId: string, timeoutMs?: number }) => Promise<GateDecision>
onGateOpened?: (params: { gateId: string, toolName: string, displayName: string, toolInput: Record<string, unknown> }) => Promise<void>
+ isDeclaredReadOnly?: (params: { pieceName: string, actionName: string }) => Promise<boolean | undefined>
taintState: TaintState
}): ToolSet {
const progressGuard = createProgressGuard()
@@ -103,12 +104,14 @@ export function createCrossProjectTools({ executeTool, eventEmitter, waitForAppr
return guardResult
}
}
+ const { data: declaredReadOnly } = await tryCatch(async () => isDeclaredReadOnly?.({ pieceName: toolInput.pieceName, actionName: toolInput.actionName }))
const executedInputs = isBatch ? toolInput.items! : [toolInput.input ?? {}]
const gatedInputs = executedInputs.filter((input) => agentToolClassification.requiresActionPreview({
actionName: toolInput.actionName,
input,
needsConfirmation: toolInput.needsConfirmation,
tainted: taintState.tainted,
+ declaredReadOnly: declaredReadOnly ?? undefined,
}))
const needsPreview = gatedInputs.length > 0
taintState.tainted = true
@@ -175,6 +178,7 @@ export function createCrossProjectTools({ executeTool, eventEmitter, waitForAppr
const isReadOnly = agentToolClassification.isReadOnlyActionCall({
actionName: toolInput.actionName,
input: toolInput.input,
+ declaredReadOnly: declaredReadOnly ?? undefined,
})
if (!isReadOnly) {
eventEmitter.emitActionReceipt({
@@ -214,9 +218,6 @@ export function createCrossProjectTools({ executeTool, eventEmitter, waitForAppr
input: z.record(z.string(), z.unknown()).optional().describe('Input for the read action (keep limits small)'),
}),
execute: async (toolInput) => {
- if (!agentToolClassification.isReadOnlyActionCall({ actionName: toolInput.actionName, input: toolInput.input })) {
- return agentToolClassification.readOnlyRejection(toolInput.actionName)
- }
taintState.tainted = true
const rawResult = await executeWithTimeout('ap_explore_data', toolInput)
return truncateLargeResult(rawResult)
diff --git a/packages/server/worker/test/lib/agent/taints-turn.test.ts b/packages/server/worker/test/lib/agent/taints-turn.test.ts
index e6dc22f54cd..dfefe0e97f8 100644
--- a/packages/server/worker/test/lib/agent/taints-turn.test.ts
+++ b/packages/server/worker/test/lib/agent/taints-turn.test.ts
@@ -167,6 +167,61 @@ describe('ap_execute_action batch approval', () => {
})
})
+describe('ap_execute_action with a declared classification', () => {
+ const declaredTools = ({ declaredReadOnly }: { declaredReadOnly: boolean | null }) => {
+ let asked = false
+ const tools = agentWorkerTools.createCrossProjectTools({
+ executeTool: async () => ({ success: true, content: [{ type: 'text', text: 'done' }] }),
+ isDeclaredReadOnly: async () => declaredReadOnly ?? undefined,
+ eventEmitter: agentWorkerTools.createEventEmitter({ sendEvent: async () => undefined, userId: 'user-1', conversationId: 'conv-1' }),
+ waitForApproval: async () => {
+ asked = true
+ return { outcome: 'approved' as const }
+ },
+ guides: {},
+ taintState: { tainted: false },
+ })
+ return { tools, wasAsked: () => asked }
+ }
+ const markAsRead = { pieceName: '@activepieces/piece-gmail', actionName: 'mark_as_read', input: {}, needsConfirmation: false }
+
+ it('asks before an action the piece declares as a write, even when its name reads like a read', async () => {
+ const { tools, wasAsked } = declaredTools({ declaredReadOnly: false })
+
+ await tools.ap_execute_action.execute?.(markAsRead, options)
+
+ expect(wasAsked()).toBe(true)
+ })
+
+ it('falls back to the action name when the piece declares nothing', async () => {
+ const { tools, wasAsked } = declaredTools({ declaredReadOnly: null })
+
+ await tools.ap_execute_action.execute?.(markAsRead, options)
+
+ expect(wasAsked()).toBe(false)
+ })
+})
+
+describe('ap_explore_data leaves the read-or-write call to the API', () => {
+ it('sends an action whose name proves nothing to the API, which knows what the piece declares', async () => {
+ const sent: string[] = []
+ const tools = agentWorkerTools.createCrossProjectTools({
+ executeTool: async (toolName) => {
+ sent.push(toolName)
+ return { success: true, content: [{ type: 'text', text: 'rows' }] }
+ },
+ eventEmitter: agentWorkerTools.createEventEmitter({ sendEvent: async () => undefined, userId: 'user-1', conversationId: 'conv-1' }),
+ waitForApproval: async () => ({ outcome: 'approved' as const }),
+ guides: {},
+ taintState: { tainted: false },
+ })
+
+ await tools.ap_explore_data.execute?.({ pieceName: '@activepieces/piece-text-helper', actionName: 'split', input: {} }, options)
+
+ expect(sent).toEqual(['ap_explore_data'])
+ })
+})
+
describe('previousReplyReadData', () => {
const reply = (tainted?: boolean) => ({ role: 'assistant', parts: [], ...(tainted === undefined ? {} : { tainted }) })
const user = { role: 'user', parts: [] }
diff --git a/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts b/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts
index 5fe8eac887f..8dffc061fe8 100644
--- a/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts
+++ b/packages/web/src/app/routes/chat-with-ai/lib/message-blocks.ts
@@ -122,7 +122,13 @@ export function buildMessageBlocks({
// would mislabel a completed card as failed. Batch executions stream their
// own live progress, so skip those too.
const cardKind = chatPartUtils.getPendingCardKind(toolName);
- if (isStreaming && cardKind && !toolCallMeta[toolCallId]?.batchProgress) {
+ const finishedWithoutCard = p.state === 'output-available';
+ if (
+ isStreaming &&
+ cardKind &&
+ !finishedWithoutCard &&
+ !toolCallMeta[toolCallId]?.batchProgress
+ ) {
const state = p.state;
const phase: CardSkeletonPhase =
state === 'output-error' || state === 'output-denied'
diff --git a/packages/web/test/app/routes/chat-with-ai/lib/message-blocks.test.ts b/packages/web/test/app/routes/chat-with-ai/lib/message-blocks.test.ts
index 24327be2e80..19203de2991 100644
--- a/packages/web/test/app/routes/chat-with-ai/lib/message-blocks.test.ts
+++ b/packages/web/test/app/routes/chat-with-ai/lib/message-blocks.test.ts
@@ -317,6 +317,24 @@ describe('buildMessageBlocks — one accordion per segment', () => {
expect(blocks.map((b) => b.kind)).toEqual(['thinking', 'card-skeleton']);
});
+ it('drops the skeleton once an action finishes without a receipt, as a declared read does', () => {
+ const blocks = buildMessageBlocks({
+ parts: [
+ status('Splitting the text'),
+ tool({
+ name: 'ap_execute_action',
+ id: 'exec',
+ input: { actionName: 'split', input: {} },
+ output: { success: true },
+ }),
+ ],
+ isStreaming: true,
+ toolCallMeta: {},
+ claimedBuildIds: new Set(),
+ }).blocks;
+ expect(blocks.map((b) => b.kind)).toEqual(['thinking']);
+ });
+
it('keeps pre-build discovery above the build card', () => {
const blocks = buildMessageBlocks({
parts: [