diff --git a/src/errors.ts b/src/errors.ts index 16042291a..1642ac372 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -19,6 +19,7 @@ export const ACTOR_LOAD_ERROR_KIND = { NOT_FOUND: 'not-found', LOAD_FAILED: 'load-failed', STANDBY_PAYMENT_NOT_SUPPORTED: 'standby-payment-not-supported', + STANDBY_WITHOUT_MCP_NOT_SUPPORTED: 'standby-without-mcp-not-supported', } as const; export type ActorLoadErrorKind = (typeof ACTOR_LOAD_ERROR_KIND)[keyof typeof ACTOR_LOAD_ERROR_KIND]; @@ -63,11 +64,21 @@ export class ActorLoadError extends Error { ); } + static standbyWithoutMcpNotSupported(actorName: string): ActorLoadError { + return new ActorLoadError( + ACTOR_LOAD_ERROR_KIND.STANDBY_WITHOUT_MCP_NOT_SUPPORTED, + actorName, + `Actor "${actorName}" runs in standby mode without an MCP server and has an empty input schema,` + + ' which is not supported yet.', + ); + } + static standbyPaymentNotSupported(actorName: string): ActorLoadError { return new ActorLoadError( ACTOR_LOAD_ERROR_KIND.STANDBY_PAYMENT_NOT_SUPPORTED, actorName, - `Actor "${actorName}" is a standby Actor, which is not supported in agentic payment mode. Please use OAuth or direct Apify token authentication in order to use standby Actors.`, + `Actor "${actorName}" is a standby Actor, which is not supported in agentic payment mode.` + + ' Please use OAuth or direct Apify token authentication in order to use standby Actors.', ); } } diff --git a/src/tools/actor_tool_naming.ts b/src/tools/actor_tool_naming.ts index 87673edae..a6b912300 100644 --- a/src/tools/actor_tool_naming.ts +++ b/src/tools/actor_tool_naming.ts @@ -4,12 +4,30 @@ import log from '@apify/log'; import { MAX_TOOL_NAME_LENGTH, TOOL_NAME_HASH_LENGTH } from '../mcp/const.js'; import type { ActorInfo } from '../types.js'; +import { ACTOR_TOOL_MODE } from '../types.js'; -/* - * Checks if the given ActorInfo represents an MCP server Actor. +/** + * The single rule for how an Actor is exposed as a tool. Tool loading and `call-actor` routing both + * read it, so the two can never disagree. + * + * | standby | `webServerMcpPath` | input schema | result | + * |----------|--------------------|--------------|-----------------------| + * | disabled | any (path ignored) | any | `RUN` | + * | enabled | present | any | `MCP` | + * | enabled | absent | non-empty | `RUN` | + * | enabled | absent | empty | `STANDBY_WITHOUT_MCP` | + * + * The input schema counts as empty when the definition has no `input`, `input.properties` is missing, + * or `input.properties` has zero keys. Nothing else counts — a non-empty `required` with no properties + * still reads as empty. */ -export function isActorInfoMcpServer(actorInfo: ActorInfo): boolean { - return !!(actorInfo.webServerMcpPath && actorInfo.actor.actorStandby?.isEnabled); +export function resolveActorToolMode(actorInfo: ActorInfo): ACTOR_TOOL_MODE { + if (actorInfo.actor.actorStandby?.isEnabled !== true) return ACTOR_TOOL_MODE.RUN; + if (actorInfo.webServerMcpPath) return ACTOR_TOOL_MODE.MCP; + if (Object.keys(actorInfo.definition.input?.properties ?? {}).length === 0) { + return ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP; + } + return ACTOR_TOOL_MODE.RUN; } /** @@ -18,8 +36,8 @@ export function isActorInfoMcpServer(actorInfo: ActorInfo): boolean { * List-time filtering in `getActorsAsTools` and the call-time guard in * `checkPaymentProviderStandbyConflict` must use this — not MCP URL presence alone. */ -export function isActorBlockedUnderPaymentProvider(actorInfo: ActorInfo): boolean { - return !!actorInfo.actor.actorStandby?.isEnabled; +export function isActorBlockedUnderPaymentProvider(actor: Pick): boolean { + return actor.actorStandby?.isEnabled === true; } /** Splits an Actor full name; a missing slash yields a null username. */ diff --git a/src/tools/actors/actor_tools_factory.ts b/src/tools/actors/actor_tools_factory.ts index 911af7e5b..db8bc8d6b 100644 --- a/src/tools/actors/actor_tools_factory.ts +++ b/src/tools/actors/actor_tools_factory.ts @@ -5,6 +5,7 @@ import log from '@apify/log'; import type { ApifyClient } from '../../apify_client.js'; import { ACTOR_MAX_MEMORY_MBYTES, + FAILURE_CATEGORY, HELPER_TOOLS, RAG_WEB_BROWSER, RAG_WEB_BROWSER_ADDITIONAL_DESC, @@ -24,6 +25,7 @@ import { type ApifyToken, type ToolEntry, type ToolInputSchema, + ACTOR_TOOL_MODE, TOOL_TYPE, } from '../../types.js'; import { getActorDefinitionCached } from '../../utils/actor.js'; @@ -31,7 +33,7 @@ import { ajv } from '../../utils/ajv.js'; import { stripQuoteWrappers } from '../../utils/generic.js'; import { logHttpError } from '../../utils/logging.js'; import { buildActorInputSchema, fixedAjvCompile } from '../actor_input_schema.js'; -import { actorNameToToolName, isActorBlockedUnderPaymentProvider, isActorInfoMcpServer } from '../actor_tool_naming.js'; +import { actorNameToToolName, isActorBlockedUnderPaymentProvider, resolveActorToolMode } from '../actor_tool_naming.js'; import { buildEnrichedDirectActorOutputSchema, actorRunOutputSchema } from '../structured_output_schemas.js'; import { CALL_ACTOR_WAIT_SECS_DEFAULT, WAIT_SECS_MAX } from './actor_run_response.js'; @@ -368,12 +370,24 @@ export async function getActorsAsTools( const actorMCPServersInfo: ActorInfo[] = []; const normalActorsInfo: ActorInfo[] = []; for (const actorInfo of nonNullActors) { - const isMcpServer = isActorInfoMcpServer(actorInfo); - if (paymentProvider && isActorBlockedUnderPaymentProvider(actorInfo)) { + if (paymentProvider && isActorBlockedUnderPaymentProvider(actorInfo.actor)) { errors.push(ActorLoadError.standbyPaymentNotSupported(actorInfo.definition.actorFullName)); continue; } - if (isMcpServer) actorMCPServersInfo.push(actorInfo); + + const toolMode = resolveActorToolMode(actorInfo); + if (toolMode === ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP) { + const error = ActorLoadError.standbyWithoutMcpNotSupported(actorInfo.definition.actorFullName); + log.softFail('Skipping standby Actor with no MCP server and an empty input schema', { + actorName: actorInfo.definition.actorFullName, + mcpSessionId, + actorLoadErrorKind: error.kind, + failureCategory: FAILURE_CATEGORY.INVALID_INPUT, + }); + errors.push(error); + continue; + } + if (toolMode === ACTOR_TOOL_MODE.MCP) actorMCPServersInfo.push(actorInfo); else normalActorsInfo.push(actorInfo); } diff --git a/src/tools/actors/call_actor.ts b/src/tools/actors/call_actor.ts index 61252291b..c3ea6adef 100644 --- a/src/tools/actors/call_actor.ts +++ b/src/tools/actors/call_actor.ts @@ -18,16 +18,9 @@ import { ACTOR_LOAD_ERROR_KIND, ActorLoadError } from '../../errors.js'; import { connectMCPClient } from '../../mcp/client.js'; import { EXTERNAL_TOOL_CALL_TIMEOUT_MSEC } from '../../mcp/const.js'; import type { PaymentProvider } from '../../payments/types.js'; -import type { - ActorInfo, - ApifyToken, - InternalToolArgs, - ToolDescriptionContext, - ToolEntry, - ToolInputSchema, -} from '../../types.js'; -import { ALL_TOOLS_PRESENT, TOOL_TYPE } from '../../types.js'; -import { getActorDefinitionCached, getActorMcpUrlCached } from '../../utils/actor.js'; +import type { ApifyToken, InternalToolArgs, ToolDescriptionContext, ToolEntry, ToolInputSchema } from '../../types.js'; +import { ACTOR_TOOL_MODE, ALL_TOOLS_PRESENT, TOOL_TYPE } from '../../types.js'; +import { getActorDefinitionCached, getActorToolResolutionCached } from '../../utils/actor.js'; import { compileSchema } from '../../utils/ajv.js'; import { ACTOR_RUN_LIMIT_MESSAGE, @@ -176,6 +169,47 @@ export function buildCallActorAppsDescription(ctx: ToolDescriptionContext = ALL_ return buildCallActorDescriptionSections(true, ctx); } +/** + * Rejection for an Actor whose standby configuration `call-actor` cannot serve. softFail, not + * logHttpError: the caller asked for an Actor we cannot expose, so this is a client fault and + * must not raise an error-level alert. + */ +function respondStandbyRejection( + error: ActorLoadError, + opts: { mcpSessionId?: string; actorId?: string; paymentProviderId?: string }, +): ToolResponse { + log.softFail('Rejecting call-actor for unsupported standby Actor', { + // The error's canonical Actor name, so both call shapes log the same value even when the + // caller addressed the Actor by ID. `actorLoadErrorKind` distinguishes which cell rejected it. + actorName: error.actorName, + mcpSessionId: opts.mcpSessionId, + paymentProviderId: opts.paymentProviderId, + actorLoadErrorKind: error.kind, + failureCategory: FAILURE_CATEGORY.INVALID_INPUT, + }); + return respondUserError(error.message, { actorId: opts.actorId, detail: error.kind }); +} + +/** + * Canonical "Actor not found" answer, shared by the run path and the `actor:toolName` route so an + * unknown Actor gets the same response regardless of call shape. + */ +function respondActorNotFound(actorName: string, loadedToolNames: readonly string[]): ToolResponse { + // See apify/apify-mcp-server#1296. + // Only search-actors: the Actor does not exist, so buildCallFailureRecoveryHint's second + // offer (get Actor details) would send the model to a lookup that fails the same way. + const recovery = loadedToolNames.includes(HELPER_TOOLS.STORE_SEARCH) + ? `\nYou can search for available Actors using the tool: ${HELPER_TOOLS.STORE_SEARCH}.` + : ''; + return respondUserError( + dedent` + Actor '${actorName}' was not found. + Please verify Actor ID or name format (e.g., "username/name" like "apify/rag-web-browser") and ensure that the Actor exists. + ` + recovery, + { httpStatus: 404, detail: `Actor '${actorName}' was not found` }, + ); +} + export function buildCallActorErrorResponse(params: CallActorErrorResponseParams): ToolResponse { const { actorName, error, actorId, mcpSessionId, loadedToolNames, inputSchema } = params; @@ -193,6 +227,16 @@ export function buildCallActorErrorResponse(params: CallActorErrorResponseParams }); } + // The two standby kinds are sanitized, user-facing reasons — forward them verbatim instead of + // wrapping them in the generic server-error text. LOAD_FAILED masks a backend fault and stays below. + if ( + error instanceof ActorLoadError && + (error.kind === ACTOR_LOAD_ERROR_KIND.STANDBY_WITHOUT_MCP_NOT_SUPPORTED || + error.kind === ACTOR_LOAD_ERROR_KIND.STANDBY_PAYMENT_NOT_SUPPORTED) + ) { + return respondStandbyRejection(error, { mcpSessionId, actorId }); + } + const errMsg = error instanceof Error ? error.message : String(error); logHttpError(error, 'Failed to call Actor', { actorName, @@ -329,24 +373,13 @@ export async function checkPaymentProviderStandbyConflict(params: { return null; } - const actorInfo: ActorInfo = { - definition: actorDefinitionWithInfo.definition, - actor: actorDefinitionWithInfo.info, - webServerMcpPath: null, - }; - - if (!isActorBlockedUnderPaymentProvider(actorInfo)) { + if (!isActorBlockedUnderPaymentProvider(actorDefinitionWithInfo.info)) { return null; } - log.softFail('Rejecting call-actor for standby Actor under third-party payment provider', { - actorName: baseActorName, - paymentProviderId: paymentProvider.id, - mcpSessionId, - failureCategory: FAILURE_CATEGORY.INVALID_INPUT, - }); - - return respondUserError(ActorLoadError.standbyPaymentNotSupported(normalizedActorName).message); + // Canonical name, not the caller's identifier — it may be an Actor ID or carry a `:toolName` suffix. + const error = ActorLoadError.standbyPaymentNotSupported(actorDefinitionWithInfo.definition.actorFullName); + return respondStandbyRejection(error, { mcpSessionId, paymentProviderId: paymentProvider.id }); } /** @@ -368,25 +401,19 @@ export function resolveActorContext(actorName: string): { } /** - * Handles the MCP tool call flow (when actorName contains ":toolName"). - * Returns a response if handled, or null if this is not an MCP tool call. + * Proxies the MCP tool call flow (when actorName contains ":toolName"). The caller routes here only + * for {@link ACTOR_TOOL_MODE.MCP} Actors, so `mcpServerUrl` is always known good. */ export async function handleMcpToolCall(params: { baseActorName: string; mcpToolName: string; input: Record; - isActorMcpServer: boolean; - mcpServerUrl: string | false; + mcpServerUrl: string; apifyToken: string; mcpSessionId?: string; signal: AbortSignal; -}): Promise { - const { baseActorName, mcpToolName, input, isActorMcpServer, mcpServerUrl, apifyToken, mcpSessionId, signal } = - params; - - if (!isActorMcpServer) { - return respondServerError(`Actor '${baseActorName}' is not an MCP server.`); - } +}): Promise { + const { baseActorName, mcpToolName, input, mcpServerUrl, apifyToken, mcpSessionId, signal } = params; if (!input) { return respondServerError( @@ -400,7 +427,7 @@ export async function handleMcpToolCall(params: { let client: Client | null = null; try { - client = await connectMCPClient(mcpServerUrl as string, apifyToken, mcpSessionId); + client = await connectMCPClient(mcpServerUrl, apifyToken, mcpSessionId); if (!client) { return respondServerError(`Failed to connect to MCP server ${mcpServerUrl}`); } @@ -472,30 +499,18 @@ export async function resolveAndValidateActor(params: { }); // NOT_FOUND falls through to the structured "Actor not found" response below. - // Any other error (LOAD_FAILED / STANDBY_PAYMENT_NOT_SUPPORTED) is rethrown so the - // outer call-actor handler reports it; STANDBY is also caught upstream by the - // call-time guard in server.ts, so it's a defensive fallback here. + // Any other error (LOAD_FAILED / STANDBY_PAYMENT_NOT_SUPPORTED / + // STANDBY_WITHOUT_MCP_NOT_SUPPORTED) is rethrown so the outer call-actor handler reports it. + // STANDBY_PAYMENT_NOT_SUPPORTED cannot actually appear here: the call above passes no + // `paymentProvider`, so `getActorsAsTools`' payment gate never fires. Kept in the list because + // the rethrow is keyed on "not NOT_FOUND", not on an enumeration of kinds. if (errors[0] && errors[0].kind !== ACTOR_LOAD_ERROR_KIND.NOT_FOUND) { throw errors[0]; } const actor = tools[0]; if (!actor) { - // See apify/apify-mcp-server#1296. - // Only search-actors: the Actor does not exist, so buildCallFailureRecoveryHint's second - // offer (get Actor details) would send the model to a lookup that fails the same way. - const recovery = loadedToolNames.includes(HELPER_TOOLS.STORE_SEARCH) - ? `\nYou can search for available Actors using the tool: ${HELPER_TOOLS.STORE_SEARCH}.` - : ''; - return { - error: respondUserError( - dedent` - Actor '${actorName}' was not found. - Please verify Actor ID or name format (e.g., "username/name" like "apify/rag-web-browser") and ensure that the Actor exists. - ` + recovery, - { httpStatus: 404, detail: `Actor '${actorName}' was not found` }, - ), - }; + return { error: respondActorNotFound(actorName, loadedToolNames) }; } const actorId = extractActorId(actor); @@ -575,7 +590,7 @@ export async function callActorPreExecute( mcpToolName: string | undefined; } > { - const { args, apifyToken, mcpSessionId } = toolArgs; + const { args, apifyToken, mcpSessionId, loadedToolNames } = toolArgs; const parsedArgs = callActorArgs.parse(args); const actorName = fixActorNameInputAndLog(parsedArgs.actor, { mcpSessionId, route: options.route }); const parsed: CallActorParsedArgs = { ...parsedArgs, actor: actorName }; @@ -584,10 +599,20 @@ export async function callActorPreExecute( // For definition resolution we always use a token-based client; payment provider is only for actual Actor runs. // Standby/MCP-server Actors under a third-party payment provider are rejected upstream by - // `checkPaymentProviderStandbyConflict` in the generic tool-call handler — see src/mcp/server.ts. + // `checkPaymentProviderStandbyConflict` — see src/mcp/tool_call_engine.ts. const apifyClientForDefinition = new ApifyClient({ token: apifyToken }); - const mcpServerUrlOrFalse = await getActorMcpUrlCached(baseActorName, apifyClientForDefinition); - const isActorMcpServer = !!mcpServerUrlOrFalse; + const resolution = await getActorToolResolutionCached(baseActorName, apifyClientForDefinition); + + if (resolution?.toolMode === ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP) { + return { + earlyResponse: respondStandbyRejection( + ActorLoadError.standbyWithoutMcpNotSupported(resolution.actorFullName), + { mcpSessionId }, + ), + }; + } + + const isActorMcpServer = resolution?.toolMode === ACTOR_TOOL_MODE.MCP; // Handle the case where LLM does not respect instructions when calling MCP server Actors // and does not provide the tool name. @@ -598,21 +623,29 @@ export async function callActorPreExecute( }; } - // Handle MCP tool calls + // A `:toolName` suffix only means anything for an MCP-server Actor; every other mode is a dead end. if (mcpToolName) { - const mcpResult = await handleMcpToolCall({ - baseActorName, - mcpToolName, - input: parsed.input as Record, - isActorMcpServer, - mcpServerUrl: mcpServerUrlOrFalse, - apifyToken, - mcpSessionId, - signal: toolArgs.signal, - }); - if (mcpResult) { - return { earlyResponse: mcpResult }; + if (resolution === null) { + return { earlyResponse: respondActorNotFound(baseActorName, loadedToolNames) }; } + if (resolution.toolMode !== ACTOR_TOOL_MODE.MCP) { + return { + earlyResponse: respondUserError(`Actor '${resolution.actorFullName}' is not an MCP server.`, { + detail: 'tool name given for a non-MCP Actor', + }), + }; + } + return { + earlyResponse: await handleMcpToolCall({ + baseActorName, + mcpToolName, + input: parsed.input as Record, + mcpServerUrl: resolution.mcpServerUrl, + apifyToken, + mcpSessionId, + signal: toolArgs.signal, + }), + }; } return { parsed, baseActorName, mcpToolName }; diff --git a/src/types.ts b/src/types.ts index 764ce323a..45db53a09 100644 --- a/src/types.ts +++ b/src/types.ts @@ -133,6 +133,14 @@ export const TOOL_TYPE = { */ export type TOOL_TYPE = (typeof TOOL_TYPE)[keyof typeof TOOL_TYPE]; +/** How an Actor definition maps to the tool surface. */ +export const ACTOR_TOOL_MODE = { + RUN: 'RUN', + MCP: 'MCP', + STANDBY_WITHOUT_MCP: 'STANDBY_WITHOUT_MCP', +} as const; +export type ACTOR_TOOL_MODE = (typeof ACTOR_TOOL_MODE)[keyof typeof ACTOR_TOOL_MODE]; + /** * Type for Actor-based tools - tools that wrap Apify Actors. * Type discriminator: {@link TOOL_TYPE.ACTOR} @@ -255,11 +263,23 @@ export type TelemetryEnv = (typeof TELEMETRY_ENV)[keyof typeof TELEMETRY_ENV]; * Type representing the Actor information needed in order to turn it into an MCP server tool. */ export type ActorInfo = { - webServerMcpPath: string | null; // To determined if the Actor is an MCP server + webServerMcpPath: string | null; // Declared MCP endpoint; only means MCP when standby is on — see `resolveActorToolMode` definition: ActorDefinitionPruned; actor: ActorOutdated; }; +/** + * How an Actor is exposed as a tool, resolved once from its definition by `resolveActorToolMode`. + * `mcpServerUrl` is present exactly when `toolMode` is {@link ACTOR_TOOL_MODE.MCP}, so callers + * connect without a cast and an un-narrowed read is a compile error. + * `actorFullName` is the platform-canonical `username/name`, not whatever identifier the caller used — + * messages built from it read the same whether the Actor was addressed by ID or by name. + */ +export type ActorToolResolutionResult = { actorFullName: string } & ( + | { toolMode: typeof ACTOR_TOOL_MODE.MCP; mcpServerUrl: string } + | { toolMode: typeof ACTOR_TOOL_MODE.RUN | typeof ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP } +); + export type ActorStoreList = ActorStoreListOutdated & { actorReviewCount?: number; actorReviewRating?: number; diff --git a/src/utils/actor.ts b/src/utils/actor.ts index 17af636d4..bb3ffdd6d 100644 --- a/src/utils/actor.ts +++ b/src/utils/actor.ts @@ -1,8 +1,10 @@ import type { ApifyClient } from '../apify_client.js'; import { getActorMCPServerPath, getActorMCPServerURL } from '../mcp/actors.js'; import { actorDefinitionCache } from '../state.js'; +import { resolveActorToolMode } from '../tools/actor_tool_naming.js'; import { getActorDefinition } from '../tools/actors/actor_definition.js'; -import type { ActorDefinitionWithInfo } from '../types.js'; +import type { ActorDefinitionWithInfo, ActorToolResolutionResult } from '../types.js'; +import { ACTOR_TOOL_MODE } from '../types.js'; import { getUserInfoCached } from './userid_cache.js'; /** @@ -44,13 +46,34 @@ export async function getActorDefinitionCached( } /** - * Resolve the Actor's MCP server URL, or `false` if it isn't an MCP server. The URL is a pure function of + * Resolve how an Actor is exposed as a tool at call time, by name. The only place `resolveActorToolMode` + * is consulted outside the tool-loading factory, so `call-actor` routing and tool loading share one rule. + * + * Returns `null` when there is no definition to classify (unknown Actor). The URL is a pure function of * the definition (`getActorMCPServerURL` does no I/O), so this rides the authorization-gated * `getActorDefinitionCached` instead of a separate cache that would leak a private Actor's URL across tenants. */ -export async function getActorMcpUrlCached(actorIdOrName: string, apifyClient: ApifyClient): Promise { - const definition = (await getActorDefinitionCached(actorIdOrName, apifyClient))?.definition; - const mcpPath = definition && getActorMCPServerPath(definition); - if (!mcpPath) return false; - return getActorMCPServerURL(definition.id, mcpPath); +export async function getActorToolResolutionCached( + actorIdOrName: string, + apifyClient: ApifyClient, +): Promise { + const cached = await getActorDefinitionCached(actorIdOrName, apifyClient); + if (!cached) return null; + + const webServerMcpPath = getActorMCPServerPath(cached.definition); + const toolMode = resolveActorToolMode({ + definition: cached.definition, + actor: cached.info, + webServerMcpPath, + }); + const { actorFullName } = cached.definition; + // `resolveActorToolMode` returns MCP only when `webServerMcpPath` is set. + if (toolMode === ACTOR_TOOL_MODE.MCP) { + return { + toolMode, + mcpServerUrl: await getActorMCPServerURL(cached.definition.id, webServerMcpPath!), + actorFullName, + }; + } + return { toolMode, actorFullName }; } diff --git a/src/utils/actor_details.ts b/src/utils/actor_details.ts index e9a285333..57b279d6a 100644 --- a/src/utils/actor_details.ts +++ b/src/utils/actor_details.ts @@ -2,11 +2,13 @@ import type { Build } from 'apify-client'; import type { ApifyClient } from '../apify_client.js'; import { CODE_RUNTIME_ACTOR_NAME } from '../const.js'; +import { ActorLoadError } from '../errors.js'; import { connectMCPClient } from '../mcp/client.js'; import type { PaymentProvider } from '../payments/types.js'; import { filterSchemaProperties, shortenProperties } from '../tools/actor_input_schema.js'; import type { Actor, ActorCardOptions, ActorInputSchema, ActorStoreList, StructuredActorCard } from '../types.js'; -import { getActorMcpUrlCached } from './actor.js'; +import { ACTOR_TOOL_MODE } from '../types.js'; +import { getActorToolResolutionCached } from './actor.js'; import { formatActorForWidget, formatActorToActorCard, formatActorToStructuredCard } from './actor_card.js'; import { searchActorsByKeywords } from './actor_search.js'; import { getHttpStatusCode, logHttpError } from './logging.js'; @@ -162,10 +164,16 @@ export async function getMcpToolsMessage( paymentProvider?: PaymentProvider, mcpSessionId?: string, ): Promise { - const mcpServerUrl = await getActorMcpUrlCached(actorName, apifyClient); + const resolution = await getActorToolResolutionCached(actorName, apifyClient); + + // Same canonical wording call-actor rejects with, so an agent gets one consistent reason + // for this Actor regardless of which tool it asked. + if (resolution?.toolMode === ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP) { + return ActorLoadError.standbyWithoutMcpNotSupported(resolution.actorFullName).message; + } // Early return: not an MCP server - if (!mcpServerUrl || typeof mcpServerUrl !== 'string') { + if (resolution?.toolMode !== ACTOR_TOOL_MODE.MCP) { return `Note: This Actor is not an MCP server and does not expose MCP tools.`; } @@ -175,7 +183,7 @@ export async function getMcpToolsMessage( } // Connect and list tools - const client = await connectMCPClient(mcpServerUrl, apifyToken, mcpSessionId); + const client = await connectMCPClient(resolution.mcpServerUrl, apifyToken, mcpSessionId); if (!client) { return `Failed to connect to MCP server for Actor '${actorName}'.`; } diff --git a/tests/unit/mcp.server.actor_mode_matrix.test.ts b/tests/unit/mcp.server.actor_mode_matrix.test.ts new file mode 100644 index 000000000..1f90c634b --- /dev/null +++ b/tests/unit/mcp.server.actor_mode_matrix.test.ts @@ -0,0 +1,224 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { ApifyClient } from '../../src/apify_client.js'; +import { FAILURE_CATEGORY, HELPER_TOOLS, TOOL_STATUS } from '../../src/const.js'; +import { actorDefinitionCache } from '../../src/state.js'; +import { callActorPreExecute, executeCallActor } from '../../src/tools/actors/call_actor.js'; +import type { ActorDefinitionWithInfo } from '../../src/types.js'; +import type { ToolResponse } from '../../src/utils/mcp.js'; +import { withServer } from './helpers/mcp_server.js'; +import { textOf, stubToolCallContext, type TextToolResult } from './helpers/tool_context.js'; + +// Any Actor not seeded into the definition cache is unknown; the fetch fallback must not hit the network. +vi.mock('../../src/tools/actors/actor_definition.js', async () => { + const actual = await vi.importActual>('../../src/tools/actors/actor_definition.js'); + return { ...actual, getActorDefinition: vi.fn(async () => null) }; +}); + +vi.mock('../../src/mcp/client.js', () => ({ + connectMCPClient: vi.fn(async () => ({ + listTools: async () => ({ + tools: [{ name: 'add', description: 'adds', inputSchema: { type: 'object', properties: {} } }], + }), + callTool: async () => ({ content: [{ type: 'text', text: 'MCP result' }] }), + close: async () => {}, + })), +})); + +const NON_EMPTY_INPUT = { type: 'object', properties: { url: { type: 'string', description: 'a url' } } }; + +/** Every cell of the decision table, seeded as a public Actor so the cache's owner gate is bypassed. */ +const RUN_ONLY = 'acme/run-only'; +const RUN_ONLY_STALE_PATH = 'acme/run-only-stale-path'; +const STANDBY_MCP = 'acme/standby-mcp'; +const STANDBY_INPUT = 'acme/standby-input'; +const STANDBY_EMPTY = 'acme/standby-empty'; +/** The unsupported cell addressed by its Actor ID — an identifier that is not the canonical `username/name`. */ +const STANDBY_EMPTY_ID = 'aBcD1234'; +/** A run-only Actor addressed by its Actor ID. */ +const RUN_ONLY_ID = 'zXyW9876'; + +function seedActor( + name: string, + opts: { webServerMcpPath?: string; isStandbyEnabled?: boolean; input?: unknown; cacheKey?: string }, +): void { + const id = name.replace('/', '-'); + actorDefinitionCache.set(opts.cacheKey ?? name, { + definition: { + id, + actorFullName: name, + description: 'test Actor', + defaultRunOptions: { memoryMbytes: 1024 }, + ...(opts.webServerMcpPath && { webServerMcpPath: opts.webServerMcpPath }), + ...(opts.input !== undefined && { input: opts.input }), + }, + info: { + id, + isPublic: true, + userId: 'owner', + ...(opts.isStandbyEnabled && { actorStandby: { isEnabled: true } }), + }, + } as unknown as ActorDefinitionWithInfo); +} + +/** Tool names the server holds after loading exactly one Actor. */ +async function loadedToolNames(actorFullName: string): Promise { + return withServer(async (server) => { + await server.loadToolsByName([actorFullName], new ApifyClient({ token: 'test-token' })); + return [...server.tools.keys()]; + }); +} + +function callActor(actor: string): Promise { + return executeCallActor(stubToolCallContext({ actor, input: {} }, new ApifyClient({ token: 'test-token' }))); +} + +function preExecute(actor: string) { + return callActorPreExecute(stubToolCallContext({ actor, input: {} }, new ApifyClient({ token: 'test-token' })), { + route: HELPER_TOOLS.ACTOR_CALL, + }); +} + +function firstText(response: ToolResponse): string { + return textOf((response as TextToolResult).content[0]); +} + +/** Asserts the pre-execution stopped early, and returns the response it answered with. */ +function earlyResponseOf(result: Awaited>): ToolResponse { + expect('earlyResponse' in result).toBe(true); + return (result as { earlyResponse: ToolResponse }).earlyResponse; +} + +function earlyText(result: Awaited>): string { + return firstText(earlyResponseOf(result)); +} + +beforeEach(() => { + seedActor(RUN_ONLY, { input: NON_EMPTY_INPUT }); + seedActor(RUN_ONLY_STALE_PATH, { webServerMcpPath: '/mcp', input: NON_EMPTY_INPUT }); + seedActor(STANDBY_MCP, { webServerMcpPath: '/mcp', isStandbyEnabled: true, input: NON_EMPTY_INPUT }); + seedActor(STANDBY_INPUT, { isStandbyEnabled: true, input: NON_EMPTY_INPUT }); + seedActor(STANDBY_EMPTY, { isStandbyEnabled: true }); + seedActor(STANDBY_EMPTY, { isStandbyEnabled: true, cacheKey: STANDBY_EMPTY_ID }); + seedActor(RUN_ONLY, { input: NON_EMPTY_INPUT, cacheKey: RUN_ONLY_ID }); +}); + +describe('Actor run/standby mode decision table', () => { + // One row per cell of the decision table: which tools the Actor contributes to tools/list. + it.each([ + ['a run-only Actor', RUN_ONLY, ['acme--run-only']], + ['a run-only Actor carrying a leftover webServerMcpPath', RUN_ONLY_STALE_PATH, ['acme--run-only-stale-path']], + ['a standby Actor exposing an MCP server (proxied tools only)', STANDBY_MCP, ['acme--standby-mcp--add']], + ['a standby Actor with no MCP server but a non-empty input schema', STANDBY_INPUT, ['acme--standby-input']], + ['a standby Actor with no MCP server and an empty input schema', STANDBY_EMPTY, []], + ])('tools/list surface for %s', async (_label, actor, expected) => { + expect(await loadedToolNames(actor)).toEqual(expected); + }); + + describe('call-actor routing', () => { + it('runs a run-only Actor with a leftover webServerMcpPath instead of demanding a tool name', async () => { + const result = await preExecute(RUN_ONLY_STALE_PATH); + + expect('earlyResponse' in result).toBe(false); + }); + + it('answers "is not an MCP server" for the actor:tool shape on a run-only Actor with a leftover path', async () => { + const result = await preExecute(`${RUN_ONLY_STALE_PATH}:add`); + + expect(earlyText(result)).toContain('is not an MCP server'); + }); + + it('records the "is not an MCP server" rejection as a caller mistake, not a server fault', async () => { + const result = await preExecute(`${RUN_ONLY_STALE_PATH}:add`); + + expect(earlyResponseOf(result).toolTelemetry).toEqual( + expect.objectContaining({ + toolStatus: TOOL_STATUS.SOFT_FAIL, + failureCategory: FAILURE_CATEGORY.INVALID_INPUT, + }), + ); + }); + + it('runs a standby Actor with no MCP server but a non-empty input schema', async () => { + const result = await preExecute(STANDBY_INPUT); + + expect('earlyResponse' in result).toBe(false); + }); + + it('rejects the actor:tool shape for a standby Actor with no MCP server but a non-empty input schema', async () => { + const result = await preExecute(`${STANDBY_INPUT}:add`); + + expect(earlyText(result)).toContain('is not an MCP server'); + }); + + it('demands a tool name for a bare call on a standby Actor exposing an MCP server', async () => { + const result = await preExecute(STANDBY_MCP); + + expect(earlyText(result)).toContain('tool name'); + }); + + it('proxies an MCP tool call on a standby Actor exposing an MCP server', async () => { + const result = await callActor(`${STANDBY_MCP}:add`); + + expect(firstText(result)).toBe('MCP result'); + expect(result.isError).toBe(false); + }); + + it('rejects a bare unsupported standby Actor during pre-execution', async () => { + const result = await preExecute(STANDBY_EMPTY); + + expect('earlyResponse' in result).toBe(true); + }); + + it('answers the canonical standby-without-MCP message for both call shapes on the unsupported cell', async () => { + const bare = await callActor(STANDBY_EMPTY); + const withToolName = await preExecute(`${STANDBY_EMPTY}:add`); + + const withToolNameText = earlyText(withToolName); + + expect(firstText(bare)).toBe(withToolNameText); + expect(withToolNameText).toContain('standby mode without an MCP server'); + expect(bare.isError).toBe(true); + expect(earlyResponseOf(withToolName).isError).toBe(true); + }); + + it('answers with the canonical Actor name for both call shapes when addressed by Actor ID', async () => { + const bare = await callActor(STANDBY_EMPTY_ID); + const withToolName = await preExecute(`${STANDBY_EMPTY_ID}:add`); + + const withToolNameText = earlyText(withToolName); + + expect(firstText(bare)).toBe(withToolNameText); + expect(withToolNameText).toContain(STANDBY_EMPTY); + expect(withToolNameText).not.toContain(STANDBY_EMPTY_ID); + }); + + it('answers "is not an MCP server" with the canonical Actor name when addressed by Actor ID', async () => { + const result = await preExecute(`${RUN_ONLY_ID}:add`); + + expect('earlyResponse' in result).toBe(true); + const text = earlyText(result); + expect(text).toContain(RUN_ONLY); + expect(text).not.toContain(RUN_ONLY_ID); + }); + + it('answers not-found instead of "is not an MCP server" for the actor:tool shape on an unknown Actor', async () => { + const result = await preExecute('acme/ghost:add'); + + const text = earlyText(result); + expect(text).toContain("Actor 'acme/ghost' was not found"); + expect(text).not.toContain('is not an MCP server'); + }); + + it('keeps the unsupported-cell message distinct from the "is not an MCP server" wording', async () => { + const unsupported = await preExecute(`${STANDBY_EMPTY}:add`); + const runOnly = await preExecute(`${RUN_ONLY_STALE_PATH}:add`); + + const unsupportedText = earlyText(unsupported); + const runOnlyText = earlyText(runOnly); + + expect(unsupportedText).not.toBe(runOnlyText); + expect(unsupportedText).not.toContain('is not an MCP server'); + }); + }); +}); diff --git a/tests/unit/tools.actor.test.ts b/tests/unit/tools.actor.test.ts index b79d0e109..2b9314606 100644 --- a/tests/unit/tools.actor.test.ts +++ b/tests/unit/tools.actor.test.ts @@ -3,7 +3,9 @@ import { createHash } from 'node:crypto'; import { describe, expect, it } from 'vitest'; import { MAX_TOOL_NAME_LENGTH, TOOL_NAME_HASH_LENGTH } from '../../src/mcp/const.js'; -import { actorNameToToolName, legacyToolNameToNew } from '../../src/tools/actor_tool_naming.js'; +import { actorNameToToolName, legacyToolNameToNew, resolveActorToolMode } from '../../src/tools/actor_tool_naming.js'; +import type { ActorInfo, ActorInputSchema } from '../../src/types.js'; +import { ACTOR_TOOL_MODE } from '../../src/types.js'; describe('actors', () => { describe('actorNameToToolName', () => { @@ -66,3 +68,56 @@ describe('actors', () => { }); }); }); + +function makeActorInfo(opts: { + isStandbyEnabled?: boolean; + webServerMcpPath?: string | null; + input?: unknown; +}): ActorInfo { + return { + webServerMcpPath: opts.webServerMcpPath ?? null, + definition: { id: 'actor-id', actorFullName: 'acme/actor', input: opts.input as ActorInputSchema | undefined }, + actor: opts.isStandbyEnabled ? { actorStandby: { isEnabled: true } } : {}, + } as unknown as ActorInfo; +} + +const NON_EMPTY_INPUT = { type: 'object', properties: { url: { type: 'string' } } }; + +describe('resolveActorToolMode()', () => { + // One row per cell of the decision table in `resolveActorToolMode`'s docstring, plus the + // edge cases that define what counts as an empty input schema. + it.each([ + ['standby disabled, no MCP path', {}, ACTOR_TOOL_MODE.RUN], + ['standby disabled, leftover MCP path', { webServerMcpPath: '/mcp' }, ACTOR_TOOL_MODE.RUN], + ['standby disabled, empty input schema', { input: undefined }, ACTOR_TOOL_MODE.RUN], + ['standby enabled, MCP path', { isStandbyEnabled: true, webServerMcpPath: '/mcp' }, ACTOR_TOOL_MODE.MCP], + ['standby enabled, no MCP path, non-empty input', { isStandbyEnabled: true }, ACTOR_TOOL_MODE.RUN], + [ + 'missing input counts as empty', + { isStandbyEnabled: true, input: undefined }, + ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, + ], + [ + 'input without properties counts as empty', + { isStandbyEnabled: true, input: { type: 'object' } }, + ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, + ], + [ + 'zero properties counts as empty', + { isStandbyEnabled: true, input: { type: 'object', properties: {} } }, + ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, + ], + [ + 'required without properties still counts as empty', + { isStandbyEnabled: true, input: { type: 'object', properties: {}, required: ['url'] } }, + ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, + ], + [ + 'non-object input carrying properties counts as non-empty', + { isStandbyEnabled: true, input: { type: 'string', properties: { url: { type: 'string' } } } }, + ACTOR_TOOL_MODE.RUN, + ], + ] as const)('resolves %s to %s', (_label, opts, expected) => { + expect(resolveActorToolMode(makeActorInfo({ input: NON_EMPTY_INPUT, ...opts }))).toBe(expected); + }); +}); diff --git a/tests/unit/tools.call_actor_common.test.ts b/tests/unit/tools.call_actor_common.test.ts index 165a5af1b..892ab2e0c 100644 --- a/tests/unit/tools.call_actor_common.test.ts +++ b/tests/unit/tools.call_actor_common.test.ts @@ -9,6 +9,7 @@ import { HELPER_TOOLS, TOOL_STATUS, } from '../../src/const.js'; +import { ActorLoadError } from '../../src/errors.js'; import * as mcpClient from '../../src/mcp/client.js'; import { EXTERNAL_TOOL_CALL_TIMEOUT_MSEC } from '../../src/mcp/const.js'; import { @@ -126,6 +127,54 @@ describe('call_actor_common', () => { ); }); + it('forwards the standby payment error message verbatim as a user error', () => { + const error = ActorLoadError.standbyPaymentNotSupported('apify/rag-web-browser'); + + const response = buildCallActorErrorResponse({ + actorName: 'apify/rag-web-browser', + error, + actorId: 'actor-standby-payment', + loadedToolNames: [HELPER_TOOLS.STORE_SEARCH, HELPER_TOOLS.ACTOR_GET_DETAILS], + }); + + expect(response.isError).toBe(true); + expect((response.content ?? []).map(textOf).join('\n')).toBe(error.message); + expect(response.toolTelemetry).toEqual( + expect.objectContaining({ + toolStatus: TOOL_STATUS.SOFT_FAIL, + failureCategory: FAILURE_CATEGORY.INVALID_INPUT, + failureDetail: error.kind, + actorId: 'actor-standby-payment', + }), + ); + }); + + // Only the two standby kinds take the user-error branch. LOAD_FAILED masks a backend fault, + // so it must stay on the generic server-error path and keep its INTERNAL_ERROR telemetry. + it('keeps a LOAD_FAILED Actor load failure on the generic server-error path', () => { + const error = ActorLoadError.loadFailed('apify/rag-web-browser'); + + const response = buildCallActorErrorResponse({ + actorName: 'apify/rag-web-browser', + error, + actorId: 'actor-load-failed', + loadedToolNames: [HELPER_TOOLS.STORE_SEARCH, HELPER_TOOLS.ACTOR_GET_DETAILS], + }); + + expect(response.isError).toBe(true); + const allText = (response.content ?? []).map(textOf).join('\n'); + expect(allText).toContain(`Failed to call Actor 'apify/rag-web-browser': ${error.message}`); + expect(allText).not.toBe(error.message); + expect(response.toolTelemetry).toEqual( + expect.objectContaining({ + toolStatus: TOOL_STATUS.FAILED, + failureCategory: FAILURE_CATEGORY.INTERNAL_ERROR, + failureDetail: error.message, + actorId: 'actor-load-failed', + }), + ); + }); + it('uses public search helper name for generic errors', () => { const response = buildCallActorErrorResponse({ actorName: 'apify/rag-web-browser', @@ -485,7 +534,6 @@ describe('call_actor_common', () => { baseActorName: 'apify/mcp-demo', mcpToolName: 'search', input: { q: 'x' }, - isActorMcpServer: true, mcpServerUrl: 'https://example.invalid/mcp', apifyToken: 'token', signal: controller.signal, @@ -507,7 +555,6 @@ describe('call_actor_common', () => { baseActorName: 'apify/mcp-demo', mcpToolName: 'search', input: { q: 'x' }, - isActorMcpServer: true, mcpServerUrl: 'https://example.invalid/mcp', apifyToken: 'token', signal: controller.signal, @@ -531,7 +578,6 @@ describe('call_actor_common', () => { baseActorName: 'apify/mcp-demo', mcpToolName: 'search', input: { q: 'x' }, - isActorMcpServer: true, mcpServerUrl: 'https://example.invalid/mcp', apifyToken: 'token', signal: controller.signal, diff --git a/tests/unit/tools.call_actor_widget.response.test.ts b/tests/unit/tools.call_actor_widget.response.test.ts index a16738228..0e0ae2668 100644 --- a/tests/unit/tools.call_actor_widget.response.test.ts +++ b/tests/unit/tools.call_actor_widget.response.test.ts @@ -3,8 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { WIDGET_URIS } from '../../src/resources/widgets.js'; import { callActorWidget } from '../../src/tools/widgets/call_actor_widget.js'; import type { HelperTool, InternalToolArgs, ToolEntry } from '../../src/types.js'; -import { TOOL_TYPE } from '../../src/types.js'; -import { getActorMcpUrlCached } from '../../src/utils/actor.js'; +import { ACTOR_TOOL_MODE, TOOL_TYPE } from '../../src/types.js'; +import { getActorToolResolutionCached } from '../../src/utils/actor.js'; import { stubToolCallContext, type TextToolResult } from './helpers/tool_context.js'; /** @@ -13,7 +13,7 @@ import { stubToolCallContext, type TextToolResult } from './helpers/tool_context * the response. */ vi.mock('../../src/utils/actor.js', () => ({ - getActorMcpUrlCached: vi.fn(), + getActorToolResolutionCached: vi.fn(), })); vi.mock('../../src/tools/actors/actor_tools_factory.js', async () => { @@ -55,8 +55,11 @@ function stubApifyClient(startSpy: (input: unknown, opts: unknown) => Promise { beforeEach(() => { - vi.mocked(getActorMcpUrlCached).mockReset(); - vi.mocked(getActorMcpUrlCached).mockResolvedValue(false); + vi.mocked(getActorToolResolutionCached).mockReset(); + vi.mocked(getActorToolResolutionCached).mockResolvedValue({ + toolMode: ACTOR_TOOL_MODE.RUN, + actorFullName: 'apify/rag-web-browser', + }); vi.mocked(getActorsAsTools).mockReset(); vi.mocked(getActorsAsTools).mockResolvedValue({ tools: [MOCK_ACTOR_TOOL], errors: [] }); }); diff --git a/tests/unit/tools.utils.test.ts b/tests/unit/tools.utils.test.ts index 7513d79f9..07be16a41 100644 --- a/tests/unit/tools.utils.test.ts +++ b/tests/unit/tools.utils.test.ts @@ -17,7 +17,7 @@ import { transformActorInputSchemaProperties, } from '../../src/tools/actor_input_schema.js'; import { isActorBlockedUnderPaymentProvider } from '../../src/tools/actor_tool_naming.js'; -import type { ActorInfo, ActorInputSchema, SchemaProperties, ToolBase, ToolEntry } from '../../src/types.js'; +import type { ActorInputSchema, SchemaProperties, ToolBase, ToolEntry } from '../../src/types.js'; import { TOOL_TYPE } from '../../src/types.js'; import { ajv } from '../../src/utils/ajv.js'; import { extractActorName, getToolFullName, getToolPublicFieldOnly } from '../../src/utils/tools.js'; @@ -1027,21 +1027,15 @@ describe('buildActorInputSchema + getToolPublicFieldOnly pipeline', () => { }); describe('isActorBlockedUnderPaymentProvider', () => { - const actorInfo = ({ standby, mcpPath = null }: { standby: boolean; mcpPath?: string | null }): ActorInfo => ({ - definition: { actorFullName: 'user/actor', id: 'act' } as ActorInfo['definition'], - actor: { actorStandby: standby ? { isEnabled: true } : undefined } as ActorInfo['actor'], - webServerMcpPath: mcpPath, + const actor = (standby: boolean) => ({ + actorStandby: standby ? { isEnabled: true } : undefined, }); it('blocks standby Actors', () => { - expect(isActorBlockedUnderPaymentProvider(actorInfo({ standby: true }))).toBe(true); + expect(isActorBlockedUnderPaymentProvider(actor(true))).toBe(true); }); it('does not block normal Actors', () => { - expect(isActorBlockedUnderPaymentProvider(actorInfo({ standby: false }))).toBe(false); - }); - - it('does not block MCP path without standby (must match list-tools filter)', () => { - expect(isActorBlockedUnderPaymentProvider(actorInfo({ standby: false, mcpPath: '/mcp' }))).toBe(false); + expect(isActorBlockedUnderPaymentProvider(actor(false))).toBe(false); }); }); diff --git a/tests/unit/utils.actor.cache.test.ts b/tests/unit/utils.actor.cache.test.ts index da0f7dda3..b423aced8 100644 --- a/tests/unit/utils.actor.cache.test.ts +++ b/tests/unit/utils.actor.cache.test.ts @@ -2,13 +2,14 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import type { ApifyClient } from '../../src/apify_client.js'; import type { ActorDefinitionWithInfo } from '../../src/types.js'; +import { ACTOR_TOOL_MODE } from '../../src/types.js'; vi.mock('../../src/tools/actors/actor_definition.js', () => ({ getActorDefinition: vi.fn() })); vi.mock('../../src/utils/userid_cache.js', () => ({ getUserInfoCached: vi.fn() })); import { actorDefinitionCache } from '../../src/state.js'; import { getActorDefinition } from '../../src/tools/actors/actor_definition.js'; -import { getActorDefinitionCached, getActorMcpUrlCached } from '../../src/utils/actor.js'; +import { getActorDefinitionCached, getActorToolResolutionCached } from '../../src/utils/actor.js'; import { getUserInfoCached } from '../../src/utils/userid_cache.js'; const getActorDefinitionMock = vi.mocked(getActorDefinition); @@ -19,7 +20,7 @@ function seedCache( name: string, isPublic: boolean, ownerUserId: string, - opts: { id?: string; webServerMcpPath?: string } = {}, + opts: { id?: string; webServerMcpPath?: string; isStandbyEnabled?: boolean; input?: unknown } = {}, ): ActorDefinitionWithInfo { const id = opts.id ?? name; const entry = { @@ -27,8 +28,14 @@ function seedCache( id, actorFullName: name, ...(opts.webServerMcpPath && { webServerMcpPath: opts.webServerMcpPath }), + ...(opts.input !== undefined && { input: opts.input }), + }, + info: { + id, + isPublic, + userId: ownerUserId, + ...(opts.isStandbyEnabled && { actorStandby: { isEnabled: true } }), }, - info: { id, isPublic, userId: ownerUserId }, } as unknown as ActorDefinitionWithInfo; actorDefinitionCache.set(name, entry); return entry; @@ -90,30 +97,61 @@ describe('getActorDefinitionCached — tenant isolation', () => { }); }); -describe('getActorMcpUrlCached — tenant isolation', () => { +describe('getActorToolResolutionCached()', () => { it('derives the MCP URL from a cached Actor the caller may see', async () => { - seedCache('acme/mcp-public', true, 'owner-6', { id: 'actorpub', webServerMcpPath: '/mcp' }); - - const result = await getActorMcpUrlCached('acme/mcp-public', client); - - expect(result).toBe('https://actorpub.apify.actor/mcp'); + seedCache('acme/mcp-public', true, 'owner-6', { + id: 'actorpub', + webServerMcpPath: '/mcp', + isStandbyEnabled: true, + }); + + const result = await getActorToolResolutionCached('acme/mcp-public', client); + + expect(result).toEqual({ + toolMode: ACTOR_TOOL_MODE.MCP, + mcpServerUrl: 'https://actorpub.apify.actor/mcp', + actorFullName: 'acme/mcp-public', + }); expect(getActorDefinitionMock).not.toHaveBeenCalled(); }); - it('does NOT leak a cached private Actor MCP URL to a non-owner — re-fetches and returns false', async () => { - seedCache('acme/mcp-private', false, 'owner-7', { id: 'actorpriv', webServerMcpPath: '/mcp' }); + it('does NOT leak a cached private Actor MCP URL to a non-owner', async () => { + seedCache('acme/mcp-private', false, 'owner-7', { + id: 'actorpriv', + webServerMcpPath: '/mcp', + isStandbyEnabled: true, + }); getUserInfoCachedMock.mockResolvedValue({ userId: 'intruder', userPlanTier: 'FREE', isOrganization: false }); getActorDefinitionMock.mockResolvedValue(null); // intruder's own fetch is unauthorized - const result = await getActorMcpUrlCached('acme/mcp-private', client); + const result = await getActorToolResolutionCached('acme/mcp-private', client); - expect(result).toBe(false); + expect(result).toBeNull(); expect(getActorDefinitionMock).toHaveBeenCalledWith('acme/mcp-private', client); }); - it('returns false for a non-existent Actor without throwing', async () => { + it('returns null for a non-existent Actor', async () => { getActorDefinitionMock.mockResolvedValue(null); - await expect(getActorMcpUrlCached('acme/missing', client)).resolves.toBe(false); + await expect(getActorToolResolutionCached('acme/missing', client)).resolves.toBeNull(); + }); + + it('returns RUN when standby is disabled despite a leftover webServerMcpPath', async () => { + seedCache('acme/stale-path', true, 'owner-8', { id: 'actorstale', webServerMcpPath: '/mcp' }); + + await expect(getActorToolResolutionCached('acme/stale-path', client)).resolves.toEqual({ + toolMode: ACTOR_TOOL_MODE.RUN, + actorFullName: 'acme/stale-path', + }); + }); + + it('reports the canonical Actor full name when the Actor is addressed by its ID', async () => { + const entry = seedCache('acme/standby-empty-by-id', true, 'owner-15', { isStandbyEnabled: true }); + actorDefinitionCache.set('aBcD1234', entry); + + await expect(getActorToolResolutionCached('aBcD1234', client)).resolves.toEqual({ + toolMode: ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, + actorFullName: 'acme/standby-empty-by-id', + }); }); }); diff --git a/tests/unit/utils.actor_details.test.ts b/tests/unit/utils.actor_details.test.ts index a221b3a49..17b996ba1 100644 --- a/tests/unit/utils.actor_details.test.ts +++ b/tests/unit/utils.actor_details.test.ts @@ -4,7 +4,14 @@ import { describe, expect, it, vi } from 'vitest'; import type { ApifyClient } from '../../src/apify_client.js'; import { CODE_RUNTIME_ACTOR_NAME } from '../../src/const.js'; -import { fetchActorDetails, resolveReadmeContent, typeObjectToString } from '../../src/utils/actor_details.js'; +import { actorDefinitionCache } from '../../src/state.js'; +import type { ActorDefinitionWithInfo } from '../../src/types.js'; +import { + fetchActorDetails, + getMcpToolsMessage, + resolveReadmeContent, + typeObjectToString, +} from '../../src/utils/actor_details.js'; vi.mock('../../src/utils/actor_search.js', () => ({ searchActorsByKeywords: vi.fn().mockResolvedValue([]), @@ -174,3 +181,40 @@ describe('fetchActorDetails()', () => { await expect(fetchActorDetails(client, 'apify/instagram-scraper')).rejects.toMatchObject({ statusCode: 401 }); }); }); + +describe('getMcpToolsMessage()', () => { + it('reports a run-only Actor with a leftover webServerMcpPath as not an MCP server', async () => { + const actorName = 'acme/stale-mcp-path'; + actorDefinitionCache.set(actorName, { + definition: { id: 'staleactor', actorFullName: actorName, webServerMcpPath: '/mcp' }, + info: { id: 'staleactor', isPublic: true, userId: 'owner' }, + } as unknown as ActorDefinitionWithInfo); + + const message = await getMcpToolsMessage( + actorName, + stubApifyClient(async () => ({})), + 'token', + ); + + expect(message).toBe('Note: This Actor is not an MCP server and does not expose MCP tools.'); + }); + + it("reports the canonical standby-without-MCP message, matching call-actor's rejection", async () => { + const actorName = 'acme/standby-empty'; + actorDefinitionCache.set(actorName, { + definition: { id: 'standbyempty', actorFullName: actorName }, + info: { id: 'standbyempty', isPublic: true, userId: 'owner', actorStandby: { isEnabled: true } }, + } as unknown as ActorDefinitionWithInfo); + + const message = await getMcpToolsMessage( + actorName, + stubApifyClient(async () => ({})), + 'token', + ); + + expect(message).toBe( + 'Actor "acme/standby-empty" runs in standby mode without an MCP server and has an empty input schema,' + + ' which is not supported yet.', + ); + }); +});