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

5.6 KB
Raw Blame
import { PredefinedInputsStructure } from '@activepieces/core-piece-types'
import { ActivepiecesError, connectionTemplate, ErrorCode, isNil, spreadIfDefined } from '@activepieces/core-utils'
import { ActionClassification } from '@activepieces/pieces-framework'
import { McpToolResult } from '@activepieces/shared'
import { LanguageModel } from 'ai'
import { FastifyBaseLogger } from 'fastify'
import { executePieceActionRun } from '../../../mcp/tools/flow-run-utils'
import { mcpUtils } from '../../../mcp/tools/mcp-utils'
import { pieceMetadataService } from '../../../pieces/metadata/piece-metadata-service'
import { pieceInputFiller, ResolveProperty } from './piece-input-filler'

async function resolveInput({ piece, instruction, predefinedInput, model, projectId, platformId, connectionExternalId, log }: ResolveInputParams): Promise<ResolvedPieceInput> {
    const { properties, pieceVersion, actionDisplayName, pieceDisplayName, classification } = await resolveAction({ piece, platformId, log })
    const account = connectionExternalId ?? connectionTemplate.unwrapExternalId(predefinedInput?.auth) ?? undefined
    const resolvedInput = await pieceInputFiller.fillInput({
        action: { name: piece.actionName, properties, ...spreadIfDefined('connectionExternalId', account) },
        instruction,
        ...(isNil(predefinedInput) && isNil(account) ? {} : { predefinedInput: { fields: predefinedInput?.fields ?? {}, ...spreadIfDefined('auth', account) } }),
        ports: {
            resolveProperty: propertyResolverFor({ piece, pieceVersion, projectId, platformId, log }),
            completeObject: pieceInputFiller.modelCompleter(model),
        },
    })

    assertUrlStaysOnThePieceHost({ actionName: piece.actionName, input: resolvedInput })

    return { resolvedInput, actionDisplayName, pieceDisplayName, ...spreadIfDefined('classification', classification) }
}

function withoutCredential(input: Record<string, unknown>): Record<string, unknown> {
    return { ...input, ...(isNil(input.auth) ? {} : { auth: REDACTED_AUTH }) }
}

async function runResolved({ piece, resolvedInput, projectId, connectionExternalId, log }: {
    piece: PieceActionRef
    resolvedInput: Record<string, unknown>
    projectId: string
    connectionExternalId?: string
    log: FastifyBaseLogger
}): Promise<PieceToolRun> {
    const result = await executePieceActionRun({
        projectId,
        pieceName: piece.pieceName,
        actionName: piece.actionName,
        input: resolvedInput,
        log,
        ...(isNil(connectionExternalId) ? {} : { connectionExternalId }),
    })

    return { result, resolvedInput: withoutCredential(resolvedInput) }
}

async function resolveAction({ piece, platformId, log }: { piece: PieceActionRef, platformId: string, log: FastifyBaseLogger }) {
    const metadata = await pieceMetadataService(log).getOrThrow({
        platformId,
        name: piece.pieceName,
        version: piece.pieceVersion,
    })
    const action = metadata.actions[piece.actionName]
    if (isNil(action)) {
        throw new ActivepiecesError({
            code: ErrorCode.ENTITY_NOT_FOUND,
            params: { entityType: 'PieceAction', entityId: `${piece.pieceName}:${piece.actionName}` },
        })
    }
    return { properties: action.props, pieceVersion: metadata.version, actionDisplayName: action.displayName, pieceDisplayName: metadata.displayName, classification: action.classification }
}

function propertyResolverFor({ piece, pieceVersion, projectId, platformId, log }: {
    piece: PieceActionRef
    pieceVersion: string
    projectId: string
    platformId: string
    log: FastifyBaseLogger
}): ResolveProperty {
    return ({ propertyName, actionOrTriggerName, input, auth }) => {
        return mcpUtils.executePropertyResolution({
            pieceName: piece.pieceName,
            pieceVersion,
            actionOrTriggerName,
            propertyName,
            input,
            projectId,
            platformId,
            log,
            ...(isNil(auth) ? {} : { auth }),
        })
    }
}

function assertUrlStaysOnThePieceHost({ actionName, input }: { actionName: string, input: Record<string, unknown> }): void {
    if (actionName !== CUSTOM_API_CALL) {
        return
    }
    const url = input.url
    const value = typeof url === 'string' ? url : (typeof url === 'object' && !isNil(url) && 'url' in url && typeof url.url === 'string' ? url.url : undefined)
    if (isNil(value) || !ABSOLUTE_URL.test(value)) {
        return
    }
    throw new ActivepiecesError({
        code: ErrorCode.VALIDATION,
        params: { message: `A custom API call from an agent step must be a path on the connection's own API, not the full address "${value}". Sending this project's credentials somewhere the connection does not belong is not something an unattended run may do.` },
    })
}

const CUSTOM_API_CALL = 'custom_api_call'
const ABSOLUTE_URL = /^https?:\/\//i
const REDACTED_AUTH = 'Redacted'

export const pieceToolRunner = {
    resolveInput,
    runResolved,
    withoutCredential,
}

export type PieceActionRef = {
    pieceName: string
    actionName: string
    pieceVersion?: string
}

export type ResolveInputParams = {
    piece: PieceActionRef
    instruction: string
    predefinedInput?: PredefinedInputsStructure
    model: LanguageModel
    projectId: string
    platformId: string
    connectionExternalId?: string
    log: FastifyBaseLogger
}

export type ResolvedPieceInput = {
    resolvedInput: Record<string, unknown>
    actionDisplayName: string
    pieceDisplayName: string
    classification?: ActionClassification
}

export type PieceToolRun = {
    result: McpToolResult
    resolvedInput: Record<string, unknown>
}