-
Notifications
You must be signed in to change notification settings - Fork 137
Expand file tree
/
Copy pathtypes.ts
More file actions
631 lines (581 loc) · 20.2 KB
/
types.ts
File metadata and controls
631 lines (581 loc) · 20.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
import type { TaskStore } from '@modelcontextprotocol/sdk/experimental/tasks/interfaces.js';
import type { Server } from '@modelcontextprotocol/sdk/server/index.js';
import type { RequestHandlerExtra } from '@modelcontextprotocol/sdk/shared/protocol.js';
import type { InitializeRequest, Notification, Prompt, Request, ToolSchema } from '@modelcontextprotocol/sdk/types.js';
import type { ValidateFunction } from 'ajv';
import type {
Actor as ActorOutdated,
ActorDefaultRunOptions,
ActorDefinition,
ActorRunPricingInfo,
ActorStats,
ActorStoreList as ActorStoreListOutdated,
PricePerEventActorPricingInfo as PricePerEventActorPricingInfoOutdated,
} from 'apify-client';
import type z from 'zod';
import type { ApifyClient } from './apify-client.js';
import type { ACTOR_PRICING_MODEL, TELEMETRY_ENV, TOOL_STATUS } from './const.js';
import type { ActorsMcpServer } from './mcp/server.js';
import type { CATEGORY_NAMES } from './tools/categories.js';
import type { StructuredPricingInfo } from './utils/pricing-info.js';
import type { ProgressTracker } from './utils/progress.js';
export type SchemaProperties = {
type: string;
title: string;
description: string;
enum?: string[]; // Array of string options for the enum
enumTitles?: string[]; // Array of string titles for the enum
default?: unknown;
prefill?: unknown;
items?: SchemaProperties;
editor?: string;
examples?: unknown[];
properties?: Record<string, SchemaProperties>;
required?: string[];
};
export type ActorInputSchema = {
$id?: string;
title?: string;
description?: string;
type: string;
properties: Record<string, SchemaProperties>;
required?: string[];
schemaVersion?: number;
};
export type ActorDefinitionWithDesc = Omit<ActorDefinition, 'input'> & {
id: string;
actorFullName: string;
description: string;
readmeSummary?: string;
defaultRunOptions: ActorDefaultRunOptions;
input?: ActorInputSchema;
};
/**
* Pruned Actor definition type.
* The `id` property is set to Actor ID.
*/
export type ActorDefinitionPruned = Pick<ActorDefinitionWithDesc,
'id' | 'actorFullName' | 'buildTag' | 'readme' | 'readmeSummary' | 'input' | 'description' | 'defaultRunOptions'> & {
webServerMcpPath?: string; // Optional, used for Actorized MCP server tools
pictureUrl?: string; // Optional, URL to the Actor's icon/picture
};
/**
* Actor definition combined with full actor metadata.
* Contains both the pruned definition (for schemas) and complete actor info.
*/
export type ActorDefinitionWithInfo = {
definition: ActorDefinitionPruned;
info: ActorOutdated;
};
/**
* Base type for all tools in the MCP server.
* Extends the MCP SDK's Tool schema, which requires inputSchema to have type: "object".
* Adds ajvValidate for runtime validation.
*/
export type ToolBase = z.infer<typeof ToolSchema> & {
/** AJV validation function for the input schema */
ajvValidate: ValidateFunction;
/** Whether this tool requires Skyfire pay ID validation (uses Apify API) */
requiresSkyfirePayId?: boolean;
/** Whether this tool is only available in OpenAI UI mode */
openaiOnly?: boolean;
};
/**
* Type for MCP SDK's inputSchema constraint.
* Extracted directly from the MCP SDK's ToolSchema to ensure alignment with the specification.
* The MCP SDK requires inputSchema to have type: "object" (literal) at the top level.
* Use this type when casting schemas that have type: string to the strict MCP format.
*/
export type ToolInputSchema = z.infer<typeof ToolSchema>['inputSchema'];
/**
* Type for Actor-based tools - tools that wrap Apify Actors.
* Type discriminator: 'actor'
*/
export type ActorTool = ToolBase & {
/** Type discriminator for actor tools */
type: 'actor';
/** Full name of the Apify Actor (username/name) */
actorFullName: string;
/** Optional memory limit in MB for the Actor execution */
memoryMbytes?: number;
};
/**
* Arguments passed to internal tool calls.
* Contains both the tool arguments and server references.
*/
export type InternalToolArgs = {
/** Arguments passed to the tool */
args: Record<string, unknown>;
/** Extra data given to request handlers.
*
* Can be used to send notifications from the server to the client.
*
* For more details see: https://github.com/modelcontextprotocol/typescript-sdk/blob/f822c1255edcf98c4e73b9bf17a9dd1b03f86716/src/shared/protocol.ts#L102
*/
extra: RequestHandlerExtra<Request, Notification>;
/** Reference to the Apify MCP server instance */
apifyMcpServer: ActorsMcpServer;
/** Reference to the MCP server instance */
mcpServer: Server;
/** Apify API token */
apifyToken: string;
/** List of Actor IDs that the user has rented */
userRentedActorIds?: string[];
/** Optional progress tracker for long running internal tools, like call-actor */
progressTracker?: ProgressTracker | null;
/** MCP session ID for logging context */
mcpSessionId?: string;
};
/**
* Helper tool - tools implemented directly in the MCP server.
* Type discriminator: 'internal'
*/
export type HelperTool = ToolBase & {
/** Type discriminator for helper/internal tools */
type: 'internal';
/**
* Executes the tool with the given arguments
* @param toolArgs - Arguments and server references
* @returns Promise resolving to the tool's output
*/
call: (toolArgs: InternalToolArgs) => Promise<object>;
};
/**
* Actor MCP tool - tools from Actorized MCP servers that this server proxies.
* Type discriminator: 'actor-mcp'
*/
export type ActorMcpTool = ToolBase & {
/** Type discriminator for actor MCP tools */
type: 'actor-mcp';
/** Origin MCP server tool name is needed for the tool call */
originToolName: string;
/** ID of the Actorized MCP server - for example, apify/actors-mcp-server */
actorId: string;
/**
* ID of the Actorized MCP server the tool is associated with.
* serverId is generated unique ID based on the serverUrl.
*/
serverId: string;
/** Connection URL of the Actorized MCP server */
serverUrl: string;
};
/**
* Discriminated union of all tool types.
*
* This is a discriminated union that ensures type safety:
* - When type is 'internal', tool is guaranteed to be HelperTool
* - When type is 'actor', tool is guaranteed to be ActorTool
* - When type is 'actor-mcp', tool is guaranteed to be ActorMcpTool
*/
export type ToolEntry = HelperTool | ActorTool | ActorMcpTool;
/**
* Price for a single event in a specific tier.
*/
export type TieredEventPrice = {
tieredEventPriceUsd: number;
};
/**
* Allowed pricing tiers for tiered event pricing.
*/
export type PricingTier = 'FREE' | 'BRONZE' | 'SILVER' | 'GOLD' | 'PLATINUM' | 'DIAMOND';
/**
* Describes a single chargeable event for an Actor.
* Supports either flat pricing (eventPriceUsd) or tiered pricing (eventTieredPricingUsd).
*/
export type ActorChargeEvent = {
eventTitle: string;
eventDescription?: string;
/** Flat price per event in USD (if not tiered) */
eventPriceUsd?: number;
/** Tiered pricing per event, by tier name (FREE, BRONZE, etc.) */
eventTieredPricingUsd?: Partial<Record<PricingTier, TieredEventPrice>>;
};
export type TieredPricing = {
[tier: string]: {
tieredPricePerUnitUsd: number;
};
}
type PricePerEventActorPricingInfo = PricePerEventActorPricingInfoOutdated & {
pricingPerEvent: {
actorChargeEvents: Record<string, ActorChargeEvent>;
};
}
export type PricingInfo = ActorRunPricingInfo & {
tieredPricing?: TieredPricing;
} | PricePerEventActorPricingInfo;
export type ToolCategory = (typeof CATEGORY_NAMES)[number];
/**
* Selector for tools input - can be a category key or a specific tool name.
*/
export type ToolSelector = ToolCategory | string;
export type Input = {
/**
* When `actors` is undefined, that means the default Actors should be loaded.
* If it is as an empty string or empty array, then no Actors should be loaded.
* Otherwise, the specified Actors should be loaded.
*/
actors?: string[] | string;
/**
* @deprecated Use `enableAddingActors` instead.
*/
enableActorAutoLoading?: boolean | string;
enableAddingActors?: boolean | string;
maxActorMemoryBytes?: number;
debugActor?: string;
debugActorInput?: unknown;
/**
* Tool selectors to include (category keys or concrete tool names).
* When `tools` is undefined that means the default tool categories should be loaded.
* If it is an empty string or empty array then no internal tools should be loaded.
* Otherwise the specified categories and/or concrete tool names should be loaded.
*/
tools?: ToolSelector[] | string;
};
// Utility type to get a union of values from an object type
export type ActorPricingModel = (typeof ACTOR_PRICING_MODEL)[keyof typeof ACTOR_PRICING_MODEL];
/**
* Telemetry environment type.
* Derived from TELEMETRY_ENV to ensure type safety and avoid duplication.
*/
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
definition: ActorDefinitionPruned;
actor: ActorOutdated;
};
export type ActorStoreList = ActorStoreListOutdated & {
actorReviewCount?: number;
actorReviewRating?: number;
badge?: string | null;
bookmarkCount?: number;
categories?: string[];
currentPricingInfo: ActorRunPricingInfo;
isWhiteListedForAgenticPayments?: boolean;
notice?: string | null;
userFullName?: string;
stats: ActorStats & {
actorReviewCount?: number;
actorReviewRating?: number;
bookmarkCount?: number;
publicActorRunStats30Days?: Partial<Record<string, number>> & {
SUCCEEDED?: number;
TOTAL?: number;
};
};
};
export type Actor = ActorOutdated & {
actorPermissionLevel?: string;
hasNoDataset?: boolean;
isCritical?: boolean;
isGeneric?: boolean;
isSourceCodeHidden?: boolean;
pictureUrl?: string;
standbyUrl?: string | null;
stats: ActorStats & {
publicActorRunStats30Days?: Partial<Record<string, number>> & {
SUCCEEDED?: number;
TOTAL?: number;
};
actorReviewCount?: number;
actorReviewRating?: number;
bookmarkCount?: number;
lastRunStartedAt?: string | Date | null;
};
};
export type ActorDefinitionStorage = {
views: Record<
string,
{
transformation: {
fields?: string[];
};
display: {
properties: Record<
string,
object
>;
};
}
>;
};
export type ApifyDocsSearchResult = {
/** URL of the documentation page, may include anchor (e.g., https://docs.apify.com/actors#build-actors) */
url: string;
/** Piece of content that matches the search query from Algolia */
content?: string;
};
export type PromptBase = Prompt & {
/**
* AJV validation function for the prompt arguments.
*/
ajvValidate: ValidateFunction;
/**
* Function to render the prompt with given arguments
*/
render: (args: Record<string, string>) => string;
};
export type ActorInputSchemaProperties = Record<string, SchemaProperties>;
export type DatasetItem = Record<number | string, unknown>;
/**
* Apify token type.
*
* Can be null or undefined in case of Skyfire requests.
*/
export type ApifyToken = string | null | undefined;
/**
* Unified status type for tool execution lifecycle.
* Derived from TOOL_STATUS to ensure type safety and avoid duplication.
*/
export type ToolStatus = (typeof TOOL_STATUS)[keyof typeof TOOL_STATUS];
/**
* Properties for tool call telemetry events sent to Segment.
*/
export type ToolCallTelemetryProperties = {
app: 'mcp';
app_version: string;
mcp_client_name: string;
mcp_client_version: string;
mcp_protocol_version: string;
mcp_client_capabilities: Record<string, unknown> | null;
mcp_session_id: string;
transport_type: string;
tool_name: string;
tool_status: ToolStatus;
tool_exec_time_ms: number;
};
/**
* UI mode for tool responses.
*/
export type UiMode = 'openai';
/**
* Parameters for executing a direct actor tool (`type: 'actor'`).
* Used by ActorExecutor implementations.
*/
export type ActorExecutionParams = {
/** Full name of the Actor (e.g., "apify/rag-web-browser") */
actorFullName: string;
/** Input to pass to the Actor (skyfire-pay-id already stripped) */
input: Record<string, unknown>;
/** Apify client (may be Skyfire-aware) */
apifyClient: ApifyClient;
/** Call options (memory, timeout) */
callOptions: { memory?: number; timeout?: number };
/** Progress tracker for sending progress notifications */
progressTracker?: ProgressTracker | null;
/** Signal for aborting the execution */
abortSignal?: AbortSignal;
/** MCP session ID for logging */
mcpSessionId?: string;
};
/**
* Result from an ActorExecutor.
* Returns `null` when the execution was aborted.
*/
export type ActorExecutionResult = {
content: { type: 'text'; text: string }[];
structuredContent?: Record<string, unknown>;
_meta?: Record<string, unknown>;
} | null;
/**
* Executor for direct actor tools (`type: 'actor'`).
* Selected at server construction time based on uiMode.
* Default mode runs synchronously; OpenAI mode runs async with widget metadata.
*/
export type ActorExecutor = {
executeActorTool(params: ActorExecutionParams): Promise<ActorExecutionResult>;
};
/**
* External store for Actor metadata that can be injected by the hosting environment.
* Provides access to Actor output schemas inferred from historical run data.
* When not provided, tools use generic output schemas without field-level detail.
*/
export type ActorStore = {
/**
* Returns the inferred JSON Schema properties for an Actor's dataset items,
* based on historical successful runs.
*
* The returned object should be a JSON Schema `properties` object, e.g.:
* `{ url: { type: 'string' }, price: { type: 'number' } }`
*
* Returns null if no schema is available (e.g., new Actor with no runs).
* Internally calls `getActorOutputSchemaAsTypeObject` and converts the result.
*
* @param actorFullName - Full Actor name in "username/name" format (e.g., "apify/rag-web-browser")
*/
getActorOutputSchema(actorFullName: string): Promise<Record<string, unknown> | null>;
/**
* Returns the inferred output schema as a simplified type object for an Actor's dataset items,
* based on historical successful runs.
*
* The returned object uses a compact type representation, e.g.:
* `{ url: "string", price: "number", tags: ["string"], user: { name: "string" } }`
*
* This is the core method that performs cache lookup, API resolution, and MongoDB queries.
* Results are cached with TTL to avoid repeated database queries.
*
* Returns null if no schema is available (e.g., new Actor with no runs).
*
* @param actorFullName - Full Actor name in "username/name" format (e.g., "apify/rag-web-browser")
*/
getActorOutputSchemaAsTypeObject(actorFullName: string): Promise<Record<string, unknown> | null>;
};
/**
* Options for configuring the ActorsMcpServer instance.
*/
export type ActorsMcpServerOptions = {
/**
* Task store for long running tasks support.
*/
taskStore?: TaskStore;
/**
* External store for Actor metadata (output schemas).
* When provided, Actor tools will have enriched output schemas with field-level detail.
* Only used by the streamable HTTP transport in hosted deployments.
*/
actorStore?: ActorStore;
setupSigintHandler?: boolean;
/**
* Switch to enable Skyfire agentic payment mode.
*/
skyfireMode?: boolean;
/**
* Allow unauthenticated mode - tools can be called without an Apify API token.
* This is primarily used for making documentation tools available without authentication.
* When enabled, Apify token validation is skipped.
* Default: false
*/
allowUnauthMode?: boolean;
initializeRequestData?: InitializeRequest;
/**
* Telemetry configuration options.
*/
telemetry?: {
/**
* Enable or disable telemetry tracking for tool calls.
* Must be explicitly set when telemetry object is provided.
* When a telemetry object is omitted entirely, defaults to true (via env var or default).
*/
enabled: boolean;
/**
* Telemetry environment when telemetry is enabled.
* - 'DEV': Use development Segment write key
* - 'PROD': Use production Segment write key (default)
*/
env?: TelemetryEnv;
};
/**
* Transport type for telemetry tracking.
* Important: this is also used for the long-running tasks logic
* which is different for local and remote server based on the transport type.
* - 'stdio': Direct/local stdio connection
* - 'http': Remote HTTP streamable connection
* - 'sse': Remote Server-Sent Events (SSE) connection (deprecated, removal on 2026-04-01)
*/
transportType?: 'stdio' | 'http' | 'sse';
/**
* Apify API token for authentication
* Primarily used by stdio transport when token is read from ~/.apify/auth.json file
* instead of APIFY_TOKEN environment variable, so it can be passed to the server
*/
token?: string;
/**
* UI mode for tool responses.
* - 'openai': OpenAI specific widget rendering
* If not specified, there will be no widget rendering.
*/
uiMode?: UiMode;
}
export type StructuredActorCard = {
title?: string;
url: string;
fullName: string;
pictureUrl?: string;
developer: {
username: string;
isOfficialApify: boolean;
url: string;
};
description: string;
categories: string[];
pricing: StructuredPricingInfo;
stats?: {
totalUsers: number;
monthlyUsers: number;
successRate?: number;
bookmarks?: number;
};
rating?: {
average: number;
count: number;
};
modifiedAt?: string;
isDeprecated: boolean;
}
/**
* Options for controlling which sections to include in an Actor card.
* All options default to true for backwards compatibility.
*/
export type ActorCardOptions = {
/** Include description text only */
includeDescription?: boolean;
/** Include usage statistics (users, runs, success rate, bookmarks) */
includeStats?: boolean;
/** Include pricing information */
includePricing?: boolean;
/** Include rating */
includeRating?: boolean;
/** Include metadata (developer, categories, last modified date, deprecation warning) */
includeMetadata?: boolean;
}
/**
* MCP request parameters with Apify-specific extensions.
* Extends the standard MCP params object with Apify custom fields in the _meta object.
*/
export type ApifyRequestParams = {
/**
* Metadata object for MCP and Apify-specific fields.
*/
_meta?: {
/** Session ID for tracking MCP requests across the Apify server */
mcpSessionId?: string;
/** Apify API token for authentication */
apifyToken?: string;
/** List of Actor IDs that the user has rented */
userRentedActorIds?: string[];
/** Progress token for out-of-band progress notifications (standard MCP) */
progressToken?: string | number;
/** Allow other metadata fields */
[key: string]: unknown;
};
/** Allow any other request parameters */
[key: string]: unknown;
};
/** MCP Server Card per SEP-1649. */
export type ServerCard = {
$schema: string;
version: string;
protocolVersion: string;
serverInfo: {
name: string;
title: string;
version: string;
};
description: string;
iconUrl: string;
documentationUrl: string;
transport: {
type: string;
endpoint: string;
};
capabilities: {
tools: { listChanged: boolean };
};
authentication: {
required: boolean;
schemes: string[];
};
tools: string;
};