From 3b2a2d7a7e3d9e4e3ac131db935455fd4f056afa Mon Sep 17 00:00:00 2001 From: Jiri Spilka Date: Thu, 20 Aug 2026 18:36:22 +0200 Subject: [PATCH 1/9] feat: Run/standby mode decision table for Actor tool loading --- src/errors.ts | 9 + src/tools/actor_tool_naming.ts | 27 ++- src/tools/actors/actor_tools_factory.ts | 19 +- src/tools/actors/call_actor.ts | 76 ++++++-- src/types.ts | 11 ++ src/utils/actor.ts | 44 ++++- .../unit/mcp.server.actor_mode_matrix.test.ts | 180 ++++++++++++++++++ tests/unit/tools.actor.test.ts | 92 ++++++++- tests/unit/tools.call_actor_common.test.ts | 70 ++++++- .../tools.call_actor_widget.response.test.ts | 12 +- tests/unit/utils.actor.cache.test.ts | 118 +++++++++++- tests/unit/utils.actor_details.test.ts | 27 ++- 12 files changed, 638 insertions(+), 47 deletions(-) create mode 100644 tests/unit/mcp.server.actor_mode_matrix.test.ts diff --git a/src/errors.ts b/src/errors.ts index 16042291a..b17f64ae0 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,6 +64,14 @@ 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, diff --git a/src/tools/actor_tool_naming.ts b/src/tools/actor_tool_naming.ts index 87673edae..d549a6814 100644 --- a/src/tools/actor_tool_naming.ts +++ b/src/tools/actor_tool_naming.ts @@ -4,12 +4,31 @@ 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 { TOOL_TYPE } 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 | absent | any | `ACTOR` (run tool) | + * | disabled | present | any | `ACTOR` — the leftover path is ignored | + * | enabled | present | any | `ACTOR_MCP` (proxied MCP tools only) | + * | enabled | absent | non-empty | `ACTOR` (run tool) | + * | enabled | absent | empty | `null` | + * + * `null` is not a fourth `TOOL_TYPE` member: it is the absence of a tool. A standby-only Actor with an + * empty input schema has nothing to run and no MCP server to proxy, so it gets no tool at all. + * + * 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 resolveActorToolType(actorInfo: ActorInfo): typeof TOOL_TYPE.ACTOR | typeof TOOL_TYPE.ACTOR_MCP | null { + if (!actorInfo.actor.actorStandby?.isEnabled) return TOOL_TYPE.ACTOR; + if (actorInfo.webServerMcpPath) return TOOL_TYPE.ACTOR_MCP; + return Object.keys(actorInfo.definition.input?.properties ?? {}).length > 0 ? TOOL_TYPE.ACTOR : null; } /** diff --git a/src/tools/actors/actor_tools_factory.ts b/src/tools/actors/actor_tools_factory.ts index ce3b1878f..ed7d72af8 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, @@ -29,7 +30,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, resolveActorToolType } 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'; @@ -364,12 +365,24 @@ export async function getActorsAsTools( const actorMCPServersInfo: ActorInfo[] = []; const normalActorsInfo: ActorInfo[] = []; for (const actorInfo of nonNullActors) { - const isMcpServer = isActorInfoMcpServer(actorInfo); + const toolType = resolveActorToolType(actorInfo); if (paymentProvider && isActorBlockedUnderPaymentProvider(actorInfo)) { errors.push(ActorLoadError.standbyPaymentNotSupported(actorInfo.definition.actorFullName)); continue; } - if (isMcpServer) actorMCPServersInfo.push(actorInfo); + // `null` means the Actor has no tool representation — standby with no MCP server and an empty + // input schema. Bulk loaders drop the error; `call-actor` forwards it to the agent. Logged here + // because the bulk path leaves no other server-side trace of the dropped Actor. + if (toolType === null) { + log.softFail('Skipping standby Actor with no MCP server and an empty input schema', { + actorName: actorInfo.definition.actorFullName, + mcpSessionId, + failureCategory: FAILURE_CATEGORY.INVALID_INPUT, + }); + errors.push(ActorLoadError.standbyWithoutMcpNotSupported(actorInfo.definition.actorFullName)); + continue; + } + if (toolType === TOOL_TYPE.ACTOR_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 2cd74cc87..1c2535dc6 100644 --- a/src/tools/actors/call_actor.ts +++ b/src/tools/actors/call_actor.ts @@ -20,6 +20,7 @@ import { EXTERNAL_TOOL_CALL_TIMEOUT_MSEC } from '../../mcp/const.js'; import type { PaymentProvider } from '../../payments/types.js'; import type { ActorInfo, + ActorToolResolutionResult, ApifyToken, InternalToolArgs, ToolDescriptionContext, @@ -27,7 +28,7 @@ import type { ToolInputSchema, } from '../../types.js'; import { ALL_TOOLS_PRESENT, TOOL_TYPE } from '../../types.js'; -import { getActorDefinitionCached, getActorMcpUrlCached } from '../../utils/actor.js'; +import { getActorDefinitionCached, getActorToolResolutionCached } from '../../utils/actor.js'; import { compileSchema } from '../../utils/ajv.js'; import { ACTOR_RUN_LIMIT_MESSAGE, @@ -168,6 +169,26 @@ 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 }, +): 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. + actorName: error.actorName, + mcpSessionId: opts.mcpSessionId, + actorLoadErrorKind: error.kind, + failureCategory: FAILURE_CATEGORY.INVALID_INPUT, + }); + return respondUserError(error.message, { actorId: opts.actorId, detail: error.kind }); +} + export function buildCallActorErrorResponse(params: CallActorErrorResponseParams): ToolResponse { const { actorName, error, actorId, mcpSessionId, loadedToolNames } = params; @@ -185,6 +206,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, @@ -313,6 +344,8 @@ export async function checkPaymentProviderStandbyConflict(params: { return null; } + // Stub for isActorBlockedUnderPaymentProvider, which only reads `actor` — the hardcoded null + // `webServerMcpPath` would make `resolveActorToolType` misclassify standby MCP Actors. const actorInfo: ActorInfo = { definition: actorDefinitionWithInfo.definition, actor: actorDefinitionWithInfo.info, @@ -323,6 +356,8 @@ export async function checkPaymentProviderStandbyConflict(params: { return null; } + // 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); log.softFail('Rejecting call-actor for standby Actor under third-party payment provider', { actorName: baseActorName, paymentProviderId: paymentProvider.id, @@ -330,7 +365,7 @@ export async function checkPaymentProviderStandbyConflict(params: { failureCategory: FAILURE_CATEGORY.INVALID_INPUT, }); - return respondUserError(ActorLoadError.standbyPaymentNotSupported(normalizedActorName).message); + return respondUserError(error.message, { detail: error.kind }); } /** @@ -359,17 +394,24 @@ export async function handleMcpToolCall(params: { baseActorName: string; mcpToolName: string; input: Record; - isActorMcpServer: boolean; - mcpServerUrl: string | false; + resolution: ActorToolResolutionResult | null; apifyToken: string; mcpSessionId?: string; signal: AbortSignal; }): Promise { - const { baseActorName, mcpToolName, input, isActorMcpServer, mcpServerUrl, apifyToken, mcpSessionId, signal } = - params; + const { baseActorName, mcpToolName, input, resolution, apifyToken, mcpSessionId, signal } = params; + + // `toolType: null` is the standby-without-MCP cell — the same reason the bare `call-actor` shape + // reports through `buildCallActorErrorResponse`. Both build the message from the canonical + // `actorFullName`, not the caller's identifier, so an Actor ID and a full name answer identically. + if (resolution?.toolType === null) { + return respondStandbyRejection(ActorLoadError.standbyWithoutMcpNotSupported(resolution.actorFullName), { + mcpSessionId, + }); + } - if (!isActorMcpServer) { - return respondServerError(`Actor '${baseActorName}' is not an MCP server.`); + if (resolution?.toolType !== TOOL_TYPE.ACTOR_MCP) { + return respondServerError(`Actor '${resolution?.actorFullName ?? baseActorName}' is not an MCP server.`); } if (!input) { @@ -384,9 +426,9 @@ export async function handleMcpToolCall(params: { let client: Client | null = null; try { - client = await connectMCPClient(mcpServerUrl as string, apifyToken, mcpSessionId); + client = await connectMCPClient(resolution.mcpServerUrl, apifyToken, mcpSessionId); if (!client) { - return respondServerError(`Failed to connect to MCP server ${mcpServerUrl}`); + return respondServerError(`Failed to connect to MCP server ${resolution.mcpServerUrl}`); } const result = await client.callTool( @@ -456,9 +498,10 @@ 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 is also caught upstream by `checkPaymentProviderStandbyConflict` + // in the tool-call engine, so it's a defensive fallback here. if (errors[0] && errors[0].kind !== ACTOR_LOAD_ERROR_KIND.NOT_FOUND) { throw errors[0]; } @@ -565,8 +608,8 @@ export async function callActorPreExecute( // 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. const apifyClientForDefinition = new ApifyClient({ token: apifyToken }); - const mcpServerUrlOrFalse = await getActorMcpUrlCached(baseActorName, apifyClientForDefinition); - const isActorMcpServer = !!mcpServerUrlOrFalse; + const resolution = await getActorToolResolutionCached(baseActorName, apifyClientForDefinition); + const isActorMcpServer = resolution?.toolType === TOOL_TYPE.ACTOR_MCP; // Handle the case where LLM does not respect instructions when calling MCP server Actors // and does not provide the tool name. @@ -583,8 +626,7 @@ export async function callActorPreExecute( baseActorName, mcpToolName, input: parsed.input as Record, - isActorMcpServer, - mcpServerUrl: mcpServerUrlOrFalse, + resolution, apifyToken, mcpSessionId, signal: toolArgs.signal, diff --git a/src/types.ts b/src/types.ts index 4dbb711bb..d88335027 100644 --- a/src/types.ts +++ b/src/types.ts @@ -260,6 +260,17 @@ export type ActorInfo = { actor: ActorOutdated; }; +/** + * How an Actor is exposed as a tool, resolved once from its definition by `resolveActorToolType`. + * `mcpServerUrl` is a plain `string` exactly when `toolType` is {@link TOOL_TYPE.ACTOR_MCP}, so + * callers connect without a cast. `toolType: null` means the Actor has no tool representation. + * `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 = + | { toolType: typeof TOOL_TYPE.ACTOR_MCP; mcpServerUrl: string; actorFullName: string } + | { toolType: typeof TOOL_TYPE.ACTOR | null; mcpServerUrl: null; actorFullName: string }; + export type ActorStoreList = ActorStoreListOutdated & { actorReviewCount?: number; actorReviewRating?: number; diff --git a/src/utils/actor.ts b/src/utils/actor.ts index 17af636d4..b4bf8b661 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 { resolveActorToolType } 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 { TOOL_TYPE } from '../types.js'; import { getUserInfoCached } from './userid_cache.js'; /** @@ -44,13 +46,43 @@ 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 `resolveActorToolType` + * 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 getActorToolResolutionCached( + actorIdOrName: string, + apifyClient: ApifyClient, +): Promise { + const cached = await getActorDefinitionCached(actorIdOrName, apifyClient); + if (!cached) return null; + + const webServerMcpPath = getActorMCPServerPath(cached.definition); + const toolType = resolveActorToolType({ + definition: cached.definition, + actor: cached.info, + webServerMcpPath, + }); + const { actorFullName } = cached.definition; + // `resolveActorToolType` returns ACTOR_MCP only when `webServerMcpPath` is set; testing the path + // here narrows it to `string`, so the URL is built without a cast. + if (toolType === TOOL_TYPE.ACTOR_MCP && webServerMcpPath) { + return { + toolType, + mcpServerUrl: await getActorMCPServerURL(cached.definition.id, webServerMcpPath), + actorFullName, + }; + } + return { toolType: toolType === TOOL_TYPE.ACTOR ? toolType : null, mcpServerUrl: null, actorFullName }; +} + +/** + * Resolve the Actor's MCP server URL, or `false` if it isn't an MCP server. + */ 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); + const resolution = await getActorToolResolutionCached(actorIdOrName, apifyClient); + return resolution?.toolType === TOOL_TYPE.ACTOR_MCP ? resolution.mcpServerUrl : false; } 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..12d97f8aa --- /dev/null +++ b/tests/unit/mcp.server.actor_mode_matrix.test.ts @@ -0,0 +1,180 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { ApifyClient } from '../../src/apify_client.js'; +import { HELPER_TOOLS } 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'; + +vi.mock('../../src/mcp/client.js', () => ({ + connectMCPClient: vi.fn(async () => ({ + listTools: async () => ({ + tools: [{ name: 'add', description: 'adds', inputSchema: { type: 'object', properties: {} } }], + }), + 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]); +} + +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', () => { + describe('tools/list surface', () => { + it('loads a run tool for a run-only Actor', async () => { + expect(await loadedToolNames(RUN_ONLY)).toEqual(['acme--run-only']); + }); + + it('loads a run tool for a run-only Actor carrying a leftover webServerMcpPath', async () => { + expect(await loadedToolNames(RUN_ONLY_STALE_PATH)).toEqual(['acme--run-only-stale-path']); + }); + + it('loads only proxied MCP tools for a standby Actor exposing an MCP server', async () => { + expect(await loadedToolNames(STANDBY_MCP)).toEqual(['acme--standby-mcp--add']); + }); + + it('loads a run tool for a standby Actor with no MCP server but a non-empty input schema', async () => { + expect(await loadedToolNames(STANDBY_INPUT)).toEqual(['acme--standby-input']); + }); + + it('loads no tool for a standby Actor with no MCP server and an empty input schema', async () => { + expect(await loadedToolNames(STANDBY_EMPTY)).toEqual([]); + }); + }); + + 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('earlyResponse' in result).toBe(true); + expect(firstText((result as { earlyResponse: ToolResponse }).earlyResponse)).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('earlyResponse' in result).toBe(true); + expect(firstText((result as { earlyResponse: ToolResponse }).earlyResponse)).toContain('tool name'); + }); + + 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`); + + expect('earlyResponse' in withToolName).toBe(true); + const withToolNameText = firstText((withToolName as { earlyResponse: ToolResponse }).earlyResponse); + + expect(firstText(bare)).toBe(withToolNameText); + expect(withToolNameText).toContain('standby mode without an MCP server'); + expect(bare.isError).toBe(true); + expect((withToolName as { earlyResponse: ToolResponse }).earlyResponse.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`); + + expect('earlyResponse' in withToolName).toBe(true); + const withToolNameText = firstText((withToolName as { earlyResponse: ToolResponse }).earlyResponse); + + 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 = firstText((result as { earlyResponse: ToolResponse }).earlyResponse); + expect(text).toContain(RUN_ONLY); + expect(text).not.toContain(RUN_ONLY_ID); + }); + + 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 = firstText((unsupported as { earlyResponse: ToolResponse }).earlyResponse); + const runOnlyText = firstText((runOnly as { earlyResponse: ToolResponse }).earlyResponse); + + 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..e8432a940 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, resolveActorToolType } from '../../src/tools/actor_tool_naming.js'; +import type { ActorInfo, ActorInputSchema } from '../../src/types.js'; +import { TOOL_TYPE } from '../../src/types.js'; describe('actors', () => { describe('actorNameToToolName', () => { @@ -66,3 +68,91 @@ 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('resolveActorToolType()', () => { + it('returns ACTOR when standby is disabled and no MCP path is set', () => { + expect(resolveActorToolType(makeActorInfo({ input: NON_EMPTY_INPUT }))).toBe(TOOL_TYPE.ACTOR); + }); + + it('returns ACTOR when standby is disabled despite a leftover MCP path', () => { + expect(resolveActorToolType(makeActorInfo({ webServerMcpPath: '/mcp', input: NON_EMPTY_INPUT }))).toBe( + TOOL_TYPE.ACTOR, + ); + }); + + it('returns ACTOR when standby is disabled and the input schema is empty', () => { + expect(resolveActorToolType(makeActorInfo({}))).toBe(TOOL_TYPE.ACTOR); + }); + + it('returns ACTOR_MCP when standby is enabled and an MCP path is set', () => { + expect(resolveActorToolType(makeActorInfo({ isStandbyEnabled: true, webServerMcpPath: '/mcp' }))).toBe( + TOOL_TYPE.ACTOR_MCP, + ); + }); + + it('returns ACTOR when standby is enabled without an MCP path but the input schema is non-empty', () => { + expect(resolveActorToolType(makeActorInfo({ isStandbyEnabled: true, input: NON_EMPTY_INPUT }))).toBe( + TOOL_TYPE.ACTOR, + ); + }); + + it('returns null when standby is enabled without an MCP path and the input schema is empty', () => { + expect(resolveActorToolType(makeActorInfo({ isStandbyEnabled: true }))).toBeNull(); + }); + + describe('empty input schema', () => { + it('treats a missing input as empty', () => { + expect(resolveActorToolType(makeActorInfo({ isStandbyEnabled: true, input: undefined }))).toBeNull(); + }); + + it('treats an input without properties as empty', () => { + expect( + resolveActorToolType(makeActorInfo({ isStandbyEnabled: true, input: { type: 'object' } })), + ).toBeNull(); + }); + + it('treats zero properties as empty', () => { + expect( + resolveActorToolType( + makeActorInfo({ isStandbyEnabled: true, input: { type: 'object', properties: {} } }), + ), + ).toBeNull(); + }); + + it('treats a non-empty required list with no properties as empty', () => { + expect( + resolveActorToolType( + makeActorInfo({ + isStandbyEnabled: true, + input: { type: 'object', properties: {}, required: ['url'] }, + }), + ), + ).toBeNull(); + }); + + it('treats a non-object input carrying properties as non-empty', () => { + expect( + resolveActorToolType( + makeActorInfo({ + isStandbyEnabled: true, + input: { type: 'string', properties: { url: { type: 'string' } } }, + }), + ), + ).toBe(TOOL_TYPE.ACTOR); + }); + }); +}); diff --git a/tests/unit/tools.call_actor_common.test.ts b/tests/unit/tools.call_actor_common.test.ts index 8c516963b..b31f32a72 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', @@ -384,8 +433,11 @@ describe('call_actor_common', () => { baseActorName: 'apify/mcp-demo', mcpToolName: 'search', input: { q: 'x' }, - isActorMcpServer: true, - mcpServerUrl: 'https://example.invalid/mcp', + resolution: { + toolType: TOOL_TYPE.ACTOR_MCP, + mcpServerUrl: 'https://example.invalid/mcp', + actorFullName: 'apify/mcp-demo', + }, apifyToken: 'token', signal: controller.signal, }); @@ -406,8 +458,11 @@ describe('call_actor_common', () => { baseActorName: 'apify/mcp-demo', mcpToolName: 'search', input: { q: 'x' }, - isActorMcpServer: true, - mcpServerUrl: 'https://example.invalid/mcp', + resolution: { + toolType: TOOL_TYPE.ACTOR_MCP, + mcpServerUrl: 'https://example.invalid/mcp', + actorFullName: 'apify/mcp-demo', + }, apifyToken: 'token', signal: controller.signal, }); @@ -430,8 +485,11 @@ describe('call_actor_common', () => { baseActorName: 'apify/mcp-demo', mcpToolName: 'search', input: { q: 'x' }, - isActorMcpServer: true, - mcpServerUrl: 'https://example.invalid/mcp', + resolution: { + toolType: TOOL_TYPE.ACTOR_MCP, + mcpServerUrl: 'https://example.invalid/mcp', + actorFullName: 'apify/mcp-demo', + }, 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..21eca08f7 100644 --- a/tests/unit/tools.call_actor_widget.response.test.ts +++ b/tests/unit/tools.call_actor_widget.response.test.ts @@ -4,7 +4,7 @@ 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 { 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,12 @@ 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({ + toolType: TOOL_TYPE.ACTOR, + mcpServerUrl: null, + actorFullName: 'apify/rag-web-browser', + }); vi.mocked(getActorsAsTools).mockReset(); vi.mocked(getActorsAsTools).mockResolvedValue({ tools: [MOCK_ACTOR_TOOL], errors: [] }); }); diff --git a/tests/unit/utils.actor.cache.test.ts b/tests/unit/utils.actor.cache.test.ts index da0f7dda3..08d485557 100644 --- a/tests/unit/utils.actor.cache.test.ts +++ b/tests/unit/utils.actor.cache.test.ts @@ -8,7 +8,8 @@ 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 { TOOL_TYPE } from '../../src/types.js'; +import { getActorDefinitionCached, getActorMcpUrlCached, 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,13 +28,21 @@ 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; } +const NON_EMPTY_INPUT = { type: 'object', properties: { url: { type: 'string' } } }; + const client = { token: 'caller-token' } as unknown as ApifyClient; beforeEach(() => { @@ -92,7 +101,11 @@ describe('getActorDefinitionCached — tenant isolation', () => { describe('getActorMcpUrlCached — tenant isolation', () => { 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' }); + seedCache('acme/mcp-public', true, 'owner-6', { + id: 'actorpub', + webServerMcpPath: '/mcp', + isStandbyEnabled: true, + }); const result = await getActorMcpUrlCached('acme/mcp-public', client); @@ -101,7 +114,11 @@ describe('getActorMcpUrlCached — tenant isolation', () => { }); 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' }); + 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 @@ -117,3 +134,94 @@ describe('getActorMcpUrlCached — tenant isolation', () => { await expect(getActorMcpUrlCached('acme/missing', client)).resolves.toBe(false); }); }); + +describe('getActorMcpUrlCached — tool-type rule', () => { + it('returns false when standby is disabled despite a leftover webServerMcpPath', async () => { + seedCache('acme/stale-path', true, 'owner-8', { id: 'actorstale', webServerMcpPath: '/mcp' }); + + await expect(getActorMcpUrlCached('acme/stale-path', client)).resolves.toBe(false); + }); + + it('returns false for a standby Actor with no MCP server and an empty input schema', async () => { + seedCache('acme/standby-empty-url', true, 'owner-9', { id: 'actorsbe', isStandbyEnabled: true }); + + await expect(getActorMcpUrlCached('acme/standby-empty-url', client)).resolves.toBe(false); + }); +}); + +describe('getActorToolResolutionCached()', () => { + it('resolves a run-only Actor to ACTOR with no MCP URL', async () => { + seedCache('acme/run-only', true, 'owner-10', { input: NON_EMPTY_INPUT }); + + await expect(getActorToolResolutionCached('acme/run-only', client)).resolves.toEqual({ + toolType: TOOL_TYPE.ACTOR, + mcpServerUrl: null, + actorFullName: 'acme/run-only', + }); + }); + + it('resolves a run-only Actor with a leftover webServerMcpPath to ACTOR with no MCP URL', async () => { + seedCache('acme/run-only-stale', true, 'owner-11', { + id: 'actorstale2', + webServerMcpPath: '/mcp', + input: NON_EMPTY_INPUT, + }); + + await expect(getActorToolResolutionCached('acme/run-only-stale', client)).resolves.toEqual({ + toolType: TOOL_TYPE.ACTOR, + mcpServerUrl: null, + actorFullName: 'acme/run-only-stale', + }); + }); + + it('resolves a standby Actor with an MCP path to ACTOR_MCP and its URL', async () => { + seedCache('acme/standby-mcp', true, 'owner-12', { + id: 'actormcp', + webServerMcpPath: '/mcp', + isStandbyEnabled: true, + }); + + await expect(getActorToolResolutionCached('acme/standby-mcp', client)).resolves.toEqual({ + toolType: TOOL_TYPE.ACTOR_MCP, + mcpServerUrl: 'https://actormcp.apify.actor/mcp', + actorFullName: 'acme/standby-mcp', + }); + }); + + it('resolves a standby Actor without an MCP path but with a non-empty input schema to ACTOR', async () => { + seedCache('acme/standby-input', true, 'owner-13', { isStandbyEnabled: true, input: NON_EMPTY_INPUT }); + + await expect(getActorToolResolutionCached('acme/standby-input', client)).resolves.toEqual({ + toolType: TOOL_TYPE.ACTOR, + mcpServerUrl: null, + actorFullName: 'acme/standby-input', + }); + }); + + it('resolves a standby Actor without an MCP path and an empty input schema to no tool type', async () => { + seedCache('acme/standby-empty', true, 'owner-14', { isStandbyEnabled: true }); + + await expect(getActorToolResolutionCached('acme/standby-empty', client)).resolves.toEqual({ + toolType: null, + mcpServerUrl: null, + actorFullName: 'acme/standby-empty', + }); + }); + + 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({ + toolType: null, + mcpServerUrl: null, + actorFullName: 'acme/standby-empty-by-id', + }); + }); + + it('returns null for an Actor with no cached or fetchable definition', async () => { + getActorDefinitionMock.mockResolvedValue(null); + + await expect(getActorToolResolutionCached('acme/missing-resolution', client)).resolves.toBeNull(); + }); +}); diff --git a/tests/unit/utils.actor_details.test.ts b/tests/unit/utils.actor_details.test.ts index a221b3a49..38dc76b77 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,21 @@ 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.'); + }); +}); From 162fb95e32799cd05dd7ef80e9a585a72b45ef3a Mon Sep 17 00:00:00 2001 From: Jiri Spilka Date: Fri, 21 Aug 2026 09:49:06 +0200 Subject: [PATCH 2/9] feat: Enhance error handling for standby Actors without MCP servers --- src/errors.ts | 6 +- src/tools/actors/actor_tools_factory.ts | 9 +-- src/tools/actors/call_actor.ts | 22 ++++--- .../unit/mcp.server.actor_mode_matrix.test.ts | 29 +++++++++ tests/unit/utils.actor.cache.test.ts | 61 ------------------- 5 files changed, 50 insertions(+), 77 deletions(-) diff --git a/src/errors.ts b/src/errors.ts index b17f64ae0..1642ac372 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -68,7 +68,8 @@ export class ActorLoadError extends Error { 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.`, + `Actor "${actorName}" runs in standby mode without an MCP server and has an empty input schema,` + + ' which is not supported yet.', ); } @@ -76,7 +77,8 @@ export class ActorLoadError extends Error { 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/actors/actor_tools_factory.ts b/src/tools/actors/actor_tools_factory.ts index ed7d72af8..7650c7469 100644 --- a/src/tools/actors/actor_tools_factory.ts +++ b/src/tools/actors/actor_tools_factory.ts @@ -370,16 +370,17 @@ export async function getActorsAsTools( errors.push(ActorLoadError.standbyPaymentNotSupported(actorInfo.definition.actorFullName)); continue; } - // `null` means the Actor has no tool representation — standby with no MCP server and an empty - // input schema. Bulk loaders drop the error; `call-actor` forwards it to the agent. Logged here - // because the bulk path leaves no other server-side trace of the dropped Actor. + // `null` means the Actor has no tool representation. Bulk loaders drop the returned error, + // so log it here to retain a server-side trace. if (toolType === null) { + 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(ActorLoadError.standbyWithoutMcpNotSupported(actorInfo.definition.actorFullName)); + errors.push(error); continue; } if (toolType === TOOL_TYPE.ACTOR_MCP) actorMCPServersInfo.push(actorInfo); diff --git a/src/tools/actors/call_actor.ts b/src/tools/actors/call_actor.ts index 1c2535dc6..5d3e64920 100644 --- a/src/tools/actors/call_actor.ts +++ b/src/tools/actors/call_actor.ts @@ -359,9 +359,10 @@ export async function checkPaymentProviderStandbyConflict(params: { // 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); log.softFail('Rejecting call-actor for standby Actor under third-party payment provider', { - actorName: baseActorName, + actorName: error.actorName, paymentProviderId: paymentProvider.id, mcpSessionId, + actorLoadErrorKind: error.kind, failureCategory: FAILURE_CATEGORY.INVALID_INPUT, }); @@ -401,15 +402,6 @@ export async function handleMcpToolCall(params: { }): Promise { const { baseActorName, mcpToolName, input, resolution, apifyToken, mcpSessionId, signal } = params; - // `toolType: null` is the standby-without-MCP cell — the same reason the bare `call-actor` shape - // reports through `buildCallActorErrorResponse`. Both build the message from the canonical - // `actorFullName`, not the caller's identifier, so an Actor ID and a full name answer identically. - if (resolution?.toolType === null) { - return respondStandbyRejection(ActorLoadError.standbyWithoutMcpNotSupported(resolution.actorFullName), { - mcpSessionId, - }); - } - if (resolution?.toolType !== TOOL_TYPE.ACTOR_MCP) { return respondServerError(`Actor '${resolution?.actorFullName ?? baseActorName}' is not an MCP server.`); } @@ -609,6 +601,16 @@ export async function callActorPreExecute( // `checkPaymentProviderStandbyConflict` in the generic tool-call handler — see src/mcp/server.ts. const apifyClientForDefinition = new ApifyClient({ token: apifyToken }); const resolution = await getActorToolResolutionCached(baseActorName, apifyClientForDefinition); + + if (resolution?.toolType === null) { + return { + earlyResponse: respondStandbyRejection( + ActorLoadError.standbyWithoutMcpNotSupported(resolution.actorFullName), + { mcpSessionId }, + ), + }; + } + const isActorMcpServer = resolution?.toolType === TOOL_TYPE.ACTOR_MCP; // Handle the case where LLM does not respect instructions when calling MCP server Actors diff --git a/tests/unit/mcp.server.actor_mode_matrix.test.ts b/tests/unit/mcp.server.actor_mode_matrix.test.ts index 12d97f8aa..2f0a5eac1 100644 --- a/tests/unit/mcp.server.actor_mode_matrix.test.ts +++ b/tests/unit/mcp.server.actor_mode_matrix.test.ts @@ -14,6 +14,7 @@ vi.mock('../../src/mcp/client.js', () => ({ listTools: async () => ({ tools: [{ name: 'add', description: 'adds', inputSchema: { type: 'object', properties: {} } }], }), + callTool: async () => ({ content: [{ type: 'text', text: 'MCP result' }] }), close: async () => {}, })), })); @@ -125,6 +126,21 @@ describe('Actor run/standby mode decision table', () => { ); }); + 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('earlyResponse' in result).toBe(true); + expect(firstText((result as { earlyResponse: ToolResponse }).earlyResponse)).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); @@ -132,6 +148,19 @@ describe('Actor run/standby mode decision table', () => { expect(firstText((result as { earlyResponse: ToolResponse }).earlyResponse)).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`); diff --git a/tests/unit/utils.actor.cache.test.ts b/tests/unit/utils.actor.cache.test.ts index 08d485557..342adbe69 100644 --- a/tests/unit/utils.actor.cache.test.ts +++ b/tests/unit/utils.actor.cache.test.ts @@ -8,7 +8,6 @@ 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 { TOOL_TYPE } from '../../src/types.js'; import { getActorDefinitionCached, getActorMcpUrlCached, getActorToolResolutionCached } from '../../src/utils/actor.js'; import { getUserInfoCached } from '../../src/utils/userid_cache.js'; @@ -41,8 +40,6 @@ function seedCache( return entry; } -const NON_EMPTY_INPUT = { type: 'object', properties: { url: { type: 'string' } } }; - const client = { token: 'caller-token' } as unknown as ApifyClient; beforeEach(() => { @@ -150,64 +147,6 @@ describe('getActorMcpUrlCached — tool-type rule', () => { }); describe('getActorToolResolutionCached()', () => { - it('resolves a run-only Actor to ACTOR with no MCP URL', async () => { - seedCache('acme/run-only', true, 'owner-10', { input: NON_EMPTY_INPUT }); - - await expect(getActorToolResolutionCached('acme/run-only', client)).resolves.toEqual({ - toolType: TOOL_TYPE.ACTOR, - mcpServerUrl: null, - actorFullName: 'acme/run-only', - }); - }); - - it('resolves a run-only Actor with a leftover webServerMcpPath to ACTOR with no MCP URL', async () => { - seedCache('acme/run-only-stale', true, 'owner-11', { - id: 'actorstale2', - webServerMcpPath: '/mcp', - input: NON_EMPTY_INPUT, - }); - - await expect(getActorToolResolutionCached('acme/run-only-stale', client)).resolves.toEqual({ - toolType: TOOL_TYPE.ACTOR, - mcpServerUrl: null, - actorFullName: 'acme/run-only-stale', - }); - }); - - it('resolves a standby Actor with an MCP path to ACTOR_MCP and its URL', async () => { - seedCache('acme/standby-mcp', true, 'owner-12', { - id: 'actormcp', - webServerMcpPath: '/mcp', - isStandbyEnabled: true, - }); - - await expect(getActorToolResolutionCached('acme/standby-mcp', client)).resolves.toEqual({ - toolType: TOOL_TYPE.ACTOR_MCP, - mcpServerUrl: 'https://actormcp.apify.actor/mcp', - actorFullName: 'acme/standby-mcp', - }); - }); - - it('resolves a standby Actor without an MCP path but with a non-empty input schema to ACTOR', async () => { - seedCache('acme/standby-input', true, 'owner-13', { isStandbyEnabled: true, input: NON_EMPTY_INPUT }); - - await expect(getActorToolResolutionCached('acme/standby-input', client)).resolves.toEqual({ - toolType: TOOL_TYPE.ACTOR, - mcpServerUrl: null, - actorFullName: 'acme/standby-input', - }); - }); - - it('resolves a standby Actor without an MCP path and an empty input schema to no tool type', async () => { - seedCache('acme/standby-empty', true, 'owner-14', { isStandbyEnabled: true }); - - await expect(getActorToolResolutionCached('acme/standby-empty', client)).resolves.toEqual({ - toolType: null, - mcpServerUrl: null, - actorFullName: 'acme/standby-empty', - }); - }); - 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); From ed032fd64fe908264ea5b9e5fb39035ccaf1f316 Mon Sep 17 00:00:00 2001 From: Jiri Spilka Date: Fri, 21 Aug 2026 13:45:06 +0200 Subject: [PATCH 3/9] feat: Refactor Actor tool resolution to use ACTOR_TOOL_MODE for improved clarity --- src/tools/actor_tool_naming.ts | 34 +++++------ src/tools/actors/actor_tools_factory.ts | 14 ++--- src/tools/actors/call_actor.ts | 19 ++---- src/types.ts | 22 +++++-- src/utils/actor.ts | 27 +++------ src/utils/actor_details.ts | 9 +-- tests/unit/tools.actor.test.ts | 60 ++++++++++--------- tests/unit/tools.call_actor_common.test.ts | 8 +-- .../tools.call_actor_widget.response.test.ts | 4 +- tests/unit/tools.utils.test.ts | 16 ++--- tests/unit/utils.actor.cache.test.ts | 49 +++++++-------- 11 files changed, 124 insertions(+), 138 deletions(-) diff --git a/src/tools/actor_tool_naming.ts b/src/tools/actor_tool_naming.ts index d549a6814..9869ad298 100644 --- a/src/tools/actor_tool_naming.ts +++ b/src/tools/actor_tool_naming.ts @@ -4,31 +4,31 @@ 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 { TOOL_TYPE } from '../types.js'; +import { ACTOR_TOOL_MODE } from '../types.js'; /** * 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 | absent | any | `ACTOR` (run tool) | - * | disabled | present | any | `ACTOR` — the leftover path is ignored | - * | enabled | present | any | `ACTOR_MCP` (proxied MCP tools only) | - * | enabled | absent | non-empty | `ACTOR` (run tool) | - * | enabled | absent | empty | `null` | - * - * `null` is not a fourth `TOOL_TYPE` member: it is the absence of a tool. A standby-only Actor with an - * empty input schema has nothing to run and no MCP server to proxy, so it gets no tool at all. + * | standby | `webServerMcpPath` | input schema | result | + * |----------|--------------------|--------------|-----------------------| + * | disabled | absent | any | `RUN` | + * | disabled | present | 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 resolveActorToolType(actorInfo: ActorInfo): typeof TOOL_TYPE.ACTOR | typeof TOOL_TYPE.ACTOR_MCP | null { - if (!actorInfo.actor.actorStandby?.isEnabled) return TOOL_TYPE.ACTOR; - if (actorInfo.webServerMcpPath) return TOOL_TYPE.ACTOR_MCP; - return Object.keys(actorInfo.definition.input?.properties ?? {}).length > 0 ? TOOL_TYPE.ACTOR : null; +export function resolveActorToolMode(actorInfo: ActorInfo): ACTOR_TOOL_MODE { + const isStandbyEnabled = actorInfo.actor.actorStandby?.isEnabled === true; + if (isStandbyEnabled && actorInfo.webServerMcpPath) return ACTOR_TOOL_MODE.MCP; + if (isStandbyEnabled && Object.keys(actorInfo.definition.input?.properties ?? {}).length === 0) { + return ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP; + } + return ACTOR_TOOL_MODE.RUN; } /** @@ -37,8 +37,8 @@ export function resolveActorToolType(actorInfo: ActorInfo): typeof TOOL_TYPE.ACT * 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 7650c7469..de09f45e0 100644 --- a/src/tools/actors/actor_tools_factory.ts +++ b/src/tools/actors/actor_tools_factory.ts @@ -23,6 +23,7 @@ import { type ApifyToken, type ToolEntry, type ToolInputSchema, + ACTOR_TOOL_MODE, TOOL_TYPE, } from '../../types.js'; import { getActorDefinitionCached } from '../../utils/actor.js'; @@ -30,7 +31,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, resolveActorToolType } 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'; @@ -365,14 +366,13 @@ export async function getActorsAsTools( const actorMCPServersInfo: ActorInfo[] = []; const normalActorsInfo: ActorInfo[] = []; for (const actorInfo of nonNullActors) { - const toolType = resolveActorToolType(actorInfo); - if (paymentProvider && isActorBlockedUnderPaymentProvider(actorInfo)) { + if (paymentProvider && isActorBlockedUnderPaymentProvider(actorInfo.actor)) { errors.push(ActorLoadError.standbyPaymentNotSupported(actorInfo.definition.actorFullName)); continue; } - // `null` means the Actor has no tool representation. Bulk loaders drop the returned error, - // so log it here to retain a server-side trace. - if (toolType === null) { + + 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, @@ -383,7 +383,7 @@ export async function getActorsAsTools( errors.push(error); continue; } - if (toolType === TOOL_TYPE.ACTOR_MCP) actorMCPServersInfo.push(actorInfo); + 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 5d3e64920..f16567662 100644 --- a/src/tools/actors/call_actor.ts +++ b/src/tools/actors/call_actor.ts @@ -19,7 +19,6 @@ 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, ActorToolResolutionResult, ApifyToken, InternalToolArgs, @@ -27,7 +26,7 @@ import type { ToolEntry, ToolInputSchema, } from '../../types.js'; -import { ALL_TOOLS_PRESENT, TOOL_TYPE } 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 { @@ -344,15 +343,7 @@ export async function checkPaymentProviderStandbyConflict(params: { return null; } - // Stub for isActorBlockedUnderPaymentProvider, which only reads `actor` — the hardcoded null - // `webServerMcpPath` would make `resolveActorToolType` misclassify standby MCP Actors. - const actorInfo: ActorInfo = { - definition: actorDefinitionWithInfo.definition, - actor: actorDefinitionWithInfo.info, - webServerMcpPath: null, - }; - - if (!isActorBlockedUnderPaymentProvider(actorInfo)) { + if (!isActorBlockedUnderPaymentProvider(actorDefinitionWithInfo.info)) { return null; } @@ -402,7 +393,7 @@ export async function handleMcpToolCall(params: { }): Promise { const { baseActorName, mcpToolName, input, resolution, apifyToken, mcpSessionId, signal } = params; - if (resolution?.toolType !== TOOL_TYPE.ACTOR_MCP) { + if (resolution?.toolMode !== ACTOR_TOOL_MODE.MCP) { return respondServerError(`Actor '${resolution?.actorFullName ?? baseActorName}' is not an MCP server.`); } @@ -602,7 +593,7 @@ export async function callActorPreExecute( const apifyClientForDefinition = new ApifyClient({ token: apifyToken }); const resolution = await getActorToolResolutionCached(baseActorName, apifyClientForDefinition); - if (resolution?.toolType === null) { + if (resolution?.toolMode === ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP) { return { earlyResponse: respondStandbyRejection( ActorLoadError.standbyWithoutMcpNotSupported(resolution.actorFullName), @@ -611,7 +602,7 @@ export async function callActorPreExecute( }; } - const isActorMcpServer = resolution?.toolType === TOOL_TYPE.ACTOR_MCP; + 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. diff --git a/src/types.ts b/src/types.ts index d88335027..7cfd4c438 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} @@ -261,15 +269,19 @@ export type ActorInfo = { }; /** - * How an Actor is exposed as a tool, resolved once from its definition by `resolveActorToolType`. - * `mcpServerUrl` is a plain `string` exactly when `toolType` is {@link TOOL_TYPE.ACTOR_MCP}, so - * callers connect without a cast. `toolType: null` means the Actor has no tool representation. + * How an Actor is exposed as a tool, resolved once from its definition by `resolveActorToolMode`. + * `mcpServerUrl` is a plain `string` exactly when `toolMode` is {@link ACTOR_TOOL_MODE.MCP}, so + * callers connect without a cast. * `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 = - | { toolType: typeof TOOL_TYPE.ACTOR_MCP; mcpServerUrl: string; actorFullName: string } - | { toolType: typeof TOOL_TYPE.ACTOR | null; mcpServerUrl: null; actorFullName: string }; + | { toolMode: typeof ACTOR_TOOL_MODE.MCP; mcpServerUrl: string; actorFullName: string } + | { + toolMode: typeof ACTOR_TOOL_MODE.RUN | typeof ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP; + mcpServerUrl: null; + actorFullName: string; + }; export type ActorStoreList = ActorStoreListOutdated & { actorReviewCount?: number; diff --git a/src/utils/actor.ts b/src/utils/actor.ts index b4bf8b661..22d54c2f7 100644 --- a/src/utils/actor.ts +++ b/src/utils/actor.ts @@ -1,10 +1,10 @@ import type { ApifyClient } from '../apify_client.js'; import { getActorMCPServerPath, getActorMCPServerURL } from '../mcp/actors.js'; import { actorDefinitionCache } from '../state.js'; -import { resolveActorToolType } from '../tools/actor_tool_naming.js'; +import { resolveActorToolMode } from '../tools/actor_tool_naming.js'; import { getActorDefinition } from '../tools/actors/actor_definition.js'; import type { ActorDefinitionWithInfo, ActorToolResolutionResult } from '../types.js'; -import { TOOL_TYPE } from '../types.js'; +import { ACTOR_TOOL_MODE } from '../types.js'; import { getUserInfoCached } from './userid_cache.js'; /** @@ -46,7 +46,7 @@ export async function getActorDefinitionCached( } /** - * Resolve how an Actor is exposed as a tool at call time, by name. The only place `resolveActorToolType` + * 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 @@ -61,28 +61,19 @@ export async function getActorToolResolutionCached( if (!cached) return null; const webServerMcpPath = getActorMCPServerPath(cached.definition); - const toolType = resolveActorToolType({ + const toolMode = resolveActorToolMode({ definition: cached.definition, actor: cached.info, webServerMcpPath, }); const { actorFullName } = cached.definition; - // `resolveActorToolType` returns ACTOR_MCP only when `webServerMcpPath` is set; testing the path - // here narrows it to `string`, so the URL is built without a cast. - if (toolType === TOOL_TYPE.ACTOR_MCP && webServerMcpPath) { + // `resolveActorToolMode` returns MCP only when `webServerMcpPath` is set. + if (toolMode === ACTOR_TOOL_MODE.MCP) { return { - toolType, - mcpServerUrl: await getActorMCPServerURL(cached.definition.id, webServerMcpPath), + toolMode, + mcpServerUrl: await getActorMCPServerURL(cached.definition.id, webServerMcpPath!), actorFullName, }; } - return { toolType: toolType === TOOL_TYPE.ACTOR ? toolType : null, mcpServerUrl: null, actorFullName }; -} - -/** - * Resolve the Actor's MCP server URL, or `false` if it isn't an MCP server. - */ -export async function getActorMcpUrlCached(actorIdOrName: string, apifyClient: ApifyClient): Promise { - const resolution = await getActorToolResolutionCached(actorIdOrName, apifyClient); - return resolution?.toolType === TOOL_TYPE.ACTOR_MCP ? resolution.mcpServerUrl : false; + return { toolMode, mcpServerUrl: null, actorFullName }; } diff --git a/src/utils/actor_details.ts b/src/utils/actor_details.ts index e9a285333..ad604f264 100644 --- a/src/utils/actor_details.ts +++ b/src/utils/actor_details.ts @@ -6,7 +6,8 @@ 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 +163,10 @@ export async function getMcpToolsMessage( paymentProvider?: PaymentProvider, mcpSessionId?: string, ): Promise { - const mcpServerUrl = await getActorMcpUrlCached(actorName, apifyClient); + const resolution = await getActorToolResolutionCached(actorName, apifyClient); // 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 +176,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/tools.actor.test.ts b/tests/unit/tools.actor.test.ts index e8432a940..bf1190b36 100644 --- a/tests/unit/tools.actor.test.ts +++ b/tests/unit/tools.actor.test.ts @@ -3,9 +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, resolveActorToolType } 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 { TOOL_TYPE } from '../../src/types.js'; +import { ACTOR_TOOL_MODE } from '../../src/types.js'; describe('actors', () => { describe('actorNameToToolName', () => { @@ -83,76 +83,80 @@ function makeActorInfo(opts: { const NON_EMPTY_INPUT = { type: 'object', properties: { url: { type: 'string' } } }; -describe('resolveActorToolType()', () => { - it('returns ACTOR when standby is disabled and no MCP path is set', () => { - expect(resolveActorToolType(makeActorInfo({ input: NON_EMPTY_INPUT }))).toBe(TOOL_TYPE.ACTOR); +describe('resolveActorToolMode()', () => { + it('returns RUN when standby is disabled and no MCP path is set', () => { + expect(resolveActorToolMode(makeActorInfo({ input: NON_EMPTY_INPUT }))).toBe(ACTOR_TOOL_MODE.RUN); }); - it('returns ACTOR when standby is disabled despite a leftover MCP path', () => { - expect(resolveActorToolType(makeActorInfo({ webServerMcpPath: '/mcp', input: NON_EMPTY_INPUT }))).toBe( - TOOL_TYPE.ACTOR, + it('returns RUN when standby is disabled despite a leftover MCP path', () => { + expect(resolveActorToolMode(makeActorInfo({ webServerMcpPath: '/mcp', input: NON_EMPTY_INPUT }))).toBe( + ACTOR_TOOL_MODE.RUN, ); }); - it('returns ACTOR when standby is disabled and the input schema is empty', () => { - expect(resolveActorToolType(makeActorInfo({}))).toBe(TOOL_TYPE.ACTOR); + it('returns RUN when standby is disabled and the input schema is empty', () => { + expect(resolveActorToolMode(makeActorInfo({}))).toBe(ACTOR_TOOL_MODE.RUN); }); - it('returns ACTOR_MCP when standby is enabled and an MCP path is set', () => { - expect(resolveActorToolType(makeActorInfo({ isStandbyEnabled: true, webServerMcpPath: '/mcp' }))).toBe( - TOOL_TYPE.ACTOR_MCP, + it('returns MCP when standby is enabled and an MCP path is set', () => { + expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true, webServerMcpPath: '/mcp' }))).toBe( + ACTOR_TOOL_MODE.MCP, ); }); - it('returns ACTOR when standby is enabled without an MCP path but the input schema is non-empty', () => { - expect(resolveActorToolType(makeActorInfo({ isStandbyEnabled: true, input: NON_EMPTY_INPUT }))).toBe( - TOOL_TYPE.ACTOR, + it('returns RUN when standby is enabled without an MCP path but the input schema is non-empty', () => { + expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true, input: NON_EMPTY_INPUT }))).toBe( + ACTOR_TOOL_MODE.RUN, ); }); - it('returns null when standby is enabled without an MCP path and the input schema is empty', () => { - expect(resolveActorToolType(makeActorInfo({ isStandbyEnabled: true }))).toBeNull(); + it('returns STANDBY_WITHOUT_MCP when standby is enabled without an MCP path and the input schema is empty', () => { + expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true }))).toBe( + ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, + ); }); describe('empty input schema', () => { it('treats a missing input as empty', () => { - expect(resolveActorToolType(makeActorInfo({ isStandbyEnabled: true, input: undefined }))).toBeNull(); + expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true, input: undefined }))).toBe( + ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, + ); }); it('treats an input without properties as empty', () => { - expect( - resolveActorToolType(makeActorInfo({ isStandbyEnabled: true, input: { type: 'object' } })), - ).toBeNull(); + expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true, input: { type: 'object' } }))).toBe( + ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, + ); }); it('treats zero properties as empty', () => { expect( - resolveActorToolType( + resolveActorToolMode( makeActorInfo({ isStandbyEnabled: true, input: { type: 'object', properties: {} } }), ), - ).toBeNull(); + ).toBe(ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP); }); it('treats a non-empty required list with no properties as empty', () => { expect( - resolveActorToolType( + resolveActorToolMode( makeActorInfo({ isStandbyEnabled: true, input: { type: 'object', properties: {}, required: ['url'] }, }), ), - ).toBeNull(); + ).toBe(ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP); }); it('treats a non-object input carrying properties as non-empty', () => { expect( - resolveActorToolType( + resolveActorToolMode( makeActorInfo({ isStandbyEnabled: true, input: { type: 'string', properties: { url: { type: 'string' } } }, }), ), - ).toBe(TOOL_TYPE.ACTOR); + ).toBe(ACTOR_TOOL_MODE.RUN); }); }); }); diff --git a/tests/unit/tools.call_actor_common.test.ts b/tests/unit/tools.call_actor_common.test.ts index b31f32a72..f7e74d3cc 100644 --- a/tests/unit/tools.call_actor_common.test.ts +++ b/tests/unit/tools.call_actor_common.test.ts @@ -21,7 +21,7 @@ import { resolveAndValidateActor, } from '../../src/tools/actors/call_actor.js'; import type { InternalToolArgs, ToolEntry } from '../../src/types.js'; -import { TOOL_TYPE } from '../../src/types.js'; +import { ACTOR_TOOL_MODE, TOOL_TYPE } from '../../src/types.js'; import { textOf, type TextToolResult } from './helpers/tool_context.js'; vi.mock('../../src/tools/actors/actor_tools_factory.js', async () => { @@ -434,7 +434,7 @@ describe('call_actor_common', () => { mcpToolName: 'search', input: { q: 'x' }, resolution: { - toolType: TOOL_TYPE.ACTOR_MCP, + toolMode: ACTOR_TOOL_MODE.MCP, mcpServerUrl: 'https://example.invalid/mcp', actorFullName: 'apify/mcp-demo', }, @@ -459,7 +459,7 @@ describe('call_actor_common', () => { mcpToolName: 'search', input: { q: 'x' }, resolution: { - toolType: TOOL_TYPE.ACTOR_MCP, + toolMode: ACTOR_TOOL_MODE.MCP, mcpServerUrl: 'https://example.invalid/mcp', actorFullName: 'apify/mcp-demo', }, @@ -486,7 +486,7 @@ describe('call_actor_common', () => { mcpToolName: 'search', input: { q: 'x' }, resolution: { - toolType: TOOL_TYPE.ACTOR_MCP, + toolMode: ACTOR_TOOL_MODE.MCP, mcpServerUrl: 'https://example.invalid/mcp', actorFullName: 'apify/mcp-demo', }, diff --git a/tests/unit/tools.call_actor_widget.response.test.ts b/tests/unit/tools.call_actor_widget.response.test.ts index 21eca08f7..9706040e1 100644 --- a/tests/unit/tools.call_actor_widget.response.test.ts +++ b/tests/unit/tools.call_actor_widget.response.test.ts @@ -3,7 +3,7 @@ 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 { 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'; @@ -57,7 +57,7 @@ describe('call-actor-widget response', () => { beforeEach(() => { vi.mocked(getActorToolResolutionCached).mockReset(); vi.mocked(getActorToolResolutionCached).mockResolvedValue({ - toolType: TOOL_TYPE.ACTOR, + toolMode: ACTOR_TOOL_MODE.RUN, mcpServerUrl: null, actorFullName: 'apify/rag-web-browser', }); 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 342adbe69..355a5b5bc 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, getActorToolResolutionCached } 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); @@ -96,7 +97,7 @@ 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', @@ -104,13 +105,17 @@ describe('getActorMcpUrlCached — tenant isolation', () => { isStandbyEnabled: true, }); - const result = await getActorMcpUrlCached('acme/mcp-public', client); + const result = await getActorToolResolutionCached('acme/mcp-public', client); - expect(result).toBe('https://actorpub.apify.actor/mcp'); + 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 () => { + 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', @@ -119,48 +124,36 @@ describe('getActorMcpUrlCached — tenant isolation', () => { 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(); }); -}); -describe('getActorMcpUrlCached — tool-type rule', () => { - it('returns false when standby is disabled despite a leftover webServerMcpPath', async () => { + 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(getActorMcpUrlCached('acme/stale-path', client)).resolves.toBe(false); - }); - - it('returns false for a standby Actor with no MCP server and an empty input schema', async () => { - seedCache('acme/standby-empty-url', true, 'owner-9', { id: 'actorsbe', isStandbyEnabled: true }); - - await expect(getActorMcpUrlCached('acme/standby-empty-url', client)).resolves.toBe(false); + await expect(getActorToolResolutionCached('acme/stale-path', client)).resolves.toEqual({ + toolMode: ACTOR_TOOL_MODE.RUN, + mcpServerUrl: null, + actorFullName: 'acme/stale-path', + }); }); -}); -describe('getActorToolResolutionCached()', () => { 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({ - toolType: null, + toolMode: ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, mcpServerUrl: null, actorFullName: 'acme/standby-empty-by-id', }); }); - - it('returns null for an Actor with no cached or fetchable definition', async () => { - getActorDefinitionMock.mockResolvedValue(null); - - await expect(getActorToolResolutionCached('acme/missing-resolution', client)).resolves.toBeNull(); - }); }); From aa18cd1e63dea94b733525466827e648a8243761 Mon Sep 17 00:00:00 2001 From: Jiri Spilka Date: Fri, 21 Aug 2026 14:21:20 +0200 Subject: [PATCH 4/9] feat: Simplify Actor tool resolution and update related documentation --- src/tools/actor_tool_naming.ts | 9 +- src/tools/actors/call_actor.ts | 72 +++++------- src/types.ts | 17 ++- src/utils/actor.ts | 2 +- .../unit/mcp.server.actor_mode_matrix.test.ts | 66 +++++------ tests/unit/tools.actor.test.ts | 107 ++++++------------ tests/unit/tools.call_actor_common.test.ts | 20 +--- .../tools.call_actor_widget.response.test.ts | 1 - tests/unit/utils.actor.cache.test.ts | 2 - 9 files changed, 108 insertions(+), 188 deletions(-) diff --git a/src/tools/actor_tool_naming.ts b/src/tools/actor_tool_naming.ts index 9869ad298..a6b912300 100644 --- a/src/tools/actor_tool_naming.ts +++ b/src/tools/actor_tool_naming.ts @@ -12,8 +12,7 @@ import { ACTOR_TOOL_MODE } from '../types.js'; * * | standby | `webServerMcpPath` | input schema | result | * |----------|--------------------|--------------|-----------------------| - * | disabled | absent | any | `RUN` | - * | disabled | present | any | `RUN` | + * | disabled | any (path ignored) | any | `RUN` | * | enabled | present | any | `MCP` | * | enabled | absent | non-empty | `RUN` | * | enabled | absent | empty | `STANDBY_WITHOUT_MCP` | @@ -23,9 +22,9 @@ import { ACTOR_TOOL_MODE } from '../types.js'; * still reads as empty. */ export function resolveActorToolMode(actorInfo: ActorInfo): ACTOR_TOOL_MODE { - const isStandbyEnabled = actorInfo.actor.actorStandby?.isEnabled === true; - if (isStandbyEnabled && actorInfo.webServerMcpPath) return ACTOR_TOOL_MODE.MCP; - if (isStandbyEnabled && Object.keys(actorInfo.definition.input?.properties ?? {}).length === 0) { + 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; diff --git a/src/tools/actors/call_actor.ts b/src/tools/actors/call_actor.ts index f16567662..75ac6261b 100644 --- a/src/tools/actors/call_actor.ts +++ b/src/tools/actors/call_actor.ts @@ -18,14 +18,7 @@ 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 { - ActorToolResolutionResult, - ApifyToken, - InternalToolArgs, - ToolDescriptionContext, - ToolEntry, - ToolInputSchema, -} from '../../types.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'; @@ -175,13 +168,14 @@ export function buildCallActorAppsDescription(ctx: ToolDescriptionContext = ALL_ */ function respondStandbyRejection( error: ActorLoadError, - opts: { mcpSessionId?: string; actorId?: string }, + 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. + // 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, }); @@ -349,15 +343,7 @@ export async function checkPaymentProviderStandbyConflict(params: { // 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); - log.softFail('Rejecting call-actor for standby Actor under third-party payment provider', { - actorName: error.actorName, - paymentProviderId: paymentProvider.id, - mcpSessionId, - actorLoadErrorKind: error.kind, - failureCategory: FAILURE_CATEGORY.INVALID_INPUT, - }); - - return respondUserError(error.message, { detail: error.kind }); + return respondStandbyRejection(error, { mcpSessionId, paymentProviderId: paymentProvider.id }); } /** @@ -379,23 +365,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; - resolution: ActorToolResolutionResult | null; + mcpServerUrl: string; apifyToken: string; mcpSessionId?: string; signal: AbortSignal; -}): Promise { - const { baseActorName, mcpToolName, input, resolution, apifyToken, mcpSessionId, signal } = params; - - if (resolution?.toolMode !== ACTOR_TOOL_MODE.MCP) { - return respondServerError(`Actor '${resolution?.actorFullName ?? baseActorName}' is not an MCP server.`); - } +}): Promise { + const { baseActorName, mcpToolName, input, mcpServerUrl, apifyToken, mcpSessionId, signal } = params; if (!input) { return respondServerError( @@ -409,9 +391,9 @@ export async function handleMcpToolCall(params: { let client: Client | null = null; try { - client = await connectMCPClient(resolution.mcpServerUrl, apifyToken, mcpSessionId); + client = await connectMCPClient(mcpServerUrl, apifyToken, mcpSessionId); if (!client) { - return respondServerError(`Failed to connect to MCP server ${resolution.mcpServerUrl}`); + return respondServerError(`Failed to connect to MCP server ${mcpServerUrl}`); } const result = await client.callTool( @@ -613,20 +595,26 @@ 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, - resolution, - apifyToken, - mcpSessionId, - signal: toolArgs.signal, - }); - if (mcpResult) { - return { earlyResponse: mcpResult }; + if (resolution?.toolMode !== ACTOR_TOOL_MODE.MCP) { + return { + earlyResponse: respondServerError( + `Actor '${resolution?.actorFullName ?? baseActorName}' is not an MCP server.`, + ), + }; } + 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 7cfd4c438..f3f8b3bd2 100644 --- a/src/types.ts +++ b/src/types.ts @@ -263,25 +263,22 @@ 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 a plain `string` exactly when `toolMode` is {@link ACTOR_TOOL_MODE.MCP}, so - * callers connect without a cast. + * `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 = - | { toolMode: typeof ACTOR_TOOL_MODE.MCP; mcpServerUrl: string; actorFullName: string } - | { - toolMode: typeof ACTOR_TOOL_MODE.RUN | typeof ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP; - mcpServerUrl: null; - actorFullName: string; - }; +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; diff --git a/src/utils/actor.ts b/src/utils/actor.ts index 22d54c2f7..bb3ffdd6d 100644 --- a/src/utils/actor.ts +++ b/src/utils/actor.ts @@ -75,5 +75,5 @@ export async function getActorToolResolutionCached( actorFullName, }; } - return { toolMode, mcpServerUrl: null, actorFullName }; + return { toolMode, actorFullName }; } diff --git a/tests/unit/mcp.server.actor_mode_matrix.test.ts b/tests/unit/mcp.server.actor_mode_matrix.test.ts index 2f0a5eac1..62fde1a7e 100644 --- a/tests/unit/mcp.server.actor_mode_matrix.test.ts +++ b/tests/unit/mcp.server.actor_mode_matrix.test.ts @@ -77,6 +77,16 @@ 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 }); @@ -88,26 +98,15 @@ beforeEach(() => { }); describe('Actor run/standby mode decision table', () => { - describe('tools/list surface', () => { - it('loads a run tool for a run-only Actor', async () => { - expect(await loadedToolNames(RUN_ONLY)).toEqual(['acme--run-only']); - }); - - it('loads a run tool for a run-only Actor carrying a leftover webServerMcpPath', async () => { - expect(await loadedToolNames(RUN_ONLY_STALE_PATH)).toEqual(['acme--run-only-stale-path']); - }); - - it('loads only proxied MCP tools for a standby Actor exposing an MCP server', async () => { - expect(await loadedToolNames(STANDBY_MCP)).toEqual(['acme--standby-mcp--add']); - }); - - it('loads a run tool for a standby Actor with no MCP server but a non-empty input schema', async () => { - expect(await loadedToolNames(STANDBY_INPUT)).toEqual(['acme--standby-input']); - }); - - it('loads no tool for a standby Actor with no MCP server and an empty input schema', async () => { - expect(await loadedToolNames(STANDBY_EMPTY)).toEqual([]); - }); + // 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', () => { @@ -120,10 +119,7 @@ describe('Actor run/standby mode decision table', () => { 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('earlyResponse' in result).toBe(true); - expect(firstText((result as { earlyResponse: ToolResponse }).earlyResponse)).toContain( - 'is not an MCP server', - ); + expect(earlyText(result)).toContain('is not an MCP server'); }); it('runs a standby Actor with no MCP server but a non-empty input schema', async () => { @@ -135,17 +131,13 @@ describe('Actor run/standby mode decision table', () => { 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('earlyResponse' in result).toBe(true); - expect(firstText((result as { earlyResponse: ToolResponse }).earlyResponse)).toContain( - 'is not an MCP server', - ); + 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('earlyResponse' in result).toBe(true); - expect(firstText((result as { earlyResponse: ToolResponse }).earlyResponse)).toContain('tool name'); + expect(earlyText(result)).toContain('tool name'); }); it('proxies an MCP tool call on a standby Actor exposing an MCP server', async () => { @@ -165,21 +157,19 @@ describe('Actor run/standby mode decision table', () => { const bare = await callActor(STANDBY_EMPTY); const withToolName = await preExecute(`${STANDBY_EMPTY}:add`); - expect('earlyResponse' in withToolName).toBe(true); - const withToolNameText = firstText((withToolName as { earlyResponse: ToolResponse }).earlyResponse); + const withToolNameText = earlyText(withToolName); expect(firstText(bare)).toBe(withToolNameText); expect(withToolNameText).toContain('standby mode without an MCP server'); expect(bare.isError).toBe(true); - expect((withToolName as { earlyResponse: ToolResponse }).earlyResponse.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`); - expect('earlyResponse' in withToolName).toBe(true); - const withToolNameText = firstText((withToolName as { earlyResponse: ToolResponse }).earlyResponse); + const withToolNameText = earlyText(withToolName); expect(firstText(bare)).toBe(withToolNameText); expect(withToolNameText).toContain(STANDBY_EMPTY); @@ -190,7 +180,7 @@ describe('Actor run/standby mode decision table', () => { const result = await preExecute(`${RUN_ONLY_ID}:add`); expect('earlyResponse' in result).toBe(true); - const text = firstText((result as { earlyResponse: ToolResponse }).earlyResponse); + const text = earlyText(result); expect(text).toContain(RUN_ONLY); expect(text).not.toContain(RUN_ONLY_ID); }); @@ -199,8 +189,8 @@ describe('Actor run/standby mode decision table', () => { const unsupported = await preExecute(`${STANDBY_EMPTY}:add`); const runOnly = await preExecute(`${RUN_ONLY_STALE_PATH}:add`); - const unsupportedText = firstText((unsupported as { earlyResponse: ToolResponse }).earlyResponse); - const runOnlyText = firstText((runOnly as { earlyResponse: ToolResponse }).earlyResponse); + 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 bf1190b36..2b9314606 100644 --- a/tests/unit/tools.actor.test.ts +++ b/tests/unit/tools.actor.test.ts @@ -84,79 +84,40 @@ function makeActorInfo(opts: { const NON_EMPTY_INPUT = { type: 'object', properties: { url: { type: 'string' } } }; describe('resolveActorToolMode()', () => { - it('returns RUN when standby is disabled and no MCP path is set', () => { - expect(resolveActorToolMode(makeActorInfo({ input: NON_EMPTY_INPUT }))).toBe(ACTOR_TOOL_MODE.RUN); - }); - - it('returns RUN when standby is disabled despite a leftover MCP path', () => { - expect(resolveActorToolMode(makeActorInfo({ webServerMcpPath: '/mcp', input: NON_EMPTY_INPUT }))).toBe( - ACTOR_TOOL_MODE.RUN, - ); - }); - - it('returns RUN when standby is disabled and the input schema is empty', () => { - expect(resolveActorToolMode(makeActorInfo({}))).toBe(ACTOR_TOOL_MODE.RUN); - }); - - it('returns MCP when standby is enabled and an MCP path is set', () => { - expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true, webServerMcpPath: '/mcp' }))).toBe( - ACTOR_TOOL_MODE.MCP, - ); - }); - - it('returns RUN when standby is enabled without an MCP path but the input schema is non-empty', () => { - expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true, input: NON_EMPTY_INPUT }))).toBe( - ACTOR_TOOL_MODE.RUN, - ); - }); - - it('returns STANDBY_WITHOUT_MCP when standby is enabled without an MCP path and the input schema is empty', () => { - expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true }))).toBe( + // 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, - ); - }); - - describe('empty input schema', () => { - it('treats a missing input as empty', () => { - expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true, input: undefined }))).toBe( - ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, - ); - }); - - it('treats an input without properties as empty', () => { - expect(resolveActorToolMode(makeActorInfo({ isStandbyEnabled: true, input: { type: 'object' } }))).toBe( - ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, - ); - }); - - it('treats zero properties as empty', () => { - expect( - resolveActorToolMode( - makeActorInfo({ isStandbyEnabled: true, input: { type: 'object', properties: {} } }), - ), - ).toBe(ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP); - }); - - it('treats a non-empty required list with no properties as empty', () => { - expect( - resolveActorToolMode( - makeActorInfo({ - isStandbyEnabled: true, - input: { type: 'object', properties: {}, required: ['url'] }, - }), - ), - ).toBe(ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP); - }); - - it('treats a non-object input carrying properties as non-empty', () => { - expect( - resolveActorToolMode( - makeActorInfo({ - isStandbyEnabled: true, - input: { type: 'string', properties: { url: { type: 'string' } } }, - }), - ), - ).toBe(ACTOR_TOOL_MODE.RUN); - }); + ], + [ + '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 f7e74d3cc..0c8c7deb3 100644 --- a/tests/unit/tools.call_actor_common.test.ts +++ b/tests/unit/tools.call_actor_common.test.ts @@ -21,7 +21,7 @@ import { resolveAndValidateActor, } from '../../src/tools/actors/call_actor.js'; import type { InternalToolArgs, ToolEntry } from '../../src/types.js'; -import { ACTOR_TOOL_MODE, TOOL_TYPE } from '../../src/types.js'; +import { TOOL_TYPE } from '../../src/types.js'; import { textOf, type TextToolResult } from './helpers/tool_context.js'; vi.mock('../../src/tools/actors/actor_tools_factory.js', async () => { @@ -433,11 +433,7 @@ describe('call_actor_common', () => { baseActorName: 'apify/mcp-demo', mcpToolName: 'search', input: { q: 'x' }, - resolution: { - toolMode: ACTOR_TOOL_MODE.MCP, - mcpServerUrl: 'https://example.invalid/mcp', - actorFullName: 'apify/mcp-demo', - }, + mcpServerUrl: 'https://example.invalid/mcp', apifyToken: 'token', signal: controller.signal, }); @@ -458,11 +454,7 @@ describe('call_actor_common', () => { baseActorName: 'apify/mcp-demo', mcpToolName: 'search', input: { q: 'x' }, - resolution: { - toolMode: ACTOR_TOOL_MODE.MCP, - mcpServerUrl: 'https://example.invalid/mcp', - actorFullName: 'apify/mcp-demo', - }, + mcpServerUrl: 'https://example.invalid/mcp', apifyToken: 'token', signal: controller.signal, }); @@ -485,11 +477,7 @@ describe('call_actor_common', () => { baseActorName: 'apify/mcp-demo', mcpToolName: 'search', input: { q: 'x' }, - resolution: { - toolMode: ACTOR_TOOL_MODE.MCP, - mcpServerUrl: 'https://example.invalid/mcp', - actorFullName: 'apify/mcp-demo', - }, + 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 9706040e1..0e0ae2668 100644 --- a/tests/unit/tools.call_actor_widget.response.test.ts +++ b/tests/unit/tools.call_actor_widget.response.test.ts @@ -58,7 +58,6 @@ describe('call-actor-widget response', () => { vi.mocked(getActorToolResolutionCached).mockReset(); vi.mocked(getActorToolResolutionCached).mockResolvedValue({ toolMode: ACTOR_TOOL_MODE.RUN, - mcpServerUrl: null, actorFullName: 'apify/rag-web-browser', }); vi.mocked(getActorsAsTools).mockReset(); diff --git a/tests/unit/utils.actor.cache.test.ts b/tests/unit/utils.actor.cache.test.ts index 355a5b5bc..b423aced8 100644 --- a/tests/unit/utils.actor.cache.test.ts +++ b/tests/unit/utils.actor.cache.test.ts @@ -141,7 +141,6 @@ describe('getActorToolResolutionCached()', () => { await expect(getActorToolResolutionCached('acme/stale-path', client)).resolves.toEqual({ toolMode: ACTOR_TOOL_MODE.RUN, - mcpServerUrl: null, actorFullName: 'acme/stale-path', }); }); @@ -152,7 +151,6 @@ describe('getActorToolResolutionCached()', () => { await expect(getActorToolResolutionCached('aBcD1234', client)).resolves.toEqual({ toolMode: ACTOR_TOOL_MODE.STANDBY_WITHOUT_MCP, - mcpServerUrl: null, actorFullName: 'acme/standby-empty-by-id', }); }); From fce2f0ee85b89f7641c96c69088d3ad745f963ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vojt=C4=9Bch=20Je=C5=99=C3=A1bek?= Date: Mon, 24 Aug 2026 10:52:00 +0200 Subject: [PATCH 5/9] fix: Answer not-found for the actor:toolName shape on unknown Actors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An unknown Actor called as `actor:toolName` answered "Actor 'X' is not an MCP server.", which implies the Actor exists — the bare call shape already answered "was not found". Extract the canonical not-found response into respondActorNotFound() and return it from the `:toolName` route when the resolution is null, so both call shapes give one consistent answer. Co-Authored-By: Claude Fable 5 --- src/tools/actors/call_actor.ts | 35 +++++++++++-------- .../unit/mcp.server.actor_mode_matrix.test.ts | 14 ++++++++ 2 files changed, 35 insertions(+), 14 deletions(-) diff --git a/src/tools/actors/call_actor.ts b/src/tools/actors/call_actor.ts index 75ac6261b..5b6b49505 100644 --- a/src/tools/actors/call_actor.ts +++ b/src/tools/actors/call_actor.ts @@ -182,6 +182,21 @@ function respondStandbyRejection( 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): ToolResponse { + 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. + You can search for available Actors using the tool: ${HELPER_TOOLS.STORE_SEARCH}. + `, + { httpStatus: 404, detail: `Actor '${actorName}' was not found` }, + ); +} + export function buildCallActorErrorResponse(params: CallActorErrorResponseParams): ToolResponse { const { actorName, error, actorId, mcpSessionId, loadedToolNames } = params; @@ -473,16 +488,7 @@ export async function resolveAndValidateActor(params: { const actor = tools[0]; if (!actor) { - 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. - You can search for available Actors using the tool: ${HELPER_TOOLS.STORE_SEARCH}. - `, - { httpStatus: 404, detail: `Actor '${actorName}' was not found` }, - ), - }; + return { error: respondActorNotFound(actorName) }; } const actorId = extractActorId(actor); @@ -597,11 +603,12 @@ export async function callActorPreExecute( // A `:toolName` suffix only means anything for an MCP-server Actor; every other mode is a dead end. if (mcpToolName) { - if (resolution?.toolMode !== ACTOR_TOOL_MODE.MCP) { + if (resolution === null) { + return { earlyResponse: respondActorNotFound(baseActorName) }; + } + if (resolution.toolMode !== ACTOR_TOOL_MODE.MCP) { return { - earlyResponse: respondServerError( - `Actor '${resolution?.actorFullName ?? baseActorName}' is not an MCP server.`, - ), + earlyResponse: respondServerError(`Actor '${resolution.actorFullName}' is not an MCP server.`), }; } return { diff --git a/tests/unit/mcp.server.actor_mode_matrix.test.ts b/tests/unit/mcp.server.actor_mode_matrix.test.ts index 62fde1a7e..a43c502e0 100644 --- a/tests/unit/mcp.server.actor_mode_matrix.test.ts +++ b/tests/unit/mcp.server.actor_mode_matrix.test.ts @@ -9,6 +9,12 @@ 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 () => ({ @@ -185,6 +191,14 @@ describe('Actor run/standby mode decision table', () => { 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`); From f87eea9682a52d3b338d10fe66a89725c61019d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 24 Aug 2026 20:29:22 +0000 Subject: [PATCH 6/9] fix: Classify a tool name on a non-MCP Actor as a caller mistake `call-actor "actor:toolName"` aimed at a non-MCP Actor answered via respondServerError, recording FAILED / INTERNAL_ERROR and raising an error-level alert on the hosted server. The caller named a tool on an Actor that has none, so it is invalid input, not a server fault. --- src/tools/actors/call_actor.ts | 4 +++- tests/unit/mcp.server.actor_mode_matrix.test.ts | 13 ++++++++++++- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/src/tools/actors/call_actor.ts b/src/tools/actors/call_actor.ts index 1aaed617f..057980916 100644 --- a/src/tools/actors/call_actor.ts +++ b/src/tools/actors/call_actor.ts @@ -629,7 +629,9 @@ export async function callActorPreExecute( } if (resolution.toolMode !== ACTOR_TOOL_MODE.MCP) { return { - earlyResponse: respondServerError(`Actor '${resolution.actorFullName}' is not an MCP server.`), + earlyResponse: respondUserError(`Actor '${resolution.actorFullName}' is not an MCP server.`, { + detail: 'tool name given for a non-MCP Actor', + }), }; } return { diff --git a/tests/unit/mcp.server.actor_mode_matrix.test.ts b/tests/unit/mcp.server.actor_mode_matrix.test.ts index a43c502e0..1f90c634b 100644 --- a/tests/unit/mcp.server.actor_mode_matrix.test.ts +++ b/tests/unit/mcp.server.actor_mode_matrix.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'; import { ApifyClient } from '../../src/apify_client.js'; -import { HELPER_TOOLS } from '../../src/const.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'; @@ -128,6 +128,17 @@ describe('Actor run/standby mode decision table', () => { 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); From 7fe65dc714723867a8470921330c4b46254c73b0 Mon Sep 17 00:00:00 2001 From: MQ37 Date: Thu, 27 Aug 2026 14:34:17 +0200 Subject: [PATCH 7/9] fix: report canonical standby-without-MCP message from getMcpToolsMessage fetch-actor-details' mcpTools note collapsed the unsupported standby-without-MCP cell into the generic 'not an MCP server' text, even though call-actor already gives that Actor a specific rejection. Reuse the same canonical message so an agent gets one consistent reason for the Actor regardless of which tool asked. --- src/utils/actor_details.ts | 7 +++++++ tests/unit/utils.actor_details.test.ts | 19 +++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/utils/actor_details.ts b/src/utils/actor_details.ts index ad604f264..57b279d6a 100644 --- a/src/utils/actor_details.ts +++ b/src/utils/actor_details.ts @@ -2,6 +2,7 @@ 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'; @@ -165,6 +166,12 @@ export async function getMcpToolsMessage( ): Promise { 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 (resolution?.toolMode !== ACTOR_TOOL_MODE.MCP) { return `Note: This Actor is not an MCP server and does not expose MCP tools.`; diff --git a/tests/unit/utils.actor_details.test.ts b/tests/unit/utils.actor_details.test.ts index 38dc76b77..d19416763 100644 --- a/tests/unit/utils.actor_details.test.ts +++ b/tests/unit/utils.actor_details.test.ts @@ -198,4 +198,23 @@ describe('getMcpToolsMessage()', () => { 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.', + ); + }); }); From 56f55dd3e0242cf4bd5d3698facd62ab30ec26cf Mon Sep 17 00:00:00 2001 From: MQ37 Date: Thu, 27 Aug 2026 14:59:23 +0200 Subject: [PATCH 8/9] style: run oxfmt on the new getMcpToolsMessage test --- tests/unit/utils.actor_details.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/unit/utils.actor_details.test.ts b/tests/unit/utils.actor_details.test.ts index d19416763..17b996ba1 100644 --- a/tests/unit/utils.actor_details.test.ts +++ b/tests/unit/utils.actor_details.test.ts @@ -199,7 +199,7 @@ describe('getMcpToolsMessage()', () => { 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 () => { + 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 }, From 859cac9b94556c0920725dcaeba273acbc4a640f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 31 Aug 2026 20:45:41 +0000 Subject: [PATCH 9/9] docs: Correct two stale comments in call_actor STANDBY_PAYMENT_NOT_SUPPORTED cannot reach the rethrow because the getActorsAsTools call above passes no paymentProvider, not because an upstream guard catches it first. The payment guard also lives in tool_call_engine.ts, not server.ts. --- src/tools/actors/call_actor.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/tools/actors/call_actor.ts b/src/tools/actors/call_actor.ts index 057980916..c3ea6adef 100644 --- a/src/tools/actors/call_actor.ts +++ b/src/tools/actors/call_actor.ts @@ -500,9 +500,10 @@ 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 / - // STANDBY_WITHOUT_MCP_NOT_SUPPORTED) is rethrown so the outer call-actor handler reports it; - // STANDBY_PAYMENT_NOT_SUPPORTED is also caught upstream by `checkPaymentProviderStandbyConflict` - // in the tool-call engine, so it's a defensive fallback here. + // 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]; } @@ -598,7 +599,7 @@ 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 resolution = await getActorToolResolutionCached(baseActorName, apifyClientForDefinition);