Skip to main content
Glama
t3rmed

Hyperliquid MCP Server

by t3rmed

get_l2_book

Retrieve Level 2 order book data for cryptocurrency trading pairs on Hyperliquid DEX to analyze market depth and liquidity for informed trading decisions.

Instructions

Get L2 order book snapshot for a specific coin

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
coinYesThe coin symbol (e.g., BTC, ETH, SOL)
nSigFigsNoNumber of significant figures for price aggregation (optional)

Implementation Reference

  • Main handler function executing the get_l2_book tool: extracts parameters, fetches L2 book via client, formats bids/asks as text response.
    async def handle_get_l2_book(client: HyperliquidClient, args: Dict[str, Any]) -> Dict[str, Any]:
        """Handle get L2 book request."""
        coin = args["coin"]
        n_sig_figs = args.get("nSigFigs")
    
        result = await client.get_l2_book(coin, n_sig_figs)
    
        if not result.success:
            raise ValueError(f"Failed to get L2 book for {coin}: {result.error}")
    
        book = result.data
        bids = book.get("levels", [[], []])[0] if book else []
        asks = book.get("levels", [[], []])[1] if book else []
    
        bids_text = "\n".join(f"{b['px']} @ {b['sz']}" for b in bids)
        asks_text = "\n".join(f"{a['px']} @ {a['sz']}" for a in asks)
    
        return {
            "content": [
                TextContent(
                    type="text",
                    text=f"L2 Order Book for {coin}:\n\nBids ({len(bids)} levels):\n{bids_text}\n\nAsks ({len(asks)} levels):\n{asks_text}",
                )
            ]
        }
  • Tool registration defining the get_l2_book MCP tool with input schema requiring 'coin' and optional 'nSigFigs'.
    get_l2_book_tool = Tool(
        name="get_l2_book",
        description="Get L2 order book snapshot for a specific coin",
        inputSchema={
            "type": "object",
            "properties": {
                "coin": {
                    "type": "string",
                    "description": "The coin symbol (e.g., BTC, ETH, SOL)",
                },
                "nSigFigs": {
                    "type": "number",
                    "description": "Number of significant figures for price aggregation (optional)",
                    "minimum": 1,
                    "maximum": 5,
                },
            },
            "required": ["coin"],
        },
    )
  • Input schema for validating tool arguments: coin (required string), nSigFigs (optional number 1-5).
    inputSchema={
        "type": "object",
        "properties": {
            "coin": {
                "type": "string",
                "description": "The coin symbol (e.g., BTC, ETH, SOL)",
            },
            "nSigFigs": {
                "type": "number",
                "description": "Number of significant figures for price aggregation (optional)",
                "minimum": 1,
                "maximum": 5,
            },
        },
        "required": ["coin"],
    },
  • Supporting method in HyperliquidClient that queries the Hyperliquid API for L2 book data, used by the handler.
    async def get_l2_book(
        self, coin: str, n_sig_figs: Optional[int] = None
    ) -> ApiResponse[L2BookResponse]:
        """Get L2 order book snapshot for a specific coin."""
        try:
            payload = {"type": "l2Book", "coin": coin}
            if n_sig_figs is not None:
                payload["nSigFigs"] = n_sig_figs
    
            response = await self.client.post("/info", json=payload)
            response.raise_for_status()
            return ApiResponse(success=True, data=response.json())
        except Exception as e:
            return ApiResponse(success=False, error=str(e))
  • MCP server registration of all tools including get_l2_book_tool in the list_tools handler.
    @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 the full burden of behavioral disclosure. It states it 'Get[s] L2 order book snapshot', implying a read-only operation, but doesn't clarify if this requires authentication, has rate limits, returns real-time or cached data, or what the output format entails. For a tool with zero annotation coverage, this is a significant gap, scoring a 2.

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 without any wasted words. It directly states what the tool does, making it easy to parse and understand quickly. This exemplifies excellent conciseness and structure, earning a 5.

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 the complexity of financial data tools, no annotations, and no output schema, the description is incomplete. It doesn't explain what an 'L2 order book snapshot' entails (e.g., bid/ask levels, depth), return values, or behavioral traits like latency or authentication needs. For a tool in this context, more detail is needed, resulting in a score of 2.

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 input schema has 100% description coverage, with clear docs for 'coin' and 'nSigFigs'. The description adds no additional parameter semantics beyond implying the tool is coin-specific, which is already covered in the schema. With high schema coverage, the baseline is 3, as the description doesn't compensate but doesn't detract either.

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 verb 'Get' and the resource 'L2 order book snapshot for a specific coin', making the purpose immediately understandable. It specifies the scope ('for a specific coin') but doesn't explicitly differentiate from siblings like 'get_all_mids' or 'get_candle_snapshot', which might also provide market data. This is clear but lacks sibling differentiation, warranting a 4.

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, such as 'get_all_mids' for mid-prices or 'get_candle_snapshot' for historical data. It doesn't mention prerequisites, exclusions, or specific contexts, leaving the agent to infer usage based on the name alone. This lack of explicit guidance results in a score of 2.

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