Skip to main content
Glama
t3rmed

Hyperliquid MCP Server

by t3rmed

cancel_order

Cancel trading orders on Hyperliquid DEX using order ID or client order ID to manage positions and execute portfolio adjustments.

Instructions

Cancel a specific order by order ID or client order ID

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
assetIndexYesAsset index for the coin
clientOrderIdNoClient order ID to cancel (use either orderId or clientOrderId)
orderIdNoOrder ID to cancel (use either orderId or clientOrderId)

Implementation Reference

  • The async handle_cancel_order function implements the core logic for the cancel_order tool: extracts args, validates orderId or clientOrderId, creates CancelOrderItem and CancelOrderAction, calls client.cancel_order, returns formatted success response or raises ValueError on failure.
    async def handle_cancel_order(client: HyperliquidClient, args: Dict[str, Any]) -> Dict[str, Any]:
        """Handle cancel order request."""
        asset_index = args["assetIndex"]
        order_id = args.get("orderId")
        client_order_id = args.get("clientOrderId")
    
        if not order_id and not client_order_id:
            raise ValueError("Either orderId or clientOrderId must be provided")
    
        cancel_item = CancelOrderItem(a=asset_index)
        if order_id:
            cancel_item.o = order_id
        else:
            cancel_item.c = client_order_id
    
        action = CancelOrderAction(cancels=[cancel_item])
        result = await client.cancel_order(action)
    
        if not result.success:
            raise ValueError(f"Failed to cancel order: {result.error}")
    
        return {
            "content": [
                TextContent(
                    type="text",
                    text=f"Order cancelled successfully!\n\n{json.dumps(result.data, indent=2)}",
                )
            ]
        }
  • The handleCancelOrder function implements the core logic for the cancel_order tool: extracts args, validates orderId or clientOrderId, creates cancel object and CancelOrderAction, calls client.cancelOrder, returns formatted success response or throws Error on failure. Nearly identical to Python version.
    export async function handleCancelOrder(client: HyperliquidClient, args: any) {
      const { assetIndex, orderId, clientOrderId } = args;
    
      if (!orderId && !clientOrderId) {
        throw new Error('Either orderId or clientOrderId must be provided');
      }
    
      const cancel: any = { a: assetIndex };
    
      if (orderId) {
        cancel.o = orderId;
      } else {
        cancel.c = clientOrderId;
      }
    
      const action: CancelOrderAction = {
        type: 'cancel',
        cancels: [cancel]
      };
    
      const result = await client.cancelOrder(action);
    
      if (!result.success) {
        throw new Error(`Failed to cancel order: ${result.error}`);
      }
    
      return {
        content: [
          {
            type: 'text',
            text: `Order cancelled successfully!\n\n${JSON.stringify(result.data, null, 2)}`
          }
        ]
      };
    }
  • Defines the cancel_order_tool Tool object with name, description, and detailed inputSchema specifying parameters like assetIndex (required), orderId, clientOrderId.
    cancel_order_tool = Tool(
        name="cancel_order",
        description="Cancel a specific order by order ID or client order ID",
        inputSchema={
            "type": "object",
            "properties": {
                "assetIndex": {
                    "type": "number",
                    "description": "Asset index for the coin",
                },
                "orderId": {
                    "type": "number",
                    "description": "Order ID to cancel (use either orderId or clientOrderId)",
                },
                "clientOrderId": {
                    "type": "string",
                    "description": "Client order ID to cancel (use either orderId or clientOrderId)",
                },
            },
            "required": ["assetIndex"],
        },
    )
  • Defines the cancelOrderTool Tool object with name, description, and inputSchema matching the Python version.
    export const cancelOrderTool: Tool = {
      name: 'cancel_order',
      description: 'Cancel a specific order by order ID or client order ID',
      inputSchema: {
        type: 'object',
        properties: {
          assetIndex: {
            type: 'number',
            description: 'Asset index for the coin'
          },
          orderId: {
            type: 'number',
            description: 'Order ID to cancel (use either orderId or clientOrderId)'
          },
          clientOrderId: {
            type: 'string',
            description: 'Client order ID to cancel (use either orderId or clientOrderId)'
          }
        },
        required: ['assetIndex']
      }
    };
  • The list_tools handler registers cancel_order_tool among other tools for the MCP server.
    @app.list_tools()
    async def list_tools() -> list:
        """List all available tools."""
        return [
            # Market data tools
            get_all_mids_tool,
            get_l2_book_tool,
            get_candle_snapshot_tool,
            # Account info tools
            get_open_orders_tool,
            get_user_fills_tool,
            get_user_fills_by_time_tool,
            get_portfolio_tool,
            # Trading tools
            place_order_tool,
            place_trigger_order_tool,
            cancel_order_tool,
            cancel_all_orders_tool,
        ]
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 only states the action without behavioral details. It doesn't disclose whether cancellation is reversible, requires specific permissions, affects portfolio balances, has rate limits, or returns confirmation details. For a mutation tool with zero annotation coverage, this is a significant gap.

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 a single, efficient sentence that front-loads the core purpose with zero redundant information. Every word earns its place by specifying the action, target, and identification methods.

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?

For a mutation tool ('cancel') with no annotations and no output schema, the description is incomplete. It doesn't explain what happens upon cancellation (e.g., order status change, funds release), error conditions, or return values. Given the complexity of order management, more context is needed.

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 100%, so the schema already documents all three parameters thoroughly. The description adds minimal value by mentioning 'order ID or client order ID', which is already covered in parameter descriptions. Baseline 3 is appropriate when schema does the heavy lifting.

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 specific order'), specifying identification methods ('by order ID or client order ID'). It distinguishes from sibling 'cancel_all_orders' by focusing on individual cancellation, though it doesn't explicitly name that sibling.

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

Usage Guidelines3/5

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

The description implies usage context through 'specific order' and parameter descriptions mentioning 'use either orderId or clientOrderId', suggesting this tool is for targeted cancellations. However, it doesn't explicitly state when to use this versus 'cancel_all_orders' or other order-related tools, nor does it mention prerequisites like order status.

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/t3rmed/hyperliquid-mcp'

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