Skip to main content
Glama

cancel_task

DestructiveIdempotent

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;
    });
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

The description adds valuable context beyond annotations by specifying what types of tasks can be cancelled (pending or running) and the batch-level operation option. While annotations already indicate destructiveHint=true and idempotentHint=true, the description clarifies the operational scope without contradicting annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is perfectly concise with a single sentence that contains no wasted words. It's front-loaded with the core action and immediately specifies the two operational modes, making every word earn its place.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's destructive nature (destructiveHint=true) and lack of output schema, the description provides good context about what the tool does. However, it doesn't mention potential side effects, error conditions, or what happens after cancellation, which would be helpful for a destructive operation.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

With 100% schema description coverage, the input schema already fully documents both parameters (task_id and batch_id) with their descriptions and mutual exclusivity rules. The description doesn't add significant parameter semantics beyond what's in the schema, maintaining the baseline score.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the specific action ('Cancel') and target resources ('a pending or running task, or all tasks in a batch'), distinguishing it from sibling tools like check_task_status, get_task_result, list_tasks, run_task, and wait_for_task. It precisely defines the scope of what can be cancelled.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context about when to use this tool (to cancel pending/running tasks or entire batches), but doesn't explicitly mention when NOT to use it or name specific alternatives. It implies usage for task management but lacks explicit exclusions or comparison with siblings.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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