Skip to main content
Glama
gerred

MCP Server Replicate

cancel_prediction

Stop an ongoing AI model prediction to manage resources and control costs when needed.

Instructions

Cancel a running prediction.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
prediction_idYes

Implementation Reference

  • The MCP tool handler for 'cancel_prediction' that executes the cancellation logic using the ReplicateClient.
    async def cancel_prediction(prediction_id: str) -> dict[str, Any]:
        """Cancel a running prediction."""
        async with ReplicateClient(api_token=os.getenv("REPLICATE_API_TOKEN")) as client:
            response = await client.cancel_prediction(prediction_id)
            return await response.json()
  • Supporting method in ReplicateClient that performs the HTTP POST request to the Replicate API endpoint for canceling a prediction.
    async def cancel_prediction(self, prediction_id: str) -> dict[str, Any]:
        """Cancel a running prediction.
        
        Args:
            prediction_id: The ID of the prediction to cancel
            
        Returns:
            Dict containing the updated prediction status
            
        Raises:
            ValueError: If the prediction is not found
            Exception: If the cancellation fails
        """
        if not self.client:
            raise RuntimeError("Client not initialized. Check error property for details.")
    
        try:
            response = await self.http_client.post(
                f"/predictions/{prediction_id}/cancel",
                headers={
                    "Authorization": f"Bearer {self.api_token}",
                    "Content-Type": "application/json",
                }
            )
            response.raise_for_status()
            return response.json()
            
        except httpx.HTTPStatusError as err:
            if err.response.status_code == 404:
                raise ValueError(f"Prediction not found: {prediction_id}")
            logger.error(f"Failed to cancel prediction: {str(err)}")
            raise Exception(f"Failed to cancel prediction: {str(err)}") from err
        except Exception as err:
            logger.error(f"Failed to cancel prediction: {str(err)}")
            raise Exception(f"Failed to cancel prediction: {str(err)}") from err
  • Pydantic model defining the structure of prediction responses, used as output type/schema for the tool.
    class Prediction(BaseModel):
        """A prediction (model run) on Replicate."""
        id: str = Field(..., description="Unique identifier for this prediction")
        version: str = Field(..., description="Model version used for this prediction")
        status: PredictionStatus = Field(..., description="Current status of the prediction")
        input: Dict[str, Any] = Field(..., description="Input parameters used for the prediction")
        output: Optional[Any] = Field(None, description="Output from the prediction if completed")
        error: Optional[str] = Field(None, description="Error message if prediction failed")
        logs: Optional[str] = Field(None, description="Execution logs from the prediction")
        created_at: datetime
        started_at: Optional[datetime] = None
        completed_at: Optional[datetime] = None
        urls: Dict[str, str] = Field(..., description="Related API URLs for this prediction")
        metrics: Optional[Dict[str, float]] = Field(None, description="Performance metrics if available")
        stream_url: Optional[str] = Field(None, description="URL for streaming output if requested") 
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It states the action ('Cancel') but doesn't explain what cancellation entails (e.g., whether it's reversible, if resources are freed, error conditions, or response format). For a mutation tool with zero annotation coverage, this leaves significant behavioral gaps.

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 extremely concise at just four words, front-loading the essential action and target. Every word earns its place with zero redundancy or unnecessary elaboration.

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

Completeness2/5

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

Given this is a mutation tool with no annotations, no output schema, and minimal parameter documentation, the description is inadequate. It doesn't explain what happens after cancellation, potential side effects, error scenarios, or how this interacts with sibling prediction tools, leaving the agent with insufficient context for reliable invocation.

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?

The description doesn't mention parameters at all, and with 0% schema description coverage for the single 'prediction_id' parameter, the schema provides only basic type information. However, since there's only one parameter and its purpose is somewhat inferable from context, this meets the baseline for minimal viability without adding meaningful semantic value.

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 resource ('a running prediction'), providing a specific verb+resource combination. However, it doesn't distinguish this tool from potential alternatives among its siblings, as there's no explicit comparison to tools like 'get_prediction' or 'create_prediction' that might handle prediction lifecycle differently.

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 minimal guidance with 'running prediction' implying usage context, but lacks explicit when-to-use rules, prerequisites (e.g., prediction must be active), or alternatives (e.g., what to do if prediction is already completed). No exclusions or comparisons to sibling tools are mentioned.

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/gerred/mcp-server-replicate'

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