MCPcopy Create free account
hub / github.com/modelcontextprotocol/typescript-sdk / handleAutomaticTaskPolling

Method handleAutomaticTaskPolling

src/server/mcp.ts:363–398  ·  view source on GitHub ↗

* Handles automatic task polling for tools with taskSupport 'optional'.

(
        tool: RegisteredTool,
        request: RequestT,
        extra: RequestHandlerExtra<ServerRequest, ServerNotification>
    )

Source from the content-addressed store, hash-verified

361 * Handles automatic task polling for tools with taskSupport 'optional'.
362 */
363 private async handleAutomaticTaskPolling<RequestT extends CallToolRequest>(
364 tool: RegisteredTool,
365 request: RequestT,
366 extra: RequestHandlerExtra<ServerRequest, ServerNotification>
367 ): Promise<CallToolResult> {
368 if (!extra.taskStore) {
369 throw new Error('No task store provided for task-capable tool.');
370 }
371
372 // Validate input and create task
373 const args = await this.validateToolInput(tool, request.params.arguments, request.params.name);
374 const handler = tool.handler as ToolTaskHandler<ZodRawShapeCompat | undefined>;
375 const taskExtra = { ...extra, taskStore: extra.taskStore };
376
377 const createTaskResult: CreateTaskResult = args // undefined only if tool.inputSchema is undefined
378 ? await Promise.resolve((handler as ToolTaskHandler<ZodRawShapeCompat>).createTask(args, taskExtra))
379 : // eslint-disable-next-line @typescript-eslint/no-explicit-any
380 await Promise.resolve(((handler as ToolTaskHandler<undefined>).createTask as any)(taskExtra));
381
382 // Poll until completion
383 const taskId = createTaskResult.task.taskId;
384 let task = createTaskResult.task;
385 const pollInterval = task.pollInterval ?? 5000;
386
387 while (task.status !== 'completed' && task.status !== 'failed' && task.status !== 'cancelled') {
388 await new Promise(resolve => setTimeout(resolve, pollInterval));
389 const updatedTask = await extra.taskStore.getTask(taskId);
390 if (!updatedTask) {
391 throw new McpError(ErrorCode.InternalError, `Task ${taskId} not found during polling`);
392 }
393 task = updatedTask;
394 }
395
396 // Return the final result
397 return (await extra.taskStore.getTaskResult(taskId)) as CallToolResult;
398 }
399
400 private _completionHandlerInitialized = false;
401

Callers 1

Calls 4

validateToolInputMethod · 0.95
createTaskMethod · 0.65
getTaskMethod · 0.65
getTaskResultMethod · 0.65

Tested by

no test coverage detected