Skip to main content
Glama

cancel_task

Stop a running A2A agent task by providing its task ID to manage agent operations.

Instructions

Cancel a running task on an A2A agent.

Args: task_id: ID of the task to cancel

Returns: Cancellation result

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
task_idYes

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • MCP tool handler for 'cancel_task'. Looks up the agent URL for the task, creates an A2AClient, calls client.cancel_task with the task ID, and returns success/error based on the A2A response.
    async def cancel_task(
        task_id: str,
        ctx: Context = None,
    ) -> Dict[str, Any]:
        """
        Cancel a running task on an A2A agent.
        
        Args:
            task_id: ID of the task to cancel
            
        Returns:
            Cancellation result
        """
        if task_id not in task_agent_mapping:
            return {
                "status": "error",
                "message": f"Task ID not found: {task_id}",
            }
        
        agent_url = task_agent_mapping[task_id]
        
        # Create a client for the agent
        client = A2AClient(url=agent_url)
        
        try:
            # Create the request payload
            payload = {
                "id": task_id
            }
            
            if ctx:
                await ctx.info(f"Cancelling task: {task_id}")
            
            # Send the cancel task request
            result = await client.cancel_task(payload)
            
            # Debug: Print the raw response for analysis
            if ctx:
                await ctx.info(f"Raw cancellation result: {result}")
                
            # Create a response dictionary
            if hasattr(result, "error"):
                return {
                    "status": "error",
                    "task_id": task_id,
                    "message": result.error.message,
                    "code": result.error.code
                }
            elif hasattr(result, "result"):
                return {
                    "status": "success",
                    "task_id": task_id,
                    "message": "Task cancelled successfully"
                }
            else:
                return {
                    "status": "unknown",
                    "task_id": task_id,
                    "message": "Unexpected response format"
                }
                
        except Exception as e:
            return {
                "status": "error",
                "message": f"Error cancelling task: {str(e)}",
            }
  • A2A client method that sends the CancelTaskRequest to the A2A server.
    async def cancel_task(self, payload: dict[str, Any]) -> CancelTaskResponse:
        request = CancelTaskRequest(params=payload)
        return CancelTaskResponse(**await self._send_request(request))
  • A2A server request dispatcher that handles CancelTaskRequest by calling task_manager.on_cancel_task.
    elif isinstance(json_rpc_request, CancelTaskRequest):
        result = await self.task_manager.on_cancel_task(
            json_rpc_request
        )
  • InMemoryTaskManager implementation of on_cancel_task. Currently returns TaskNotCancelableError without performing cancellation.
    async def on_cancel_task(
        self, request: CancelTaskRequest
    ) -> CancelTaskResponse:
        logger.info(f'Cancelling task {request.params.id}')
        task_id_params: TaskIdParams = request.params
    
        async with self.lock:
            task = self.tasks.get(task_id_params.id)
            if task is None:
                return CancelTaskResponse(
                    id=request.id, error=TaskNotFoundError()
                )
    
        return CancelTaskResponse(id=request.id, error=TaskNotCancelableError())
  • Pydantic models defining the request and response schemas for the A2A 'tasks/cancel' method.
    class CancelTaskRequest(JSONRPCRequest):
        method: Literal['tasks/cancel',] = 'tasks/cancel'
        params: TaskIdParams
    
    
    class CancelTaskResponse(JSONRPCResponse):
        result: Task | None = None
Behavior2/5

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

With no annotations provided, the description carries full burden but offers limited behavioral insight. It states the tool cancels a 'running task' and returns a 'cancellation result', but doesn't disclose critical details like required permissions, whether cancellation is reversible, potential side effects on the agent, or error conditions (e.g., invalid task_id). This is inadequate for a mutation tool with zero annotation coverage.

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

Conciseness4/5

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

The description is front-loaded with the core purpose, followed by structured Args and Returns sections. It's efficient with minimal waste, though the 'Returns' line is vague ('Cancellation result') and could be more informative without sacrificing brevity.

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

Completeness3/5

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

Given the tool's complexity (a mutation with no annotations) and schema richness (0% coverage, but has output schema), the description is partially complete. It covers the basic action and parameter, and the output schema may handle return values, but it lacks behavioral context, usage guidelines, and detailed parameter semantics, making it only minimally viable.

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?

Schema description coverage is 0%, but the description adds basic meaning by specifying 'task_id: ID of the task to cancel'. This clarifies the parameter's purpose beyond the schema's type definition. However, it doesn't provide format details (e.g., UUID), validation rules, or examples, leaving gaps given the low coverage.

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

Purpose4/5

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

The description clearly states the action ('Cancel') and target ('a running task on an A2A agent'), providing specific verb+resource. However, it doesn't explicitly differentiate from sibling tools like 'get_task_result' or 'unregister_agent' that might also interact with tasks or agents, which prevents a perfect score.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., the task must be running), exclusions (e.g., cannot cancel completed tasks), or comparisons to siblings like 'get_task_result' for checking task status, leaving the agent with minimal context for decision-making.

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/GongRzhe/A2A-MCP-Server'

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