Skip to main content
Glama
sammcj

Bybit MCP Server

by sammcj

get_wallet_balance

Retrieve wallet balance details for a Bybit account by specifying account type and cryptocurrency. Use this tool to access real-time balance information for UNIFIED, CONTRACT, or SPOT accounts.

Instructions

Get wallet balance information for the authenticated user

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
accountTypeYesAccount type
coinNoCryptocurrency symbol, e.g., BTC, ETH, USDT. If not specified, returns all coins.

Implementation Reference

  • The toolCall method implements the core logic of the get_wallet_balance tool: validates input, fetches wallet balance from Bybit API using this.client.getWalletBalance, handles errors, and formats the response.
    async toolCall(request: z.infer<typeof CallToolRequestSchema>) {
      try {
        this.logInfo("Starting get_wallet_balance tool call")
    
        if (this.isDevMode) {
          throw new Error("Cannot get wallet balance in development mode - API credentials required")
        }
    
        // Parse and validate input
        const validationResult = inputSchema.safeParse(request.params.arguments)
        if (!validationResult.success) {
          const errorDetails = validationResult.error.errors.map(err => ({
            field: err.path.join('.'),
            message: err.message,
            code: err.code
          }))
          throw new Error(`Invalid input: ${JSON.stringify(errorDetails)}`)
        }
    
        const { accountType, coin } = validationResult.data
        this.logInfo(`Validated arguments - accountType: ${accountType}${coin ? `, coin: ${coin}` : ''}`)
    
        // Execute API request with rate limiting and retry logic
        const response = await this.executeRequest(async () => {
          return await this.getWalletData(accountType, coin)
        })
    
        // Format response
        const result: FormattedWalletResponse = {
          accountType,
          coin,
          data: {
            list: response.list
          },
          timestamp: new Date().toISOString(),
          meta: {
            requestId: crypto.randomUUID()
          }
        }
    
        this.logInfo(`Successfully retrieved wallet balance for ${accountType}${coin ? ` (${coin})` : ''}`)
        return this.formatResponse(result)
      } catch (error) {
        this.logInfo(`Error in get_wallet_balance: ${error instanceof Error ? error.message : String(error)}`)
        return this.handleError(error)
      }
    }
  • MCP Tool definition including name, description, and JSON input schema for get_wallet_balance.
    toolDefinition: Tool = {
      name: this.name,
      description: "Get wallet balance information for the authenticated user",
      inputSchema: {
        type: "object",
        properties: {
          accountType: {
            type: "string",
            description: "Account type",
            enum: ["UNIFIED", "CONTRACT", "SPOT"],
          },
          coin: {
            type: "string",
            description: "Cryptocurrency symbol, e.g., BTC, ETH, USDT. If not specified, returns all coins.",
          },
        },
        required: ["accountType"],
      },
    }
  • Zod schema used internally for validating tool input parameters.
    const inputSchema = z.object({
      accountType: z.enum(["UNIFIED", "CONTRACT", "SPOT"]),
      coin: z.string().optional()
    })
  • Dynamically loads all tool implementations from src/tools/ directory by importing and instantiating classes like GetWalletBalance, validating they are valid tools, and returning an array of instances. This registers get_wallet_balance among others.
    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 []
      }
    }
  • src/index.ts:134-151 (registration)
    In the main server startup, calls loadTools() to get tool instances including get_wallet_balance, creates a map by name, and uses it in MCP request handlers for listing and calling tools.
    const tools = await loadTools()
    toolsMap = createToolsMap(tools)
    
    if (tools.length === 0) {
      console.log(JSON.stringify(formatJsonRpcMessage(
        "warning",
        "No tools were loaded. Server will start but may have limited functionality."
      )))
    } else {
      console.log(JSON.stringify(formatJsonRpcMessage(
        "info",
        `Loaded ${tools.length} tools: ${tools.map(t => t.name).join(", ")}`
      )))
    }
    
    const transport = new StdioServerTransport()
    await server.connect(transport)
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. While it implies a read operation ('Get'), it doesn't specify authentication requirements beyond 'authenticated user', rate limits, error conditions, or what the return format looks like. For a financial data tool with zero annotation coverage, this is insufficient.

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 communicates the core purpose without unnecessary words. It's appropriately sized for a simple retrieval tool and front-loads the essential information.

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 absence of both annotations and an output schema, the description is incomplete. It doesn't explain what balance information is returned (e.g., available balance, locked balance, total balance) or the response format. For a financial tool with no structured behavioral or output documentation, this leaves significant gaps.

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 schema has 100% description coverage, so parameters are well-documented in the structured schema. The description adds no additional parameter information beyond what's already in the schema (accountType with enum values, coin with default behavior). This meets the baseline 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 action ('Get') and resource ('wallet balance information') with the scope ('for the authenticated user'), making the purpose immediately understandable. However, it doesn't differentiate this tool from potential sibling wallet-related tools (though none are listed in the provided siblings).

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 any prerequisites, constraints, or relationships with the sibling tools (which appear to be market data and trading tools rather than direct alternatives).

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