Skip to main content
Glama

cancel_task

Cancel a pending or running task or all tasks in a batch to manage AI workflows and free up resources.

Instructions

Cancel a pending or running task, or all tasks in a batch.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
task_idNoThe task ID to cancel (required if batch_id not provided)
batch_idNoCancel all tasks with this batch ID (required if task_id not provided)

Implementation Reference

  • Schema definition for the cancel_task MCP tool, including input schema for task_id or batch_id.
    const CANCEL_TASK_TOOL: Tool = {
        name: 'cancel_task',
        description: 'Cancel a pending or running task, or all tasks in a batch.',
        annotations: {
            title: 'Cancel Task',
            readOnlyHint: false, // Modifies task state
            destructiveHint: true, // Cancels/stops a running task
            idempotentHint: true, // Cancelling an already cancelled task is safe
            openWorldHint: false, // Only affects local task state
        },
        inputSchema: {
            type: 'object',
            properties: {
                task_id: {
                    type: 'string',
                    description:
                        'The task ID to cancel (required if batch_id not provided)',
                },
                batch_id: {
                    type: 'string',
                    description:
                        'Cancel all tasks with this batch ID (required if task_id not provided)',
                },
            },
            required: [], // At least one must be provided, validated in handler
        },
    };
  • Main handler for cancel_task tool execution. Validates input, cancels single task via taskManager.cancelTask or all tasks in a batch by iterating and calling cancelTask on each.
    case 'cancel_task': {
        // Validate that at least one parameter is provided
        if (!args.task_id && !args.batch_id) {
            throw new Error('Either task_id or batch_id is required');
        }
    
        if (args.task_id && args.batch_id) {
            throw new Error(
                'Provide either task_id or batch_id, not both'
            );
        }
    
        // Handle single task cancellation
        if (args.task_id) {
            const cancelled = taskManager.cancelTask(args.task_id);
    
            return {
                content: [
                    {
                        type: 'text',
                        text: cancelled
                            ? `Task ${args.task_id} cancelled successfully`
                            : `Could not cancel task ${args.task_id} (may be already completed)`,
                    },
                ],
            };
        }
    
        // Handle batch cancellation
        if (args.batch_id) {
            const allTasks = taskManager.getAllTasks();
            const batchTasks = allTasks.filter(
                t => t.batchId === args.batch_id
            );
    
            if (batchTasks.length === 0) {
                return {
                    content: [
                        {
                            type: 'text',
                            text: `No tasks found with batch_id: ${args.batch_id}`,
                        },
                    ],
                };
            }
    
            let cancelledCount = 0;
            let alreadyCompleteCount = 0;
    
            for (const task of batchTasks) {
                if (taskManager.cancelTask(task.id)) {
                    cancelledCount++;
                } else if (
                    task.status === 'completed' ||
                    task.status === 'failed' ||
                    task.status === 'cancelled'
                ) {
                    alreadyCompleteCount++;
                }
            }
    
            return {
                content: [
                    {
                        type: 'text',
                        text: JSON.stringify(
                            {
                                batch_id: args.batch_id,
                                total_tasks: batchTasks.length,
                                cancelled: cancelledCount,
                                already_complete: alreadyCompleteCount,
                                message: `Cancelled ${cancelledCount} tasks from batch ${args.batch_id}`,
                            },
                            null,
                            2
                        ),
                    },
                ],
            };
        }
    
        // Should never reach here due to validation above
        throw new Error('Invalid cancel_task parameters');
    }
  • Core cancelTask method in TaskManager singleton. Aborts the AbortController if running/pending, sets status to 'cancelled', logs the action.
    public cancelTask(taskId: string): boolean {
        const task = this.tasks.get(taskId);
        if (!task) {
            return false;
        }
    
        if (task.status === 'running' || task.status === 'pending') {
            task.abortController?.abort();
            task.status = 'cancelled';
            task.completedAt = new Date();
            logger.info(`Cancelled task ${taskId}`);
            return true;
        }
    
        return false;
    }
  • src/serve.ts:558-579 (registration)
    Registers cancel_task by including CANCEL_TASK_TOOL in the list returned by ListToolsRequestHandler.
    server.setRequestHandler(ListToolsRequestSchema, async () => {
        if (process.env.MCP_MODE !== 'true') {
            logger.debug('Received ListTools request');
        }
        const response = {
            tools: [
                RUN_TASK_TOOL,
                CHECK_TASK_STATUS_TOOL,
                GET_TASK_RESULT_TOOL,
                CANCEL_TASK_TOOL,
                WAIT_FOR_TASK_TOOL,
                LIST_TASKS_TOOL,
            ],
        };
        if (process.env.MCP_MODE !== 'true') {
            logger.debug(
                'Returning tools:',
                response.tools.map(t => t.name)
            );
        }
        return response;
    });

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/just-every/mcp-task'

If you have feedback or need assistance with the MCP directory API, please join our Discord server