Skip to main content
Glama
sammcj

Bybit MCP Server

by sammcj

get_orderbook

Retrieve real-time orderbook data for a specific trading pair on Bybit, including market depth for bids and asks, to analyze liquidity and trading opportunities.

Instructions

Get orderbook (market depth) data for a trading pair

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
categoryNoCategory of the instrument (spot, linear, inverse)
limitNoLimit for the number of bids and asks (1, 25, 50, 100, 200)
symbolYesTrading pair symbol (e.g., 'BTCUSDT')

Implementation Reference

  • Main handler logic for the get_orderbook tool: input validation, API call execution with retry, response formatting, and error handling.
    async toolCall(request: z.infer<typeof CallToolRequestSchema>) {
      try {
        this.logInfo("Starting get_orderbook tool call")
    
        // Parse and validate input
        const validationResult = inputSchema.safeParse(request.params.arguments)
        if (!validationResult.success) {
          throw new Error(`Invalid input: ${JSON.stringify(validationResult.error.errors)}`)
        }
    
        const {
          symbol,
          category = CONSTANTS.DEFAULT_CATEGORY as "spot" | "linear" | "inverse",
          limit = "25"
        } = validationResult.data
    
        this.logInfo(`Validated arguments - symbol: ${symbol}, category: ${category}, limit: ${limit}`)
    
        // Execute API request with rate limiting and retry logic
        const response = await this.executeRequest(async () => {
          const data = await this.getOrderbookData(symbol, category, limit)
          return data
        })
    
        // Format response
        const result = {
          symbol,
          category,
          limit: parseInt(limit, 10),
          asks: response.a,
          bids: response.b,
          timestamp: response.ts,
          updateId: response.u,
          meta: {
            requestId: crypto.randomUUID()
          }
        }
    
        this.logInfo(`Successfully retrieved orderbook data for ${symbol}`)
        return this.formatResponse(result)
      } catch (error) {
        this.logInfo(`Error in get_orderbook: ${error instanceof Error ? error.message : String(error)}`)
        return this.handleError(error)
      }
    }
  • Zod schema used for validating and parsing tool input parameters (symbol, category, limit).
    const inputSchema = z.object({
      symbol: z.string()
        .min(1, "Symbol is required")
        .regex(/^[A-Z0-9]+$/, "Symbol must contain only uppercase letters and numbers"),
      category: z.enum(["spot", "linear", "inverse"]).optional(),
      limit: z.union([
        z.enum(["1", "25", "50", "100", "200"]),
        z.number().transform(n => {
          const validLimits = [1, 25, 50, 100, 200]
          const closest = validLimits.reduce((prev, curr) =>
            Math.abs(curr - n) < Math.abs(prev - n) ? curr : prev
          )
          return String(closest)
        })
      ]).optional()
    })
  • MCP-compatible tool definition including name, description, and JSON input schema.
    toolDefinition: Tool = {
      name: this.name,
      description: "Get orderbook (market depth) data for a trading pair",
      inputSchema: {
        type: "object",
        properties: {
          symbol: {
            type: "string",
            description: "Trading pair symbol (e.g., 'BTCUSDT')",
            pattern: "^[A-Z0-9]+$"
          },
          category: {
            type: "string",
            description: "Category of the instrument (spot, linear, inverse)",
            enum: ["spot", "linear", "inverse"],
          },
          limit: {
            type: "string",
            description: "Limit for the number of bids and asks (1, 25, 50, 100, 200)",
            enum: ["1", "25", "50", "100", "200"],
          },
        },
        required: ["symbol"],
      },
    }
  • Helper method that constructs parameters and calls the Bybit API client to retrieve orderbook data.
    private async getOrderbookData(
      symbol: string,
      category: "spot" | "linear" | "inverse",
      limit: string
    ): Promise<APIResponseV3WithTime<OrderbookData>> {
      const params: GetOrderbookParamsV5 = {
        category,
        symbol,
        limit: parseInt(limit, 10),
      }
      this.logInfo(`Fetching orderbook with params: ${JSON.stringify(params)}`)
      return await this.client.getOrderbook(params)
    }
  • Dynamic registration loader that discovers, imports, instantiates, and validates all tool classes from the src/tools directory, including GetOrderbook.
    export async function loadTools(): Promise<BaseToolImplementation[]> {
      try {
        const toolsPath = await findToolsPath()
        const files = await fs.readdir(toolsPath)
        const tools: BaseToolImplementation[] = []
    
        for (const file of files) {
          if (!isToolFile(file)) {
            continue
          }
    
          try {
            const modulePath = `file://${join(toolsPath, file)}`
            const { default: ToolClass } = await import(modulePath)
    
            if (!ToolClass || typeof ToolClass !== 'function') {
              console.warn(JSON.stringify({
                type: "warning",
                message: `Invalid tool class in ${file}`
              }))
              continue
            }
    
            const tool = new ToolClass()
    
            if (
              tool instanceof BaseToolImplementation &&
              tool.name &&
              tool.toolDefinition &&
              typeof tool.toolCall === "function"
            ) {
              tools.push(tool)
              console.info(JSON.stringify({
                type: "info",
                message: `Loaded tool: ${tool.name}`
              }))
            } else {
              console.warn(JSON.stringify({
                type: "warning",
                message: `Invalid tool implementation in ${file}`
              }))
            }
          } catch (error) {
            console.error(JSON.stringify({
              type: "error",
              message: `Error loading tool from ${file}: ${error instanceof Error ? error.message : String(error)}`
            }))
          }
        }
    
        return tools
      } catch (error) {
        console.error(JSON.stringify({
          type: "error",
          message: `Failed to load tools: ${error instanceof Error ? error.message : String(error)}`
        }))
        return []
      }
    }
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 what the tool does but lacks critical details such as whether this is a read-only operation, potential rate limits, authentication requirements, or the format of the returned data. This is inadequate for a tool that likely interacts with financial markets.

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 immediately conveys the tool's purpose without unnecessary words. It's appropriately sized and front-loaded, making it easy for an agent to parse quickly.

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 market data tools and the absence of both annotations and an output schema, the description is insufficient. It doesn't explain what the returned orderbook data looks like, potential limitations, or error conditions, leaving significant gaps for an agent to understand the tool's behavior.

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, providing clear details for all three parameters (symbol, category, limit) including enums and patterns. The description adds no additional parameter semantics beyond what's in the schema, so it meets the baseline score of 3 for high schema 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 verb ('Get') and resource ('orderbook (market depth) data for a trading pair'), making the purpose immediately understandable. It distinguishes this tool from siblings like get_ticker or get_trades by specifying market depth data, though it doesn't explicitly contrast with similar tools like get_market_structure.

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 scenarios where orderbook data is needed over other market data tools like get_ticker or get_market_info, nor does it specify prerequisites or exclusions for usage.

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

Related 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/sammcj/bybit-mcp'

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